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/rtcrtpsender | data/mdn-content/files/en-us/web/api/rtcrtpsender/setstreams/index.md | ---
title: "RTCRtpSender: setStreams() method"
short-title: setStreams()
slug: Web/API/RTCRtpSender/setStreams
page-type: web-api-instance-method
browser-compat: api.RTCRtpSender.setStreams
---
{{DefaultAPISidebar("WebRTC API")}}
The {{domxref("RTCRtpSender")}} method **`setStreams()`** associates the sender's {{domxref("RTCRtpSender.track", "track")}} with the specified {{domxref("MediaStream")}} objects.
## Syntax
```js-nolint
setStreams()
setStreams(mediaStream1)
setStreams(mediaStream1, mediaStream2)
setStreams(mediaStream1, mediaStream2, /* …, */ mediaStreamN)
```
### Parameters
- `mediaStreamN` {{optional_inline}}
- : An arbitrary number of {{domxref("MediaStream")}} objects specified as arguments, that identify the streams to which the `RTCRtpSender`'s {{domxref("RTCRtpSender.track", "track")}} belongs.
If this parameter isn't specified, no new streams will be associated with the track.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the sender's connection is closed.
## Description
`setStreams()` is purely additive. It doesn't remove the track from any streams; it adds it to new ones.
If you specify streams to which the track already belongs, that stream is unaffected.
Once the track has been added to all of the streams, renegotiation of the connection will be triggered by the {{domxref("RTCPeerConnection.negotiationneeded_event", "negotiationneeded")}} event being dispatched to the {{domxref("RTCPeerConnection")}} to which the sender belongs.
## Examples
This example adds all of an {{domxref("RTCPeerConnection")}}'s tracks to the specified stream.
```js
function addTracksToStream(stream) {
let senders = pc.getSenders();
senders.forEach((sender) => {
if (sender.track && sender.transport.state === connected) {
sender.setStreams(stream);
}
});
}
```
After calling the {{domxref("RTCPeerConnection")}} method {{domxref("RTCPeerConnection.getSenders", "getSenders()")}} to get the list of the connection's senders, the `addTracksToStream()` function iterates over the list.
For each sender, if the sender's track is non-null and its transport's state is `connected`, we call `setStreams()` to add the track to the `stream` specified.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcrtpsender | data/mdn-content/files/en-us/web/api/rtcrtpsender/track/index.md | ---
title: "RTCRtpSender: track property"
short-title: track
slug: Web/API/RTCRtpSender/track
page-type: web-api-instance-property
browser-compat: api.RTCRtpSender.track
---
{{APIRef("WebRTC")}}
The **`track`** read-only property of
the {{domxref("RTCRtpSender")}} interface returns the {{domxref("MediaStreamTrack")}}
which is being handled by the `RTCRtpSender`.
## Value
A {{domxref("MediaStreamTrack")}} object representing the media associated with the
`RTCRtpSender`. If no track is associated with the sender, this value is
`null`, in which case the sender transmits nothing.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcrtpsender | data/mdn-content/files/en-us/web/api/rtcrtpsender/getparameters/index.md | ---
title: "RTCRtpSender: getParameters() method"
short-title: getParameters()
slug: Web/API/RTCRtpSender/getParameters
page-type: web-api-instance-method
browser-compat: api.RTCRtpSender.getParameters
---
{{DefaultAPISidebar("WebRTC")}}
The **`getParameters()`** method of the {{domxref("RTCRtpSender")}} interface returns an object describing the current configuration for how the sender's {{domxref("RTCRtpSender.track", "track")}} will be encoded and transmitted to a remote {{domxref("RTCRtpReceiver")}}.
## Syntax
```js-nolint
getParameters()
```
### Parameters
None.
### Return value
An object indicating the current configuration of the sender. <!-- RTCRtpSendParameters, derived from RTCRtpParameters -->
<!-- spec defines following in RTCRtpSendParameters -->
- `encodings`
- : An array of objects, each specifying the parameters and settings for a single codec that could be used to encode the track's media.
The properties of the objects include:
- `active`
- : `true` (the default) if the encoding is being sent, `false` if it is not being sent or used.
- `dtx` {{Deprecated_Inline}} {{Non-standard_Inline}}
- : Only used for an {{domxref("RTCRtpSender")}} whose {{domxref("MediaStreamTrack.kind", "kind")}} is `audio`, this property indicates whether or not discontinuous transmission is being used (a feature by which a phone is turned off or the microphone muted automatically in the absence of voice activity).
The value is taken either `enabled` or `disabled`.
- `maxBitrate`
- : A positive integer indicating the maximum number of bits per second that the user agent is allowed to grant to tracks encoded with this encoding.
Other parameters may further constrain the bit rate, such as the value of `maxFramerate`, or the bandwidth available for the transport or physical network.
The value is computed using the standard Transport Independent Application Specific Maximum (TIAS) bandwidth as defined by {{RFC(3890, "", "6.2.2")}}; this is the maximum bandwidth needed without considering protocol overheads from IP, TCP or UDP, and so forth.
Note that the bitrate can be achieved in a number of ways, depending on the media and encoding.
For example, for video a low bit rate might be achieved by dropping frames (a bitrate of zero might allow just one frame to be sent), while for audio the track might have to stop playing if the bitrate is too low for it to be sent.
- `maxFramerate`
- : A value specifying the maximum number of frames per second to allow for this encoding.
- `priority`
- : A string indicating the priority of the {{domxref("RTCRtpSender")}}, which may determine how the user agent allocates bandwidth between senders.
Allowed values are `very-low`, `low` (default), `medium`, `high`.
- `rid`
- : A string which, if set, specifies an _RTP stream ID_ (_RID_) to be sent using the RID header extension.
This parameter cannot be modified using {{domxref("RTCRtpSender.setParameters", "setParameters()")}}.
Its value can only be set when the transceiver is first created.
- `scaleResolutionDownBy`
- : Only used for senders whose track's {{domxref("MediaStreamTrack.kind", "kind")}} is `video`, this is a floating-point value specifying a factor by which to scale down the video during encoding.
The default value, 1.0, means that the video will be encoded at its original size.
A value of 2.0 scales the video frames down by a factor of 2 in each dimension, resulting in a video 1/4 the size of the original.
The value must not be less than 1.0 (attempting to scale the video to a larger size will throw a {{jsxref("RangeError")}}).
- `transactionId`
- : A string containing a unique ID.
This value is used to ensure that {{domxref("RTCRtpSender.setParameters", "setParameters()")}} can only be called to modify the parameters returned by a specific previous call to `getParameters()`.
This parameter cannot be changed by the caller.
<!-- spec defines following in RTCRtpParameters -->
- `codecs`
- : An array of {{domxref("RTCRtpCodecParameters")}} objects describing the set of codecs from which the sender or receiver will choose.
This parameter cannot be changed once initially set.
- `headerExtensions`
- : An array of zero or more RTP header extensions, each identifying an extension supported by the sender or receiver. Header extensions are described in {{RFC(3550, "", "5.3.1")}}.
This parameter cannot be changed once initially set.
- `rtcp`
- : An {{domxref("RTCRtcpParameters")}} object providing the configuration parameters used for {{Glossary("RTCP")}} on the sender or receiver.
This parameter cannot be changed once initially set.
- `degradationPreference` {{deprecated_inline}} {{optional_inline}} <!-- removed from spec. May have been or be in chrome -->
- : Specifies the preferred way the WebRTC layer should handle optimizing bandwidth against quality in constrained-bandwidth situations.
The possible values are `maintain-framerate`, `maintain-resolution`, or `balanced`.
The default value is `balanced`.
## Examples
This example gets the sender's current transaction ID; the transaction ID uniquely identifies the current set of parameters, to ensure that calls to {{domxref("RTCRtpSender.setParameters", "setParameters()")}} are always handled in the correct order, avoiding inadvertently overwriting parameters with older parameters.
```js
function getSenderTransactionID(sender) {
let parameters = sender.getParameters();
return parameters.transactionId;
}
```
In the same, way, this code gets the canonical name (CNAME) being used for {{Glossary("RTCP")}} on an {{domxref("RTCRtpSender")}}.
```js
function getRtpCNAME(sender) {
let parameters = sender.getParameters();
return parameters.rtcp.cname;
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("RTCRtpSender.setParameters()")}}
- {{domxref("RTCRtpReceiver.getParameters()")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcrtpsender | data/mdn-content/files/en-us/web/api/rtcrtpsender/transport/index.md | ---
title: "RTCRtpSender: transport property"
short-title: transport
slug: Web/API/RTCRtpSender/transport
page-type: web-api-instance-property
browser-compat: api.RTCRtpSender.transport
---
{{DefaultAPISidebar("WebRTC")}}
The read-only **`transport`** property of an
{{domxref("RTCRtpSender")}} object provides the {{domxref("RTCDtlsTransport")}} object
used to interact with the underlying transport over which the sender is exchanging
Real-time Transport Control Protocol ({{Glossary("RTCP")}}) packets.
This transport is responsible for receiving the data for the media on the sender's
{{domxref("RTCRtpReceiver.track", "track")}}.
## Value
An {{domxref("RTCDtlsTransport")}} object representing the underlying transport being
used by the sender to exchange packets with the remote peer, or `null` if the
sender isn't yet connected to a transport.
## Description
When the `RTCRtpSender` is first created, the value of
`transport` is `null`. This is replaced with an
`RTCDtlsTransport` once the sender's transport has been established.
Note that when bundling is in effect—that is, when the {{domxref("RTCPeerConnection")}}
was created with a configuration object whose `bundlePolicy` is `max-compat`
or `max-bundle`—multiple senders may be sharing the same transport; in this
case, all of them are using the same connection to transmit and/or receive
{{Glossary("RTP")}} and {{Glossary("RTCP")}} packets.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcrtpsender | data/mdn-content/files/en-us/web/api/rtcrtpsender/dtmf/index.md | ---
title: "RTCRtpSender: dtmf property"
short-title: dtmf
slug: Web/API/RTCRtpSender/dtmf
page-type: web-api-instance-property
browser-compat: api.RTCRtpSender.dtmf
---
{{APIRef("WebRTC")}}
The read-only **`dtmf`** property on the
**{{domxref("RTCRtpSender")}}** interface returns a
{{domxref("RTCDTMFSender")}} object which can be used to send {{Glossary("DTMF")}} tones
over the {{domxref("RTCPeerConnection")}}. See [Using DTMF](/en-US/docs/Web/API/WebRTC_API/Using_DTMF) for details on how to
make use of the returned `RTCDTMFSender` object.
## Value
An {{domxref("RTCDTMFSender")}} which can be used to send DTMF over the RTP session, or
`null` if the track being carried by the RTP session or the
{{domxref("RTCPeerConnection")}} as a whole doesn't support DTMF.
> **Note:** Only audio tracks can support DTMF, and typically only one audio track per
> `RTCPeerConnection` will have an associated {{domxref("RTCDTMFSender")}}
## Example
tbd
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
- [Using DTMF with WebRTC](/en-US/docs/Web/API/WebRTC_API/Using_DTMF)
- {{domxref("RTCPeerConnection")}}
- {{domxref("RTCDTMFSender")}}
- {{domxref("RTCRtpSender")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/gpuvalidationerror/index.md | ---
title: GPUValidationError
slug: Web/API/GPUValidationError
page-type: web-api-interface
status:
- experimental
browser-compat: api.GPUValidationError
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`GPUValidationError`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} describes an application error indicating that an operation did not pass the WebGPU API's validation constraints.
It represents one of the types of errors surfaced by {{domxref("GPUDevice.popErrorScope")}} and the {{domxref("GPUDevice.uncapturederror_event", "uncapturederror")}} event.
Validation errors occur whenever invalid inputs are given to a WebGPU call. These are consistent, predictable, and should not occur provided your app is well-formed. They will occur in the same way on every device your code runs on, so once you've fixed any errors that show up during development you probably don't need to observe them directly most of the time. An exception to that rule is if you're consuming user-supplied assets, shaders, etc., in which case watching for validation errors while loading could be helpful.
> **Note:** We have attempted to provide useful information to help you understand why validation errors are occurring in your WebGPU code in "Validation" sections where appropriate, which list criteria to meet to avoid validation errors. See for example the [`GPUDevice.createBindGroup()` Validation section](/en-US/docs/Web/API/GPUDevice/createBindGroup#validation).
{{InheritanceDiagram}}
## Constructor
- {{domxref("GPUValidationError.GPUValidationError", "GPUValidationError()")}} {{Experimental_Inline}}
- : Creates a new `GPUValidationError` object instance.
## Instance properties
The `message` property is inherited from its parent, {{domxref("GPUError")}}:
- {{domxref("GPUError.message", "message")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : A string providing a human-readable message that explains why the error occurred.
## Examples
The following example uses an error scope to capture a suspected validation error, logging it to the console.
```js
device.pushErrorScope("validation");
let sampler = device.createSampler({
maxAnisotropy: 0, // Invalid, maxAnisotropy must be at least 1.
});
device.popErrorScope().then((error) => {
if (error) {
// error is a GPUValidationError object instance
sampler = null;
console.error(`An error occurred while creating sampler: ${error.message}`);
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
- [WebGPU Error Handling best practices](https://toji.dev/webgpu-best-practices/error-handling)
| 0 |
data/mdn-content/files/en-us/web/api/gpuvalidationerror | data/mdn-content/files/en-us/web/api/gpuvalidationerror/gpuvalidationerror/index.md | ---
title: "GPUValidationError: GPUValidationError() constructor"
short-title: GPUValidationError()
slug: Web/API/GPUValidationError/GPUValidationError
page-type: web-api-constructor
status:
- experimental
browser-compat: api.GPUValidationError.GPUValidationError
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`GPUValidationError()`** constructor creates a new
{{domxref("GPUValidationError")}} object instance.
## Syntax
```js-nolint
new GPUValidationError(message)
```
### Parameters
- `message`
- : A string providing a human-readable message that explains why the error occurred.
## Examples
A developer would not manually use the constructor to create a `GPUValidationError` object. The user agent uses this constructor to create an appropriate object when a validation error is surfaced by {{domxref("GPUDevice.popErrorScope")}} or the {{domxref("GPUDevice.uncapturederror_event", "uncapturederror")}} event.
See the main [`GPUValidationError`](/en-US/docs/Web/API/GPUValidationError#examples) page for a specific example involving a `GPUValidationError` object instance.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
- [WebGPU Error Handling best practices](https://toji.dev/webgpu-best-practices/error-handling)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/credentialscontainer/index.md | ---
title: CredentialsContainer
slug: Web/API/CredentialsContainer
page-type: web-api-interface
browser-compat: api.CredentialsContainer
---
{{APIRef("Credential Management API")}}{{securecontext_header}}
The **`CredentialsContainer`** interface of the [Credential Management API](/en-US/docs/Web/API/Credential_Management_API) exposes methods to request credentials and notify the user agent when events such as successful sign in or sign out happen. This interface is accessible from {{domxref('Navigator.credentials')}}.
## Instance properties
None.
## Instance methods
- {{domxref("CredentialsContainer.create()")}}
- : Returns a {{jsxref("Promise")}} that resolves with a new {{domxref("Credential")}} instance based on the provided options, or `null` if no `Credential` object can be created. In exceptional circumstances, the {{jsxref("Promise")}} may reject.
- {{domxref("CredentialsContainer.get()")}}
- : Returns a {{jsxref("Promise")}} that resolves with the {{domxref("Credential")}} instance that matches the provided parameters.
- {{domxref("CredentialsContainer.preventSilentAccess()")}}
- : Sets a flag that specifies whether automatic log in is allowed for future visits to the current origin, then returns an empty {{jsxref("Promise")}}. For example, you might call this, after a user signs out of a website to ensure that they aren't automatically signed in on the next site visit. Earlier versions of the spec called this method `requireUserMediation()`. See [Browser compatibility](#browser_compatibility) for support details.
- {{domxref("CredentialsContainer.store()")}}
- : Stores a set of credentials for a user, inside a provided {{domxref("Credential")}} instance and returns that instance in a {{jsxref("Promise")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/credentialscontainer | data/mdn-content/files/en-us/web/api/credentialscontainer/store/index.md | ---
title: "CredentialsContainer: store() method"
short-title: store()
slug: Web/API/CredentialsContainer/store
page-type: web-api-instance-method
browser-compat: api.CredentialsContainer.store
---
{{APIRef("Credential Management API")}}{{SecureContext_Header}}
The **`store()`** method of the
{{domxref("CredentialsContainer")}} stores a set of credentials for the user inside a
{{domxref("Credential")}} instance, returning this in a {{jsxref("Promise")}}.
> **Note:** This method is restricted to top-level contexts. Calls to it within an
> `<iframe>` element will resolve without effect.
## Syntax
```js-nolint
store(credentials)
```
### Parameters
- `credentials`
- : A valid {{domxref("Credential")}} instance.
### Return value
A {{jsxref("Promise")}} that resolves to `undefined`.
### Exceptions
- `NotAllowedError` {{domxref("DOMException")}}
- : Thrown if there is also a credential of the same type as the current one under operation.
## Examples
### Storing a password credential at successful authentication
This code would be executed after a user signs up or logs in and the server confirms
the credential is correct.
```js
// Check if the browser supports password credentials (and the Credential Management API)
if ("PasswordCredential" in window) {
let credential = new PasswordCredential({
id: "example-username",
name: "Carina Anand", // In case of a login, the name comes from the server.
password: "correct horse battery staple",
});
navigator.credentials.store(credential).then(
() => {
console.info("Credential stored in the user agent's credential manager.");
},
(err) => {
console.error("Error while storing the credential: ", err);
},
);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/credentialscontainer | data/mdn-content/files/en-us/web/api/credentialscontainer/get/index.md | ---
title: "CredentialsContainer: get() method"
short-title: get()
slug: Web/API/CredentialsContainer/get
page-type: web-api-instance-method
browser-compat: api.CredentialsContainer.get
---
{{APIRef("Credential Management API")}}{{SecureContext_Header}}
The **`get()`** method of the {{domxref("CredentialsContainer")}} interface returns a {{jsxref("Promise")}} that fulfills with a single credential instance that matches the provided parameters, which the browser can then use to authenticate with a relying party. This is used by several different credential-related APIs with significantly different purposes:
- The [Credential Management API](/en-US/docs/Web/API/Credential_Management_API) uses `get()` to authenticate using basic federated credentials or username/password credentials.
- The [Web Authentication API](/en-US/docs/Web/API/Web_Authentication_API) uses `get()` to authenticate or provide additional factors during MFA with public key credentials (based on asymmetric cryptography).
- The [Federated Credential Management (FedCM) API](/en-US/docs/Web/API/FedCM_API) uses `get()` to authenticate with federated identity providers (IdPs).
- The [WebOTP API](/en-US/docs/Web/API/WebOTP_API) uses `get()` to request retrieval of a one-time password (OTP) from a specially-formatted SMS message sent by an app server.
The below reference page starts with a syntax section that explains the general method call structure and parameters that apply to all the different APIs. After that, it is split into separate sections providing parameters, return values, and examples specific to each API.
## General syntax
```js-nolint
get()
get(options)
```
### Parameters
- `options` {{optional_inline}}
- : An object that contains options for the request. The options include criteria that the credentials are required or allowed to have, and options for interacting with the user. It can contain the following properties:
- "Credential type"
- : An object or boolean defining the type of credential being requested — this can be one of:
- `federated`: An object containing requirements for a requested credential from a federated identify provider. Bear in mind that the Federated Credential Management API (the `identity` credential type) supersedes this credential type. See the [Credential Management API](#credential_management_api) section below for more details.
- `password`: A boolean value indicating that a password credential is being requested. See the [Credential Management API](#credential_management_api) section below for more details.
- `identity`: An object containing details of federated identity providers (IdPs) that a relying party (RP) website can use for purposes such as signing in or signing up on a website. It causes the `get()` call to initiate a request for a user to sign in to an RP with an IdP. See the [Federated Credential Management API](#federated_credential_management_api) section below for more details.
- `otp`: An object containing transport type hints. Causes the `get()` call to initiate a request for the retrieval of an OTP. See the [WebOTP API](#webotp_api) section below for more details.
- `publicKey`: An object containing requirements for returned public key credentials. Causes the `get()` call to use an existing set of public key credentials to authenticate to a relying party. See the [Web Authentication API](#web_authentication_api) section below for more details.
- `mediation` {{optional_inline}}
- : A string indicating whether the user will be required to login for every visit to a client app. The value can be one of the following:
- `"conditional"`: Discovered credentials are presented to the user in a non-modal dialog box along with an indication of the origin requesting credentials. In practice, this means autofilling available credentials; see [Sign in with a passkey through form autofill](https://web.dev/articles/passkey-form-autofill) for more details of how this is used; {{domxref("PublicKeyCredential.isConditionalMediationAvailable()")}} also provides some useful information.
- `"optional"`: If credentials can be handed over for a given operation without user mediation, they will be, enabling automatic reauthentication without user mediation. If user mediation is required, then the user agent will ask the user to authenticate. This value is intended for situations where you have reasonable confidence that a user won't be surprised or confused at seeing a login dialog box — for example on a site that doesn't automatically log users in, when a user has just clicked a "Login/Signup" button.
- `"required"`: The user will always be asked to authenticate, even if prevent silent access (see {{domxref("CredentialsContainer.preventSilentAccess()")}}) is set to `false`. This value is intended for situations where you want to force user authentication — for example if you want a user to reauthenticate when a sensitive operation is being performed (like confirming a credit card payment), or when switching users.
- `"silent"`: The user will not be asked to authenticate. The user agent will automatically reauthenticate the user and log them in if possible. If consent is required, the promise will fulfill with `null`. This value is intended for situations where you would want to automatically sign a user in upon visiting a web app if possible, but if not, you don't want to present them with a confusing login dialog box. Instead, you'd want to wait for them to explicitly click a "Login/Signup" button.
If `mediation` is omitted, it will default to `"optional"`.
> **Note:** In the case of a federated authentication (FedCM API) request, a `mediation` value of `optional` or `silent` may result in attempted [auto-reauthentication](/en-US/docs/Web/API/FedCM_API/RP_sign-in#auto-reauthentication). Whether this occurred is communicated to the IdP (via the [`is_auto_selected`](/en-US/docs/Web/API/FedCM_API/IDP_integration#is_auto_selected) parameter sent to the IdP's `id_assertion_endpoint` during validation) and the RP (via the {{domxref("IdentityCredential.isAutoSelected")}} property). This is useful for performance evaluation, security requirements (the IdP may wish to reject automatic reauthentication requests and always require user mediation), and general UX (an IdP or RP may wish to present different UX for auto and non-auto login experiences).
- `signal` {{optional_inline}}
- : An {{domxref("AbortSignal")}} object instance that allows an ongoing `get()` operation to be aborted. An aborted operation may complete normally (generally if the abort was received after the operation finished) or reject with an "`AbortError`" {{domxref("DOMException")}}.
## Credential Management API
The [Credential Management API](/en-US/docs/Web/API/Credential_Management_API) lets a website store and retrieve password and federated credentials. These capabilities allow users to sign in without typing passwords, see the federated account they used to sign in to a site, and resume a session without the explicit sign-in flow of an expired session.
### `federated` object structure
`federated` will contain the following properties:
- `protocols`
- : An array of strings representing the protocols of the requested credentials' federated identity providers (for example, `"openidconnect"`).
- `providers`
- : An array of strings representing the credentials' federated identity providers (for example `"https://www.facebook.com"` or `"https://accounts.google.com"`).
### `password` boolean value
`password` is a single boolean value. If set to `true`, it indicates that the requested credential is a password credential.
### Return value
A {{jsxref("Promise")}} that resolves with a {{domxref("Credential")}} instance matching the provided parameters:
- If the provided credential type was a `federated` object, the returned instance will be a {{domxref("FederatedCredential")}}.
- If the provided credential type was a `password` boolean value of `true`, the returned instance will be a {{domxref("PasswordCredential")}}.
If a single credential cannot be unambiguously obtained, the Promise will resolve to `null`.
### Examples
```js
navigator.credentials
.get({
federated: {
protocols: ["openidconnect"],
providers: ["https://www.facebook.com", "https://accounts.google.com"],
},
})
.then((fedCred) => {
console.log(fedCred.provider);
});
```
## Federated Credential Management API
The [Federated Credential Management (FedCM) API](/en-US/docs/Web/API/FedCM_API) provides a standard mechanism for identity providers (IdPs) to enable identity federation services in a privacy-preserving way without relying on third-party cookies and redirects. This includes a JavaScript API that enables the use of federated authentication for purposes such as signing in or signing up to a website. For more usage information, check out the linked landing page for the API.
Relying parties (RPs) can call `get()` with an `identity` option to request that a user signs in to the RP with an existing IdP account that they are already signed in to on the browser.
> **Note:** Usage of `get()` with the `identity` parameter may be blocked by an {{httpheader("Permissions-Policy/identity-credentials-get", "identity-credentials-get")}} [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy) set on your server.
### `identity` object structure
`identity` can contain the following properties:
- `context` {{optional_inline}}
- : An enumerated value specifying the context in which the user is authenticating with FedCM. The browser uses this value to vary the text in its FedCM UI to better suit the context. Possible values are:
- `continue`: Suitable for situations where the user is choosing an identity to continue to the next page in the flow, which requires a sign-in. Browsers will provide a text string similar to "Continue to \<page-origin\> with \<IdP\>".
- `signin`: Suitable for general situations where the user is signing in with an IdP account they've already used on this origin. Browsers will provide a text string similar to "Sign in to \<page-origin\> with \<IdP\>". This is the default value.
- `signup`: An option for situations where the user is signing in to the origin with a new IdP account they've not used here before. Browsers will provide a text string similar to "Sign up to \<page-origin\> with \<IdP\>".
- `use`: Suitable for situations where a different action, such as validating a payment, is being performed. Browsers will provide a text string similar to "Use \<page-origin\> with \<IdP\>".
- `providers`
- : An array containing a single object specifying details of an IdP to be used to sign in. This object can contain the following properties:
- `configURL`
- : A string specifying the URL of the IdP's config file. See [Provide a config file](/en-US/docs/Web/API/FedCM_API/IDP_integration#provide_a_config_file_and_endpoints) for more information.
- `clientId`
- : A string specifying the RP's client identifier. This information is issued by the IdP to the RP in a separate process that is specific to the IdP.
- `loginHint` {{optional_inline}}
- : A string providing a hint about the account option(s) the browser should provide for the user to sign in with. This is useful in cases where the user has already signed in and the site asks them to reauthenticate. Otherwise, the reauthentication process can be confusing when a user has multiple accounts and can't remember which one they used to sign in previously. The value for the `loginHint` property can be taken from the user's previous sign-in, and is matched against the `login_hints` values provided by the IdP in the array of user information returned from the IdP's [accounts list endpoint](/en-US/docs/Web/API/FedCM_API/IDP_integration#the_accounts_list_endpoint).
- `nonce` {{optional_inline}}
- : A random string that can be included to ensure the response is issued specifically for this request and prevent {{glossary("replay attack", "replay attacks")}}.
> **Note:** Currently FedCM only allows the API to be invoked with a single IdP, i.e. the `identity.providers` array has to have a length of 1. Multiple IdPs must be supported via different `get()` calls.
### Return value
A {{jsxref("Promise")}} that resolves with an {{domxref("IdentityCredential")}} instance matching the provided parameters if the user identity is successfully validated by the IdP.
This object contains a token that includes user identity information that has been signed with the IdP's {{glossary("digital certificate")}}.
The RP sends the token to its server to validate the certificate, and on success can use the (now trusted) identity information in the token to sign them into their service (starting a new session), sign them up to their service if they are a new user, etc.
If the `get()` method's promise rejects, the RP can direct the user to the IdP login page to sign in or create an account.
> **Note:** The exact nature of the token is opaque to the FedCM API, and to the browser. The IdP decides on the syntax and usage of it, and the RP needs to follow the instructions provided by the IdP (see [Verify the Google ID token on your server side](https://developers.google.com/identity/gsi/web/guides/verify-google-id-token), for example) to make sure they are using it correctly.
### Exceptions
- `IdentityCredentialError` {{domxref("DOMException")}}
- : The request to the [ID assertion endpoint](/en-US/docs/Web/API/FedCM_API/IDP_integration#the_id_assertion_endpoint) is unable to validate the authentication, and rejects with an error response containing information about why. See the [Error API example](#example_including_error_api_information) below for more information on how it can be used.
- `NetworkError` {{domxref("DOMException")}}
- : The IdP did not respond within 60 seconds, the provided credentials were not valid/found, or the browser's login status for the IdP is set to `"logged-out"` (see [Update login status using the Login Status API](/en-US/docs/Web/API/FedCM_API/IDP_integration#update_login_status_using_the_login_status_api) for more information about FedCM login status). In the latter case, there may be some delay in the rejection to avoid leaking the IdP login status to the RP.
- `NotAllowedError` {{domxref("DOMException")}}
- : Use of this feature was blocked by an {{HTTPHeader("Permissions-Policy/identity-credentials-get","identity-credentials-get")}} [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy).
### Examples
#### Basic example
Relying parties can call `get()` with the `identity` option to make a request for users to sign in to the relying party via an identity provider (IdP), using identity federation. A typical request would look like this:
```js
async function signIn() {
const identityCredential = await navigator.credentials.get({
identity: {
providers: [
{
configURL: "https://accounts.idp.example/config.json",
clientId: "********",
nonce: "******",
},
],
},
});
}
```
Check out [Federated Credential Management (FedCM) API](/en-US/docs/Web/API/FedCM_API) for more details on how this works. This call will start off the sign-in flow described in [FedCM sign-in flow](/en-US/docs/Web/API/FedCM_API/RP_sign-in#fedcm_sign-in_flow).
#### Example including context and login hint
A similar call including the `context` and `loginHint` extensions would look like so:
```js
async function signIn() {
const identityCredential = await navigator.credentials.get({
identity: {
context: "signup",
providers: [
{
configURL: "https://accounts.idp.example/config.json",
clientId: "********",
nonce: "******",
loginHint: "[email protected]",
},
],
},
});
}
```
> **Note:** After a user has signed in with an IdP, the IdP can call the static {{domxref("IdentityProvider.getUserInfo_static", "IdentityProvider.getUserInfo()")}} method to retrieve their details. `getUserInfo()` must be called from within an IdP-origin {{htmlelement("iframe")}} to ensure that RP scripts cannot access the data. This information can then be used to display a personalized welcome message and sign-in button. This approach is already common on sites that use identity federation for sign-in. However, `getUserInfo()` offers a way to achieve this without relying on third-party cookies.
#### Example including Error API information
If the IdP is unable to validate the authentication for a request to the [ID assertion endpoint](/en-US/docs/Web/API/FedCM_API/IDP_integration#the_id_assertion_endpoint) it will respond with an error.
The error may be handled in code as shown:
```js
async function signIn() {
try {
const identityCredential = await navigator.credentials.get({
identity: {
providers: [
{
configURL: "https://accounts.idp.example/config.json",
clientId: "********",
nonce: "******",
},
],
},
});
} catch (e) {
// Handle the error in some way, for example provide information
// to help the user succeed in a future sign-in attempt
const code = e.code;
const url = e.url;
}
}
```
## WebOTP API
The [WebOTP API](/en-US/docs/Web/API/WebOTP_API) lets a web client request an OTP from an SMS sent by the web app's server. This capability is intended to streamline usage of OTPs in web apps, for example when using phone numbers as additional factors in sign-in flows. The OTP is retrieved from the SMS and can be set as a verification input value automatically after the user gives consent, avoiding the need for the user to manually go into their SMS app and copy and paste it.
### `otp` object structure
`otp` will contain the following properties:
- `transport`
- : An array of strings representing transport hints for how the OTP should ideally be transmitted. This will always contain a single hint — `"sms"`. Unknown values will be ignored.
### Return value
A {{jsxref("Promise")}} that resolves with an {{domxref("OTPCredential")}} object instance.
### Exceptions
- `AbortError` {{domxref("DOMException")}}
- : The `get()` operation is associated with an {{domxref("AbortSignal")}} (i.e., set in the `signal` property) that has already been aborted.
- `SecurityError` {{domxref("DOMException")}}
- : Either the usage is blocked by a {{HTTPHeader("Permissions-Policy/otp-credentials","otp-credentials")}} [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy) or the calling domain is not a valid domain.
### Examples
The below code triggers the browser's permission flow when an SMS message arrives. If permission is granted, then the promise resolves with an `OTPCredential` object. The contained `code` value is then set as the value of an {{htmlelement("input")}} form element, which is then submitted.
```js
navigator.credentials
.get({
otp: { transport: ["sms"] },
signal: ac.signal,
})
.then((otp) => {
input.value = otp.code;
if (form) form.submit();
})
.catch((err) => {
console.error(err);
});
```
> **Note:** For a full explanation of the code, see the {{domxref('WebOTP API','','',' ')}} landing page. You can also [see this code as part of a full working demo](https://web-otp.glitch.me/).
## Web Authentication API
The [Web Authentication API](/en-US/docs/Web/API/Web_Authentication_API) enables strong authentication with public key cryptography, enabling passwordless authentication and/or secure multi-authentication (MFA) without SMS texts. Check out the linked API landing page for more usage information.
> **Note:** Usage of `get()` with the `publicKey` parameter may be blocked by a {{HTTPHeader("Permissions-Policy/publickey-credentials-get","publickey-credentials-get")}} [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy) set on your server.
### `publicKey` object structure
`publicKey` can contain the following properties:
- `allowCredentials` {{optional_inline}}
- : An array of objects defining a restricted list of the acceptable credentials for retrieval. Each object will contain the following properties:
- `id`
- : An {{jsxref("ArrayBuffer")}}, {{jsxref("TypedArray")}}, or {{jsxref("DataView")}} representing the ID of the public key credential to retrieve. This value is mirrored by the {{domxref("PublicKeyCredential.rawId", "rawId")}} property of the {{domxref("PublicKeyCredential")}} object returned by a successful `get()` call.
- `transports`
- : An array of strings providing hints as to the methods the client could use to communicate with the relevant authenticator of the public key credential to retrieve. Possible transports are: `"ble"`, `"hybrid"`, `"internal"`, `"nfc"`, and `"usb"`.
> **Note:** This value is mirrored by the return value of the {{domxref("AuthenticatorAttestationResponse.getTransports", "PublicKeyCredential.response.getTransports()")}} method of the {{domxref("PublicKeyCredential")}} object returned by the `create()` call that originally created the credential.
> At that point, it should be stored by the app for later use.
- `type`
- : A string defining the type of the public key credential to retrieve. This can currently take a single value, `"public-key"`, but more values may be added in the future. This value is mirrored by the {{domxref("Credential.type", "type")}} property of the {{domxref("PublicKeyCredential")}} object returned by a successful `get()` call.
If `allowCredentials` is omitted, it will default to an empty array, meaning that any credential is potentially acceptable for retrieval without the relying party first providing an ID.
- `attestation` {{optional_inline}}
- : A string specifying the relying party's preference for how the attestation statement (i.e., provision of verifiable evidence of the authenticity of the authenticator and its data) is conveyed during authentication. The value can be one of the following:
- `"none"`
- : Specifies that the relying party is not interested in authenticator attestation. This might be to avoid additional user consent for round trips to the relying party server to relay identifying information, or round trips to an attestation certificate authority (CA), with the aim of making the authentication process smoother. If `"none"` is chosen as the `attestation` value, and the authenticator signals that it uses a CA to generate its attestation statement, the client app will replace it with a "None" attestation statement, indicating that no attestation statement is available.
- `"direct"`
- : Specifies that the relying party wants to receive the attestation statement as generated by the authenticator.
- `"enterprise"`
- : Specifies that the relying party wants to receive an attestation statement that may include uniquely identifying information. This is intended for controlled deployments within an enterprise where the organization wishes to tie registrations to specific authenticators.
- `"indirect"`
- : Specifies that the relying party wants to receive a verifiable attestation statement, but it will allow the client to decide how to receive it. For example, the client could choose to replace the authenticator's assertion statement with one generated by an anonymization CA to protect user privacy.
If `attestation` is omitted, it will default to `"none"`.
- `attestationFormats` {{optional_inline}}
- : An array of strings specifying the relying party's preference for the attestation statement format used by the authenticator. Values should be ordered from highest to lowest preference, and should be considered hints — the authenticator may choose to issue an attestation statement in a different format. For a list of valid formats, see [WebAuthn Attestation Statement Format Identifiers](https://www.iana.org/assignments/webauthn/webauthn.xhtml#webauthn-attestation-statement-format-ids).
If omitted, `attestationFormats` defaults to an empty array.
- `challenge`
- : An {{jsxref("ArrayBuffer")}}, {{jsxref("TypedArray")}}, or {{jsxref("DataView")}} originating from the relying party's server and used as a [cryptographic challenge](https://en.wikipedia.org/wiki/Challenge%E2%80%93response_authentication). This value will be signed by the authenticator and the signature will be sent back as part of the {{domxref("AuthenticatorAssertionResponse.signature")}} (available in the {{domxref("PublicKeyCredential.response", "response")}} property of the {{domxref("PublicKeyCredential")}} object returned by a successful `get()` call).
- `extensions` {{optional_inline}}
- : An object containing properties representing the input values for any requested extensions. These extensions are used to specific additional processing by the client or authenticator during the authentication process. Examples include dealing with legacy FIDO API credentials, and evaluating outputs from a pseudo-random function (PRF) associated with a credential.
Extensions are optional and different browsers may recognize different extensions. Processing extensions is always optional for the client: if a browser does not recognize a given extension, it will just ignore it. For information on using extensions, and which ones are supported by which browsers, see [Web Authentication extensions](/en-US/docs/Web/API/Web_Authentication_API/WebAuthn_extensions).
- `rpId` {{optional_inline}}
- : A string that specifies the relying party's identifier (for example `"login.example.org"`). For security purposes:
- The calling web app verifies that `rpId` matches the relying party's origin.
- The authenticator verifies that `rpId` matches the `rpId` of the credential used for the authentication ceremony.
If `rpId` is omitted, it will default to the current origin's domain.
- `timeout` {{optional_inline}}
- : A numerical hint, in milliseconds, indicating the time the relying party is willing to wait for the retrieval operation to complete. This hint may be overridden by the browser.
- `userVerification` {{optional_inline}}
- : A string specifying the relying party's requirements for user verification of the authentication process. This verification is initiated by the authenticator, which will request the user to provide an available factor (for example a PIN or a biometric input of some kind).
The value can be one of the following:
- `"required"`
- : The relying party requires user verification, and the operation will fail if it does not occur.
- `"preferred"`
- : The relying party prefers user verification if possible, but the operation will not fail if it does not occur.
- `"discouraged"`
- : The relying party does not want user verification, in the interests of making user interaction as smooth as possible.
If `userVerification` is omitted, it will default to `"preferred"`.
- `hints` {{optional_inline}}
- : An array of strings providing hints as to what authentication UI the user-agent should provide for the user.
The values can be any of the following:
- `"security-key"`
- : Authentication requires a separate dedicated physical device to provide the key.
- `"client-device"`
- : The user authenticates using their own device, such as a phone.
- `"hybrid"`
- : Authentication relies on a combination of authorization/authentication methods, potentially relying on both user and server-based mechanisms.
### Return value
A {{jsxref("Promise")}} that resolves with an {{domxref("PublicKeyCredential")}} instance matching the provided parameters. If a single credential cannot be unambiguously obtained, the Promise will resolve to `null`.
### Exceptions
- `NotAllowedError` {{domxref("DOMException")}}
- : Usage was blocked by a {{HTTPHeader("Permissions-Policy/publickey-credentials-get","publickey-credentials-get")}} [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy).
### Examples
The following snippet shows a typical `get()` call with the WebAuthn `publicKey` option:
```js
const publicKey = {
challenge: new Uint8Array([139, 66, 181, 87, 7, 203, ...]),
rpId: "acme.com",
allowCredentials: [{
type: "public-key",
id: new Uint8Array([64, 66, 25, 78, 168, 226, 174, ...])
}],
userVerification: "required",
}
navigator.credentials.get({ publicKey })
```
A successful `get()` call returns a promise that resolves with a {{domxref("PublicKeyCredential")}} object instance, representing a public key credential previously created via a WebAuthn {{domxref("CredentialsContainer.create()", "create()")}} that has now been used to authenticate a user. Its {{domxref("PublicKeyCredential.response")}} property contains an {{domxref("AuthenticatorAssertionResponse")}} object providing access to several useful pieces of information including the authenticator data, signature, and user handle.
```js
navigator.credentials.get({ publicKey }).then((publicKeyCredential) => {
const response = publicKeyCredential.response;
// Access authenticator data ArrayBuffer
const authenticatorData = response.authenticatorData;
// Access client JSON
const clientJSON = response.clientDataJSON;
// Access signature ArrayBuffer
const signature = response.signature;
// Access userHandle ArrayBuffer
const userHandle = response.userHandle;
});
```
Some of this data will need to be stored on the server — for example the `signature` to provide proof that authenticator possesses the genuine private key used to create the credential, and the `userHandle` to link the user with the credential, sign in attempt, and other data.
> **Note:** See [Authenticating a user](/en-US/docs/Web/API/Web_Authentication_API#authenticating_a_user) for more information about how the overall flow works.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/credentialscontainer | data/mdn-content/files/en-us/web/api/credentialscontainer/create/index.md | ---
title: "CredentialsContainer: create() method"
short-title: create()
slug: Web/API/CredentialsContainer/create
page-type: web-api-instance-method
browser-compat: api.CredentialsContainer.create
---
{{APIRef("Credential Management API")}}{{SecureContext_Header}}
The **`create()`** method of the {{domxref("CredentialsContainer")}} interface returns a {{jsxref("Promise")}} that resolves with a new credential instance based on the provided options, the information from which can then be stored and later used to authenticate users via {{domxref("CredentialsContainer.get", "navigator.credentials.get()")}}.
This is used by multiple different credential-related APIs with significantly different purposes:
- The [Credential Management API](/en-US/docs/Web/API/Credential_Management_API) uses `create()` to create basic federated credentials or username/password credentials.
- The [Web Authentication API](/en-US/docs/Web/API/Web_Authentication_API) uses `create()` to create public key credentials (based on asymmetric cryptography).
The below reference page starts with a syntax section that explains the general method call structure and parameters that apply to all the different APIs. After that, it is split into separate sections providing parameters, return values, and examples specific to each API.
> **Note:** This method is restricted to top-level {{glossary("browsing context", "browsing contexts")}} (i.e., a document running directly inside a browser tab, and not embedded inside another document). Calls to it from within an `<iframe>` element will resolve without effect.
## General syntax
```js-nolint
create()
create(options)
```
### Parameters
- `options` {{optional_inline}}
- : An object that contains options for the requested new `Credentials` object. It can contain the following properties:
- A _credential type_
- : An object defining the type of credential being requested — this can be one of one of:
- `federated`
- : An object containing requirements for creating a federated identify provider credential. Bear in mind that the [Federated Credential Management API (FedCM)](/en-US/docs/Web/API/FedCM_API) supersedes this credential type. See the [Credential Management API](#credential_management_api) section below for more details.
- `password`
- : An object containing requirements for creating a password credential. See the [Credential Management API](#credential_management_api) section below for more details.
- `publicKey`
- : An object containing requirements for creating a public key credential. Causes the `create()` call to request that the user agent creates new credentials via an authenticator — either for registering a new account or for associating a new asymmetric key pair with an existing account. See the [Web Authentication API](#web_authentication_api) section below for more details.
- `signal` {{optional_inline}}
- : An {{domxref("AbortSignal")}} object instance that allows an ongoing `create()` operation to be aborted. An aborted operation may complete normally (generally if the abort was received after the operation finished) or reject with an "`AbortError`" {{domxref("DOMException")}}.
## Credential Management API
The [Credential Management API](/en-US/docs/Web/API/Credential_Management_API) lets a website store and retrieve password and federated credentials. These capabilities allow users to sign in without typing passwords, see the federated account they used to sign in to a site, and resume a session without the explicit sign-in flow of an expired session.
### `federated` object structure
`federated` can contain the following properties:
- `iconURL` {{optional_inline}}
- : A string representing the URL of an icon or avatar to be associated with the credential.
- `id`
- : A string representing a unique ID for the credential.
- `name` {{optional_inline}}
- : A string representing the credential username.
- `origin`
- : A string representing the credential's origin. {{domxref("FederatedCredential")}} objects are origin-bound, which means that they will only be usable on the specified origin they were intended to be used on.
- `protocol` {{optional_inline}}
- : A string representing the protocol of the credentials' federated identity provider (for example, `"openidconnect"`).
- `provider`
- : A string representing the credentials' federated identity provider (for example `"https://www.facebook.com"` or `"https://accounts.google.com"`).
### `password` object structure
A `password` object can be a reference to an object literal or an {{domxref("HTMLFormElement")}}. In both cases, they need to provide the following data:
- `iconURL` {{optional_inline}}
- : A string representing the URL of an icon or avatar to be associated with the credential.
- `id`
- : A string representing a unique ID for the credential.
- `name` {{optional_inline}}
- : A string representing the credential username.
- `origin`
- : A string representing the credential's origin. {{domxref("PasswordCredential")}} objects are origin-bound, which means that they will only be usable on the specified origin they were intended to be used on.
- `password`
- : A string representing the credential password.
In the case of the string literal, the properties are provided as-is. In the case of the {{domxref("HTMLFormElement")}}, the values need to be provided in form input fields (this can include {{htmlelement("input")}}, {{htmlelement("select")}}, or {{htmlelement("textarea")}} elements) with the following `name` attribute values:
- `id`: `"username"`
- `name`: `"name"` or `"nickname"`
- `iconURL`: `"photo"`
- `password`: `"new-password"` or `"current-password"`
The exception to this is `origin` — this is set to the origin of the document the {{domxref("HTMLFormElement")}} is contained within.
### Return value
A {{jsxref("Promise")}} that resolves with a {{domxref("Credential")}} instance matching the provided parameters:
- If the created credential type was a `federated` object, the returned instance will be a {{domxref("FederatedCredential")}}.
- If the created credential type was a `password` object, the returned instance will be a {{domxref("PasswordCredential")}}.
If a single credential cannot be successfully created, the Promise will resolve to `null`.
### Exceptions
- {{jsxref("TypeError")}}
- : In the case of a {{domxref("PasswordCredential")}} creation request, `id`, `origin`, or `password` were not provided (empty).
### Examples
```js
navigator.credentials
.create({
password: {
id: "ergnjregoith5y9865jhokmfdskl;vmfdl;kfd...",
name: "fluffybunny",
origin: "example.com",
password: "fluffyhaxx0r",
},
})
.then((pwdCred) => {
console.log(pwdCred.name);
});
```
## Web Authentication API
The [Web Authentication API](/en-US/docs/Web/API/Web_Authentication_API) enables strong authentication with public key cryptography, enabling passwordless authentication and/or secure multi-authentication (MFA) without SMS texts. Check out the linked API landing page for more usage information.
> **Note:** Usage of `create()` with the `publicKey` parameter may be blocked by a {{HTTPHeader("Permissions-Policy/publickey-credentials-create","publickey-credentials-create")}} [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy) set on your server.
### `publicKey` object structure
The `publicKey` object can contain the following properties:
- `attestation` {{optional_inline}}
- : A string specifying the relying party's preference for how the attestation statement (i.e., provision of verifiable evidence of the authenticity of the authenticator and its data) is conveyed during credential creation. The value can be one of the following:
- `"none"`
- : Specifies that the relying party is not interested in authenticator attestation. This might be to avoid additional user consent for round trips to the relying party server to relay identifying information, or round trips to an attestation certificate authority (CA), with the aim of making the authentication process smoother. If `"none"` is chosen as the `attestation` value, and the authenticator signals that it uses a CA to generate its attestation statement, the client app will replace it with a "None" attestation statement, indicating that no attestation statement is available.
- `"direct"`
- : Specifies that the relying party wants to receive the attestation statement as generated by the authenticator.
- `"enterprise"`
- : Specifies that the Relying Party wants to receive an attestation statement that may include uniquely identifying information. This is intended for controlled deployments within an enterprise where the organization wishes to tie registrations to specific authenticators.
- `"indirect"`
- : Specifies that the relying party wants to receive a verifiable attestation statement, but it will allow the client to decide how to receive it. For example, the client could choose to replace the authenticator's assertion statement with one generated by an Anonymization CA to protect user privacy.
If `attestation` is omitted, it will default to `"none"`.
- `attestationFormats` {{optional_inline}}
- : An array of strings specifying the relying party's preference for the attestation statement format used by the authenticator. Values should be ordered from highest to lowest preference, and should be considered hints — the authenticator may choose to issue an attestation statement in a different format. For a list of valid formats, see [WebAuthn Attestation Statement Format Identifiers](https://www.iana.org/assignments/webauthn/webauthn.xhtml#webauthn-attestation-statement-format-ids).
If omitted, `attestationFormats` defaults to an empty array.
- `authenticatorSelection` {{optional_inline}}
- : An object whose properties are criteria used to filter out the potential authenticators for the credential creation operation. This object can contain the properties:
- `authenticatorAttachment` {{optional_inline}}
- : A string indicating which authenticator attachment type should be permitted for the chosen authenticator. Possible values are:
- `"platform"`
- : The authenticator is part of the device WebAuthn is running on (termed a **platform authenticator**), therefore WebAuthn will communicate with it using a transport available to that platform, such as a platform-specific API. A public key credential bound to a platform authenticator is called a **platform credential**.
- `"cross-platform"`
- : The authenticator is not a part of the device WebAuthn is running on (termed a **roaming authenticator** as it can roam between different devices), therefore WebAuthn will communicate with it using a cross-platform transport protocol such as Bluetooth or NFC. A public key credential bound to a roaming authenticator is called a **roaming credential**.
If omitted, any type of authenticator, either platform or cross-platform, can be selected for the credential creation operation.
- `requireResidentKey` {{optional_inline}}
- : A boolean. If set to `true`, it indicates that a resident key is required (see `residentKey`) This property is deprecated, but still available in some implementations for backwards compatibility with WebAuthn Level 1. The value should be set to `true` if `residentKey` is set to `"required"`.
If omitted, `requireResidentKey` defaults to `false`.
- `residentKey` {{optional_inline}}
- : A string that specifies the extent to which the relying party desires to create a **client-side discoverable credential** (i.e., one that is usable in authentication requests where the relying party does not provide credential IDs — {{domxref("CredentialsContainer.get()", "navigator.credentials.get()")}} is called with an empty `allowCredentials` value). The alternative is a **server-side credential**, where the relying party must provide credential IDs in the `get()` `allowCredentials` value.
Possible values are:
- `"discouraged"`
- : The relying party prefers creation of a server-side credential, but will accept a client-side discoverable credential.
- `"preferred"`
- : The relying party strongly prefers creation of a client-side discoverable credential, but will accept a server-side credential. The user agent should guide the user through setting up user verification, if needed, to create a discoverable credential. This takes precedence over the `userVerification` setting.
- `"required"`
- : The relying party requires a client-side discoverable credential. If one cannot be created, an error is thrown.
If omitted, `residentKey` defaults to `"required"` if `requireResidentKey` is `true`, otherwise the default value is `"discouraged"`.
- `userVerification` {{optional_inline}}
- : A string that specifies the relying party's requirements for user verification for the `create()` operation. Possible values are:
- `"discouraged"`
- : The relying party prefers no user verification for the `create()` operation, in the interests of minimizing disruption to the user experience.
- `"preferred"`
- : The relying party prefers user verification for the `create()` operation, but it will not fail if user verification cannot be performed.
- `"required"`
- : The relying party requires user verification for the `create()` operation — if user verification cannot be performed, an error is thrown.
If omitted, `userVerification` defaults to `"preferred"`.
- `challenge`
- : An {{jsxref("ArrayBuffer")}}, {{jsxref("TypedArray")}}, or {{jsxref("DataView")}} provided by the relying party's server and used as a [cryptographic challenge](https://en.wikipedia.org/wiki/Challenge%E2%80%93response_authentication). This value will be signed by the authenticator and the signature will be sent back as part of {{domxref("AuthenticatorAttestationResponse.attestationObject")}}.
- `excludeCredentials` {{optional_inline}}
- : An {{jsxref("Array")}} of objects describing existing credentials that are already mapped to this user account (as identified by `user.id`). This is provided by the relying party, and checked by the user agent to avoid creating a new public key credential on an authenticator that already has a credential mapped to the specified user account. for an existing user who already has some. Each item should be of the form:
- `id`
- : An {{jsxref("ArrayBuffer")}}, {{jsxref("TypedArray")}}, or {{jsxref("DataView")}} representing the existing credential ID.
- `transports` {{optional_inline}}
- : An {{jsxref("Array")}} of strings representing allowed transports. Possible transports are: `"ble"`, `"hybrid"`, `"internal"`, `"nfc"`, and `"usb"` (see {{domxref("AuthenticatorAttestationResponse.getTransports", "getTransports()")}} for more details).
- `type`
- : A string defining the type of public key credential to create. This can currently take a single value, `"public-key"`, but more values may be added in the future.
If the `create()` call is attempting to create a duplicate public key credential on an authenticator, the user agent will guide to user to create the credential using a different authenticator, or fail if that is not possible.
If `excludeCredentials` is omitted, it defaults to an empty array.
- `extensions` {{optional_inline}}
- : An object containing properties representing the input values for any requested extensions. These extensions are used to specific additional processing by the client or authenticator during the credential creation process. Examples include specifying whether a returned credential is discoverable, or whether the relying party will be able to store large blob data associated with a credential.
Extensions are optional and different browsers may recognize different extensions. Processing extensions is always optional for the client: if a browser does not recognize a given extension, it will just ignore it. For information on using extensions, and which ones are supported by which browsers, see [Web Authentication extensions](/en-US/docs/Web/API/Web_Authentication_API/WebAuthn_extensions).
- `pubKeyCredParams`
- : An {{jsxref("Array")}} of objects which specify the key types and signature algorithms the Relying Party supports, ordered from most preferred to least preferred. The client and authenticator will make a best-effort to create a credential of the most preferred type possible. These objects will contain the following properties:
- `alg`
- : A number that is equal to a [COSE Algorithm Identifier](https://www.iana.org/assignments/cose/cose.xhtml#algorithms), representing the cryptographic algorithm to use for this credential type. It is recommended that relying parties that wish to support a wide range of authenticators should include at least the following values in the provided choices:
- `-8`: Ed25519
- `-7`: ES256
- `-257`: RS256
- `type`
- : A string defining the type of public key credential to create. This can currently take a single value, `"public-key"`, but more values may be added in the future.
If none of the listed credential types can be created, the `create()` operation fails.
- `rp`
- : An object describing the relying party that requested the credential creation. It can contain the following properties:
- `id` {{optional_inline}}
- : A string representing the ID of the relying party. A public key credential can only be used for authentication with the same relying party (as identified by the `publicKey.rpId` in a {{domxref("CredentialsContainer.get()", "navigator.credentials.get()")}} call) it was registered with — the IDs need to match.
The `id` cannot include a port or scheme like a standard origin, but the domain scheme must be `https` scheme. The `id` needs to equal the origin's effective domain, or a domain suffix thereof. So for example if the relying party's origin is `https://login.example.com:1337`, the following `id`s are valid:
- `login.example.com`
- `example.com`
But not:
- `m.login.example.com`
- `com`
If omitted, `id` defaults to the document origin — which would be `login.example.com` in the above example.
- `name`
- : A string representing the name of the relying party (e.g. `"Facebook"`). This is the name the user will be presented with when creating or validating a WebAuthn operation.
- `timeout` {{optional_inline}}
- : A numerical hint, in milliseconds, which indicates the time the calling web app is willing to wait for the creation operation to complete. This hint may be overridden by the browser.
- `user`
- : An object describing the user account for which the credential is generated. It can contain the following properties:
- `displayName`
- : A string providing a human-friendly user display name (example: `"John Doe"`), which will have been set by user during initial registration with the relying party.
- `id`
- : An {{jsxref("ArrayBuffer")}}, {{jsxref("TypedArray")}}, or {{jsxref("DataView")}} representing a unique ID for the user account. This value has a maximum length of 64 bytes, and is not intended to be displayed to the user.
- `name`
- : A string providing a human-friendly identifier for the user's account, to help distinguish between different accounts with similar `displayName`s. This could be an email address (such as `"[email protected]"`), phone number (for example `"+12345678901"`), or some other kind of user account identifier (for example `"johndoe667"`).
- `hints` {{optional_inline}}
- : An array of strings providing hints as to what authentication UI the user-agent should provide for the user.
The values can be any of the following:
- `"security-key"`
- : Authentication requires a separate dedicated physical device to provide the key.
- `"client-device"`
- : The user authenticates using their own device, such as a phone.
- `"hybrid"`
- : Authentication relies on a combination of authorization/authentication methods, potentially relying on both user and server-based mechanisms.
### Return value
A {{jsxref("Promise")}} that resolves with an {{domxref("PublicKeyCredential")}} instance matching the provided parameters. If no credential object can be created, the promise resolves with `null`.
### Exceptions
- `NotAllowedError` {{domxref("DOMException")}}
- : Possible causes include:
- Usage was blocked by a {{HTTPHeader("Permissions-Policy/publickey-credentials-create","publickey-credentials-create")}} [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy).
- The function is called cross-origin but the iframe's [`allow`](/en-US/docs/Web/HTML/Element/iframe#allow) attribute does not set an appropriate {{HTTPHeader("Permissions-Policy/publickey-credentials-create","publickey-credentials-create")}} policy.
- The function is called cross-origin and the `<iframe>` does not have {{glossary("transient activation")}}.
## Examples
The following snippet shows a typical `create()` call with the WebAuthn `publicKey` option:
```js
const publicKey = {
challenge: new Uint8Array([117, 61, 252, 231, 191, 241, ...]),
rp: { id: "acme.com", name: "ACME Corporation" },
user: {
id: new Uint8Array([79, 252, 83, 72, 214, 7, 89, 26]),
name: "jamiedoe",
displayName: "Jamie Doe"
},
pubKeyCredParams: [ {type: "public-key", alg: -7} ]
}
navigator.credentials.create({ publicKey })
```
A successful `create()` call returns a promise that resolves with a {{domxref("PublicKeyCredential")}} object instance, representing a public key credential that can later be used to authenticate a user via a WebAuthn {{domxref("CredentialsContainer.get()", "get()")}} call. Its {{domxref("PublicKeyCredential.response")}} property contains an {{domxref("AuthenticatorAttestationResponse")}} object providing access to several useful pieces of information including the authenticator data, public key, transport mechanisms, and more.
```js
navigator.credentials.create({ publicKey }).then((publicKeyCredential) => {
const response = publicKeyCredential.response;
// Access attestationObject ArrayBuffer
const attestationObj = response.attestationObject;
// Access client JSON
const clientJSON = response.clientDataJSON;
// Return authenticator data ArrayBuffer
const authenticatorData = response.getAuthenticatorData();
// Return public key ArrayBuffer
const pk = response.getPublicKey();
// Return public key algorithm identifier
const pkAlgo = response.getPublicKeyAlgorithm();
// Return permissible transports array
const transports = response.getTransports();
});
```
Some of this data will need to be stored on the server for future authentication operations against this credential — for example the public key, the algorithm used, and the permissible transports.
> **Note:** See [Creating a key pair and registering a user](/en-US/docs/Web/API/Web_Authentication_API#creating_a_key_pair_and_registering_a_user) for more information about how the overall flow works.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/credentialscontainer | data/mdn-content/files/en-us/web/api/credentialscontainer/preventsilentaccess/index.md | ---
title: "CredentialsContainer: preventSilentAccess() method"
short-title: preventSilentAccess()
slug: Web/API/CredentialsContainer/preventSilentAccess
page-type: web-api-instance-method
browser-compat: api.CredentialsContainer.preventSilentAccess
---
{{APIRef("Credential Management API")}}{{SecureContext_Header}}
The **`preventSilentAccess()`** method of the {{domxref("CredentialsContainer")}} interface sets a flag that specifies whether automatic log in is allowed for future visits to the current origin, then returns a {{jsxref("Promise")}} that resolves to `undefined`.
For example, you might call this, after a user signs out of a website to ensure that they aren't automatically signed in on the next site visit.
Mediation varies by origin, and is an added check point of browser stored credentials, informing a user of an account login status. This method is typically called after a user signs out of a website, ensuring this user's login information is not automatically passed on the next site visit.
Earlier versions of the spec called this method `requireUserMediation()`.
The [Browser compatibility](/en-US/docs/Web/API/CredentialsContainer#browser_compatibility) section has support details.
## Syntax
```js-nolint
preventSilentAccess()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that resolves to `undefined`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/location/index.md | ---
title: Location
slug: Web/API/Location
page-type: web-api-interface
browser-compat: api.Location
---
{{APIRef("HTML DOM")}}
The **`Location`** interface represents the location (URL) of the object it is linked to. Changes done on it are reflected on the object it relates to. Both the {{domxref("Document")}} and {{domxref("Window")}} interface have such a linked `Location`, accessible via {{domxref("Document.location")}} and {{domxref("Window.location")}} respectively.
## Location anatomy
Hover over the URL segments below to highlight their meaning:
```html hidden
<span id="href" title="href"
><span id="origin" title="origin"
><span id="protocol" title="protocol">https:</span>//<span
id="host"
title="host"
><span id="hostname" title="hostname">example.org</span>:<span
id="port"
title="port"
>8080</span
></span
></span
><span id="pathname" title="pathname">/foo/bar</span
><span id="search" title="search">?q=baz</span
><span id="hash" title="hash">#bang</span></span
>
```
```css hidden
html {
display: table;
width: 100%;
}
body {
display: table-cell;
text-align: center;
vertical-align: middle;
font-family: Georgia;
font-size: 175%;
line-height: 1em;
white-space: nowrap;
}
[title] {
position: relative;
display: inline-block;
box-sizing: border-box;
line-height: 2em;
cursor: pointer;
color: gray;
}
[title]::before {
content: attr(title);
font-family: monospace;
position: absolute;
top: 100%;
width: 100%;
left: 50%;
margin-left: -50%;
font-size: 60%;
line-height: 1.5;
background: black;
}
[title]:hover::before,
:target::before {
background: black;
color: yellow;
}
[title] [title]::before {
margin-top: 1.5em;
}
[title] [title] [title]::before {
margin-top: 3em;
}
[title] [title] [title] [title]::before {
margin-top: 4.5em;
}
[title]:hover,
:target {
position: relative;
z-index: 1;
outline: 50em solid rgb(255 255 255 / 80%);
}
```
```js hidden
document.body.addEventListener("click", (event) => {
event.preventDefault();
window.location.hash = event.target.hasAttribute("id")
? `#${event.target.getAttribute("id")}`
: "";
});
```
{{EmbedLiveSample('Location anatomy', '85ch', '180px')}}
## Instance properties
- {{domxref("Location.ancestorOrigins")}} {{ReadOnlyInline}}
- : A static {{domxref("DOMStringList")}} containing, in reverse order, the origins of all ancestor browsing contexts of the document associated with the given `Location` object.
- {{domxref("Location.href")}}
- : A {{Glossary("stringifier")}} that returns a string containing the entire URL. If changed, the associated document navigates to the new page. It can be set from a different origin than the associated document.
- {{domxref("Location.protocol")}}
- : A string containing the protocol scheme of the URL, including the final `':'`.
- {{domxref("Location.host")}}
- : A string containing the host, that is the _hostname_, a `':'`, and the _port_ of the URL.
- {{domxref("Location.hostname")}}
- : A string containing the domain of the URL.
- {{domxref("Location.port")}}
- : A string containing the port number of the URL.
- {{domxref("Location.pathname")}}
- : A string containing an initial `'/'` followed by the path of the URL, not including the query string or fragment.
- {{domxref("Location.search")}}
- : A string containing a `'?'` followed by the parameters or "querystring" of the URL. Modern browsers provide [URLSearchParams](/en-US/docs/Web/API/URLSearchParams/get#examples) and [URL.searchParams](/en-US/docs/Web/API/URL/searchParams#examples) to make it easy to parse out the parameters from the querystring.
- {{domxref("Location.hash")}}
- : A string containing a `'#'` followed by the fragment identifier of the URL.
- {{domxref("Location.origin")}} {{ReadOnlyInline}}
- : Returns a string containing the canonical form of the origin of the specific location.
## Instance methods
- {{domxref("Location.assign()")}}
- : Loads the resource at the URL provided in parameter.
- {{domxref("Location.reload()")}}
- : Reloads the current URL, like the Refresh button.
- {{domxref("Location.replace()")}}
- : Replaces the current resource with the one at the provided URL (redirects to the provided URL). The difference from the `assign()` method and setting the `href` property is that after using `replace()` the current page will not be saved in session {{domxref("History")}}, meaning the user won't be able to use the _back_ button to navigate to it.
- {{domxref("Location.toString()")}}
- : Returns a string containing the whole URL. It is a synonym for {{domxref("Location.href")}}, though it can't be used to modify the value.
## Examples
```js
// location: https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container
const loc = document.location;
console.log(loc.href); // https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container
console.log(loc.protocol); // https:
console.log(loc.host); // developer.mozilla.org:8080
console.log(loc.hostname); // developer.mozilla.org
console.log(loc.port); // 8080
console.log(loc.pathname); // /en-US/search
console.log(loc.search); // ?q=URL
console.log(loc.hash); // #search-results-close-container
console.log(loc.origin); // https://developer.mozilla.org:8080
location.assign("http://another.site"); // load another page
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- Two `Location` properties: {{domxref("Window.location")}} and {{domxref("Document.location")}}.
- URL manipulation interfaces: {{domxref("URL")}} and {{domxref("URLSearchParams")}}.
| 0 |
data/mdn-content/files/en-us/web/api/location | data/mdn-content/files/en-us/web/api/location/origin/index.md | ---
title: "Location: origin property"
short-title: origin
slug: Web/API/Location/origin
page-type: web-api-instance-property
browser-compat: api.Location.origin
---
{{APIRef("Location")}}
The **`origin`** read-only property of
the {{domxref("Location")}} interface is a string containing the
Unicode serialization of the origin of the represented URL.
That is:
- for URL using the `http` or `https`, the scheme followed by
`'://'`, followed by the domain, followed by `':'`, followed by
the port (the default port, `80` and `443` respectively, if
explicitly specified);
- for URL using `file:` scheme, the value is browser dependent;
- for URL using the `blob:` scheme, the origin of the URL following
`blob:`. E.g `"blob:https://mozilla.org"` will have
`"https://mozilla.org".`
{{AvailableInWorkers}}
## Value
A string.
## Examples
```js
// On this page, returns the origin
const result = window.location.origin; // Returns:'https://developer.mozilla.org'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/location | data/mdn-content/files/en-us/web/api/location/tostring/index.md | ---
title: "Location: toString() method"
short-title: toString()
slug: Web/API/Location/toString
page-type: web-api-instance-method
browser-compat: api.Location.toString
---
{{ApiRef("Location")}}
The **`toString()`** {{Glossary("stringifier")}} method of the
{{domxref("Location")}} interface returns a string containing the
whole URL. It is a read-only version of {{domxref("Location.href")}}.
## Syntax
```js-nolint
toString()
```
### Parameters
None.
### Return value
A string representing the object's URL.
## Examples
```js
// Let's imagine this code is executed on https://example.com/path?search#hash
const result = window.location.toString(); // Returns: 'https://example.com/path?search#hash'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/location | data/mdn-content/files/en-us/web/api/location/ancestororigins/index.md | ---
title: "Location: ancestorOrigins property"
short-title: ancestorOrigins
slug: Web/API/Location/ancestorOrigins
page-type: web-api-instance-property
browser-compat: api.Location.ancestorOrigins
---
{{APIRef("Location")}}
The **`ancestorOrigins`** read-only
property of the {{domxref("Location")}} interface is a static
{{domxref("DOMStringList")}} containing, in reverse order, the origins of all ancestor
browsing contexts of the document associated with the given {{domxref("Location")}}
object.
You can use `location.ancestorOrigins` in the script for a document to
determine, for example, whenever the document is being framed by a site which you don't
expect it to be framed by. You can also use it to vary the behavior of the document
based on what site or list of sites is framing it.
## Value
A {{domxref("DOMStringList")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/location | data/mdn-content/files/en-us/web/api/location/reload/index.md | ---
title: "Location: reload() method"
short-title: reload()
slug: Web/API/Location/reload
page-type: web-api-instance-method
browser-compat: api.Location.reload
---
{{ APIRef("HTML DOM") }}
The **`reload()`** method of the {{DOMXref("Location")}} interface reloads the current URL, like the Refresh button.
## Syntax
```js-nolint
reload()
```
### Parameters
- `forceGet` {{non-standard_inline}}
- : Pass `true` to force a reload bypassing the cache. Defaults to `false`. Only supported in Firefox.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- `SecurityError` {{domxref("DOMException")}}
- : Thrown if the {{Glossary("origin")}} of the script calling the method is not the {{Glossary("Same-origin policy", "same origin")}} of the page originally described by the {{domxref("Location")}} object, mostly when the script is hosted on a different domain.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("Location")}} interface it belongs to.
- Similar methods: {{domxref("Location.assign()")}} and
{{domxref("Location.replace()")}}.
| 0 |
data/mdn-content/files/en-us/web/api/location | data/mdn-content/files/en-us/web/api/location/search/index.md | ---
title: "Location: search property"
short-title: search
slug: Web/API/Location/search
page-type: web-api-instance-property
browser-compat: api.Location.search
---
{{ApiRef("Location")}}
The **`search`** property of the {{domxref("Location")}}
interface is a search string, also called a _query string_; that is, a
string containing a `'?'` followed by the parameters of the
URL.
Modern browsers provide
[`URLSearchParams`](/en-US/docs/Web/API/URLSearchParams/get#examples)
and
[`URL.searchParams`](/en-US/docs/Web/API/URL/searchParams#examples)
to make it easy to parse out the parameters from the querystring.
## Value
A string.
## Examples
```js
// Let an <a id="myAnchor" href="/en-US/docs/Location.search?q=123"> element be in the document
const anchor = document.getElementById("myAnchor");
const queryString = anchor.search; // Returns:'?q=123'
// Further parsing:
const params = new URLSearchParams(queryString);
const q = parseInt(params.get("q")); // is the number 123
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/location | data/mdn-content/files/en-us/web/api/location/port/index.md | ---
title: "Location: port property"
short-title: port
slug: Web/API/Location/port
page-type: web-api-instance-property
browser-compat: api.Location.port
---
{{ApiRef("Location")}}
The **`port`** property of the {{domxref("Location")}}
interface is a string containing the port number of the URL. If the
URL does not contain an explicit port number, it will be set to `''`.
## Value
A string.
## Examples
```js
// Let's an <a id="myAnchor" href="https://developer.mozilla.org:443/en-US/docs/Location.port"> element be in the document
const anchor = document.getElementByID("myAnchor");
const result = anchor.port; // Returns:'443'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/location | data/mdn-content/files/en-us/web/api/location/hash/index.md | ---
title: "Location: hash property"
short-title: hash
slug: Web/API/Location/hash
page-type: web-api-instance-property
browser-compat: api.Location.hash
---
{{ APIRef("Location") }}
The **`hash`** property of the
{{domxref("Location")}} interface returns a string containing a
`'#'` followed by the fragment identifier of the URL — the ID on the page
that the URL is trying to target.
The fragment is not [URL decoded](https://en.wikipedia.org/wiki/URL_encoding). If the URL does not
have a fragment identifier, this property contains an empty string, `""`.
## Value
A string.
## Examples
```html
<a id="myAnchor" href="/en-US/docs/Location.href#Examples">Examples</a>
<script>
const anchor = document.getElementById("myAnchor");
console.log(anchor.hash); // Returns '#Examples'
</script>
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/location | data/mdn-content/files/en-us/web/api/location/pathname/index.md | ---
title: "Location: pathname property"
short-title: pathname
slug: Web/API/Location/pathname
page-type: web-api-instance-property
browser-compat: api.Location.pathname
---
{{ApiRef("Location")}}
The **`pathname`** property of the {{domxref("Location")}}
interface is a string containing the path of the URL for the location. If there is no path, `pathname` will be empty: otherwise, `pathname` contains an initial '/' followed by the path of the URL, not including the query string or fragment.
## Value
A string.
## Examples
```js
// Let's say we are on the URL https://developer.mozilla.org/en-US/docs/Web/API/Location/pathname#examples
console.log(location.pathname); // '/en-US/docs/Web/API/Location/pathname'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/location | data/mdn-content/files/en-us/web/api/location/assign/index.md | ---
title: "Location: assign() method"
short-title: assign()
slug: Web/API/Location/assign
page-type: web-api-instance-method
browser-compat: api.Location.assign
---
{{ APIRef("HTML DOM") }}
The **`assign()`** method of the {{DOMXref("Location")}}
interface causes the window to load
and display the document at the URL specified. After the navigation occurs, the user can
navigate back to the page that called `Location.assign()` by pressing the "back" button.
## Syntax
```js-nolint
assign(url)
```
### Parameters
- `url`
- : A string containing the URL of the page to navigate to; for example, an absolute URL such as `https://developer.mozilla.org/en-US/docs/Web/API/Location/reload`, or a relative URL — such as `"/Web` (just a path, for navigating to another document at the same origin) or `#specifications` (just a fragment string, for navigating to some part of the same page), and so on.
### Exceptions
- `SecurityError` {{domxref("DOMException")}}
- : Thrown if the {{Glossary("origin")}} of the script calling the method is not the {{Glossary("Same-origin policy", "same origin")}} of the page originally described by the {{domxref("Location")}} object, mostly when the script is hosted on a different domain.
- `SyntaxError` {{domxref("DOMException")}}
- : Thrown if the provided `url` parameter is not a valid URL.
### Return value
None ({{jsxref("undefined")}}).
## Examples
```js
// Navigate to the Location.reload article
window.location.assign(
"https://developer.mozilla.org/en-US/docs/Web/API/Location/reload",
);
// Then navigate to its Specifications section
window.location.assign("#specifications");
// Eventually navigate to https://developer.mozilla.org/en-US/docs/Web
window.location.assign("/Web");
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("Location")}} interface it belongs to.
- Similar methods: {{domxref("Location.replace()")}} and
{{domxref("Location.reload()")}}.
| 0 |
data/mdn-content/files/en-us/web/api/location | data/mdn-content/files/en-us/web/api/location/hostname/index.md | ---
title: "Location: hostname property"
short-title: hostname
slug: Web/API/Location/hostname
page-type: web-api-instance-property
browser-compat: api.Location.hostname
---
{{ApiRef("URL API")}}
The **`hostname`** property of the {{domxref("Location")}}
interface is a string containing the domain of the URL.
## Value
A string.
## Examples
```js
console.log(window.location.hostname);
// developer.mozilla.org
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/location | data/mdn-content/files/en-us/web/api/location/host/index.md | ---
title: "Location: host property"
short-title: host
slug: Web/API/Location/host
page-type: web-api-instance-property
browser-compat: api.Location.host
---
{{ApiRef("Location")}}
The **`host`** property of the {{domxref("Location")}}
interface is a string containing the host, that is the
_hostname_, and then, if the _port_ of the URL is nonempty, a
`':'`, and the _port_ of the URL.
## Value
A string.
## Examples
```js
const anchor = document.createElement("a");
anchor.href = "https://developer.mozilla.org/en-US/Location.host";
console.log(anchor.host === "developer.mozilla.org");
anchor.href = "https://developer.mozilla.org:443/en-US/Location.host";
console.log(anchor.host === "developer.mozilla.org");
// The port number is not included because 443 is the scheme's default port
anchor.href = "https://developer.mozilla.org:4097/en-US/Location.host";
console.log(anchor.host === "developer.mozilla.org:4097");
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/location | data/mdn-content/files/en-us/web/api/location/replace/index.md | ---
title: "Location: replace() method"
short-title: replace()
slug: Web/API/Location/replace
page-type: web-api-instance-method
browser-compat: api.Location.replace
---
{{ APIRef("HTML DOM") }}
The **`replace()`** method of the {{DOMXref("Location")}}
interface replaces the current resource with the one at the provided URL. The difference
from the {{domxref("Location.assign","assign()")}} method is that after using
`replace()` the current page will not be saved in session {{domxref("History")}},
meaning the user won't be able to use the _back_ button to navigate to it.
## Syntax
```js-nolint
replace(url)
```
### Parameters
- `url`
- : A string containing the URL of the page to navigate to.
### Exceptions
- `SyntaxError` {{domxref("DOMException")}}
- : Thrown if the provided `url` parameter is not a valid URL.
### Return value
None ({{jsxref("undefined")}}).
## Examples
```js
// Navigate to the Location.reload article by replacing this page
window.location.replace(
"https://developer.mozilla.org/en-US/docs/Web/API/Location.reload",
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("Location")}} interface it belongs to.
- Similar methods: {{domxref("Location.assign()")}} and
{{domxref("Location.reload()")}}.
| 0 |
data/mdn-content/files/en-us/web/api/location | data/mdn-content/files/en-us/web/api/location/href/index.md | ---
title: "Location: href property"
short-title: href
slug: Web/API/Location/href
page-type: web-api-instance-property
browser-compat: api.Location.href
---
{{ApiRef("Location")}}
The **`href`** property of the {{domxref("Location")}}
interface is a {{Glossary("stringifier")}} that returns a string containing the whole
URL, and allows the href to be updated.
Setting the value of `href` _navigates_ to the provided URL. If you
want _redirection_, use {{domxref("Location/replace","location.replace()")}}. The difference from setting the `href` property value is that when using the `location.replace()` method, after navigating to the given URL, the current page will not be saved in session [history](/en-US/docs/Web/API/History_API) — meaning the user won't be able to use the back button to navigate to it.
## Value
A string.
## Examples
```js
// Lets imagine an <a id="myAnchor" href="https://developer.mozilla.org/en-US/Location/href"> element is in the document
const anchor = document.getElementById("myAnchor");
const result = anchor.href; // Returns: 'https://developer.mozilla.org/en-US/Location/href'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/location | data/mdn-content/files/en-us/web/api/location/protocol/index.md | ---
title: "Location: protocol property"
short-title: protocol
slug: Web/API/Location/protocol
page-type: web-api-instance-property
browser-compat: api.Location.protocol
---
{{ApiRef("Location")}}
The **`protocol`** property of the {{domxref("Location")}}
interface is a string representing the protocol scheme of the URL,
including the final `':'`.
## Value
A string.
## Examples
```js
// Let's an <a id="myAnchor" href="https://developer.mozilla.org/en-US/Location.protocol"> element be in the document
const anchor = document.getElementById("myAnchor");
const result = anchor.protocol; // Returns:'https:'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/audionode/index.md | ---
title: AudioNode
slug: Web/API/AudioNode
page-type: web-api-interface
browser-compat: api.AudioNode
---
{{APIRef("Web Audio API")}}
The **`AudioNode`** interface is a generic interface for representing an audio processing module.
Examples include:
- an audio source (e.g. an HTML {{HTMLElement("audio")}} or {{HTMLElement("video")}} element, an {{domxref("OscillatorNode")}}, etc.),
- the audio destination,
- intermediate processing module (e.g. a filter like {{domxref("BiquadFilterNode")}} or {{domxref("ConvolverNode")}}), or
- volume control (like {{domxref("GainNode")}})
{{InheritanceDiagram}}
> **Note:** An `AudioNode` can be target of events, therefore it implements the {{domxref("EventTarget")}} interface.
## Instance properties
- {{domxref("AudioNode.context")}} {{ReadOnlyInline}}
- : Returns the associated {{domxref("BaseAudioContext")}}, that is the object representing the processing graph the node is participating in.
- {{domxref("AudioNode.numberOfInputs")}} {{ReadOnlyInline}}
- : Returns the number of inputs feeding the node. Source nodes are defined as nodes having a `numberOfInputs` property with a value of `0`.
- {{domxref("AudioNode.numberOfOutputs")}} {{ReadOnlyInline}}
- : Returns the number of outputs coming out of the node. Destination nodes — like {{ domxref("AudioDestinationNode") }} — have a value of `0` for this attribute.
- {{domxref("AudioNode.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. Its usage and precise definition depend on the value of {{domxref("AudioNode.channelCountMode")}}.
- {{domxref("AudioNode.channelCountMode")}}
- : Represents an enumerated value describing the way channels must be matched between the node's inputs and outputs.
- {{domxref("AudioNode.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"`.
## Instance methods
_Also implements methods from the interface_ {{domxref("EventTarget")}}.
- {{domxref("AudioNode.connect()")}}
- : Allows us to connect the output of this node to be input into another node, either as audio data or as the value of an {{domxref("AudioParam")}}.
- {{domxref("AudioNode.disconnect()")}}
- : Allows us to disconnect the current node from another one it is already connected to.
## Description
### The audio routing graph

Each `AudioNode` has inputs and outputs, and multiple audio nodes are connected to build a _processing graph_. This graph is contained in an {{domxref("AudioContext")}}, and each audio node can only belong to one audio context.
A _source node_ has zero inputs but one or multiple outputs, and can be used to generate sound. On the other hand, a _destination node_ has no outputs; instead, all its inputs are directly played back on the speakers (or whatever audio output device the audio context uses). In addition, there are _processing nodes_ which have inputs and outputs. The exact processing done varies from one `AudioNode` to another but, in general, a node reads its inputs, does some audio-related processing, and generates new values for its outputs, or lets the audio pass through (for example in the {{domxref("AnalyserNode")}}, where the result of the processing is accessed separately).
The more nodes in a graph, the higher the latency will be. For example, if your graph has a latency of 500ms, when the source node plays a sound, it will take half a second until that sound can be heard on your speakers (or even longer because of latency in the underlying audio device). Therefore, if you need to have interactive audio, keep the graph as small as possible, and put user-controlled audio nodes at the end of a graph. For example, a volume control (`GainNode`) should be the last node so that volume changes take immediate effect.
Each input and output has a given amount of _channels_. For example, mono audio has one channel, while stereo audio has two channels. The Web Audio API will up-mix or down-mix the number of channels as required; check the Web Audio spec for details.
For a list of all audio nodes, see the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) homepage.
### Creating an `AudioNode`
There are two ways to create an `AudioNode`: via the _constructor_ and via the _factory method_.
```js
// constructor
const analyserNode = new AnalyserNode(audioCtx, {
fftSize: 2048,
maxDecibels: -25,
minDecibels: -60,
smoothingTimeConstant: 0.5,
});
```
```js
// factory method
const analyserNode = audioCtx.createAnalyser();
analyserNode.fftSize = 2048;
analyserNode.maxDecibels = -25;
analyserNode.minDecibels = -60;
analyserNode.smoothingTimeConstant = 0.5;
```
You are free to use either constructors or factory methods, or mix both, however there are advantages to using the constructors:
- All parameters can be set during construction time and don't need to be set individually.
- You can [sub-class an audio node](https://github.com/WebAudio/web-audio-api/issues/251). While the actual processing is done internally by the browser and cannot be altered, you could write a wrapper around an audio node to provide custom properties and methods.
- Slightly better performance: In both Chrome and Firefox, the factory methods call the constructors internally.
_Brief history:_ The first version of the Web Audio spec only defined the factory methods. After a [design review in October 2013](https://github.com/WebAudio/web-audio-api/issues/250), it was decided to add constructors because they have numerous benefits over factory methods. The constructors were added to the spec from August to October 2016. Factory methods continue to be included in the spec and are not deprecated.
## Example
This simple snippet of code shows the creation of some audio nodes, and how the `AudioNode` properties and methods can be used. You can find examples of such usage on any of the examples linked to on the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) landing page (for example [Violent Theremin](https://github.com/mdn/webaudio-examples/tree/main/violent-theremin)).
```js
const audioCtx = new AudioContext();
const oscillator = new OscillatorNode(audioCtx);
const gainNode = new GainNode(audioCtx);
oscillator.connect(gainNode).connect(audioCtx.destination);
oscillator.context;
oscillator.numberOfInputs;
oscillator.numberOfOutputs;
oscillator.channelCount;
```
## 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/audionode | data/mdn-content/files/en-us/web/api/audionode/connect/index.md | ---
title: "AudioNode: connect() method"
short-title: connect()
slug: Web/API/AudioNode/connect
page-type: web-api-instance-method
browser-compat: api.AudioNode.connect
---
{{ APIRef("Web Audio API") }}
The `connect()` method of the {{ domxref("AudioNode") }} interface lets
you connect one of the node's outputs to a target, which may be either another
`AudioNode` (thereby directing the sound data to the specified node) or an
{{domxref("AudioParam")}}, so that the node's output data is automatically used to
change the value of that parameter over time.
## Syntax
```js-nolint
connect(destination)
connect(destination, outputIndex)
connect(destination, outputIndex, inputIndex)
```
### Parameters
- `destination`
- : The {{domxref("AudioNode")}} or {{domxref("AudioParam")}} to which to connect.
- `outputIndex` {{optional_inline}}
- : An index specifying which output of the current `AudioNode` to connect to
the destination. The index numbers are defined according to the number of output
channels (see [Audio channels](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#audio_channels)).
While you can only connect a given output to a given input once
(repeated attempts are ignored), you can connect an output to multiple inputs by
calling `connect()` repeatedly. This makes [fan-out](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#fan-in_and_fan-out)
possible. The default value is 0.
- `inputIndex` {{optional_inline}}
- : An index describing which input of the destination you want to connect the current
`AudioNode` to; the default is 0. The index numbers are defined according
to the number of input channels
(see [Audio channels](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#audio_channels)). It is possible to connect an `AudioNode` to another
`AudioNode`, which in turn connects back to the first
`AudioNode`, creating a cycle.
### Return value
If the destination is a node, `connect()` returns a reference to the
destination {{domxref("AudioNode")}} object, allowing you to chain multiple
`connect()` calls. In some browsers, older implementations of this interface
return {{jsxref("undefined")}}.
If the destination is an `AudioParam`, `connect()` returns
`undefined`.
### Exceptions
- `IndexSizeError` {{domxref("DOMException")}}
- : Thrown if the value specified as `outputIndex` or `inputIndex` doesn't correspond to an existing input or output.
- `InvalidAccessError` {{domxref("DOMException")}}
- : Thrown if the destination node is not part of the same audio context as the source node.
- `NotSupportedError` {{domxref("DOMException")}}
- : Thrown if the specified connection would create a cycle (in which the audio loops back through
the same nodes repeatedly) and there are no {{domxref("DelayNode")}} objects in the cycle to
prevent the resulting waveform from getting stuck constructing the same audio frame
indefinitely. Also thrown if the `inputIndex` parameter is used while the destination is an {{domxref("AudioParam")}}.
## Examples
### Connecting to an audio input
The most obvious use of the `connect()` method is to direct the audio output
from one node into the audio input of another node for further processing. For example,
you might send the audio from a {{domxref("MediaElementAudioSourceNode")}}—that is, the
audio from an HTML media element such as {{HTMLElement("audio")}}—through a band pass
filter implemented using a {{domxref("BiquadFilterNode")}} to reduce noise before then
sending the audio along to the speakers.
This example creates an oscillator, then links it to a gain node, so that the gain node
controls the volume of the oscillator node.
```js
const audioCtx = new AudioContext();
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
```
### AudioParam example
In this example, we will be altering the gain value of a {{domxref("GainNode")}} using
an {{domxref("OscillatorNode")}} with a slow frequency value. This technique is know as
an _LFO_-controlled parameter.
```js
const audioCtx = new AudioContext();
// create an normal oscillator to make sound
const oscillator = audioCtx.createOscillator();
// create a second oscillator that will be used as an LFO (Low-frequency
// oscillator), and will control a parameter
const lfo = audioCtx.createOscillator();
// set the frequency of the second oscillator to a low number
lfo.frequency.value = 2.0; // 2Hz: two oscillations per second
// create a gain whose gain AudioParam will be controlled by the LFO
const gain = audioCtx.createGain();
// connect the LFO to the gain AudioParam. This means the value of the LFO
// will not produce any audio, but will change the value of the gain instead
lfo.connect(gain.gain);
// connect the oscillator that will produce audio to the gain
oscillator.connect(gain);
// connect the gain to the destination so we hear sound
gain.connect(audioCtx.destination);
// start the oscillator that will produce audio
oscillator.start();
// start the oscillator that will modify the gain value
lfo.start();
```
#### AudioParam notes
It is possible to connect an `AudioNode` output to more than one {{
domxref("AudioParam") }}, and more than one AudioNode output to a single {{
domxref("AudioParam") }}, with multiple calls to `connect()`. [Fan-in and fan-out](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#fan-in_and_fan-out) are therefore supported.
An {{ domxref("AudioParam") }} will take the rendered audio data from any
`AudioNode` output connected to it and convert it to mono by [down-mixing](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#up-mixing_and_down-mixing)
(if it is not already mono). Next, it will mix it together with any other such outputs,
and the intrinsic parameter value (the value the {{ domxref("AudioParam") }} would
normally have without any audio connections), including any timeline changes scheduled
for the parameter.
Therefore, it is possible to choose the range in which an {{domxref("AudioParam")}}
will change by setting the value of the {{domxref("AudioParam")}} to the central
frequency, and to use a {{domxref("GainNode")}} between the audio source and the
{{domxref("AudioParam")}} to adjust the range of the {{domxref("AudioParam")}} changes.
## 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/audionode | data/mdn-content/files/en-us/web/api/audionode/context/index.md | ---
title: "AudioNode: context property"
short-title: context
slug: Web/API/AudioNode/context
page-type: web-api-instance-property
browser-compat: api.AudioNode.context
---
{{APIRef("Web Audio API")}}
The read-only `context` property of the
{{domxref("AudioNode")}} interface returns the associated
{{domxref("BaseAudioContext")}}, that is the object representing the processing graph
the node is participating in.
## Value
The {{domxref("AudioContext")}} or {{domxref("OfflineAudioContext")}} object that was
used to construct this `AudioNode`.
## Examples
```js
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioCtx = new AudioContext();
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillator.connect(gainNode).connect(audioCtx.destination);
console.log(oscillator.context); // AudioContext
console.log(oscillator.context === audioCtx); // true
```
## 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/audionode | data/mdn-content/files/en-us/web/api/audionode/channelcount/index.md | ---
title: "AudioNode: channelCount property"
short-title: channelCount
slug: Web/API/AudioNode/channelCount
page-type: web-api-instance-property
browser-compat: api.AudioNode.channelCount
---
{{ APIRef("Web Audio API") }}
The **`channelCount`** property of the {{ domxref("AudioNode") }} interface 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.
`channelCount`'s usage and precise definition depend on the value of {{domxref("AudioNode.channelCountMode")}}:
- It is ignored if the `channelCountMode` value is `max`.
- It is used as a maximum value if the `channelCountMode` value is `clamped-max`.
- It is used as the exact value if the `channelCountMode` value is `explicit`.
## Value
An integer.
## Examples
```js
const audioCtx = new AudioContext();
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
oscillator.channelCount;
```
## 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/audionode | data/mdn-content/files/en-us/web/api/audionode/channelcountmode/index.md | ---
title: "AudioNode: channelCountMode property"
short-title: channelCountMode
slug: Web/API/AudioNode/channelCountMode
page-type: web-api-instance-property
browser-compat: api.AudioNode.channelCountMode
---
{{ APIRef("Web Audio API") }}
The `channelCountMode` property of the {{ domxref("AudioNode") }} interface represents an enumerated value describing the way channels must be matched between the node's inputs and outputs.
## Value
The possible values of the `channelCountMode` enumerated value, and their meanings are:
- `max`
- : The number of channels is equal to the maximum number of channels of all connections.
In this case, `channelCount` is ignored and only up-mixing happens.
The following AudioNode children default to this value: {{domxref("GainNode")}}, {{domxref("DelayNode")}}, {{domxref("ScriptProcessorNode")}}, {{domxref("BiquadFilterNode")}}, {{domxref("WaveShaperNode")}}.
- `clamped-max`
- : The number of channels is equal to the maximum number of channels of all connections, clamped to the value of `channelCount`.
The following AudioNode children default to this value: {{domxref("PannerNode")}}, {{domxref("ConvolverNode")}}, {{domxref("DynamicsCompressorNode")}}
- `explicit`
- : The number of channels is defined by the value of `channelCount`.
The following AudioNode children default to this value: {{domxref("AudioDestinationNode")}}, {{domxref("AnalyserNode")}}, {{domxref("ChannelSplitterNode")}}, {{domxref("ChannelMergerNode")}}
> **Note:** In older versions of the spec, the default for a {{domxref("ChannelSplitterNode")}} was `max`.
## Examples
```js
const audioCtx = new AudioContext();
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
oscillator.channelCountMode = "explicit";
```
## 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/audionode | data/mdn-content/files/en-us/web/api/audionode/numberofoutputs/index.md | ---
title: "AudioNode: numberOfOutputs property"
short-title: numberOfOutputs
slug: Web/API/AudioNode/numberOfOutputs
page-type: web-api-instance-property
browser-compat: api.AudioNode.numberOfOutputs
---
{{APIRef("Web Audio API")}}
The `numberOfOutputs` property of
the {{ domxref("AudioNode") }} interface returns the number of outputs coming out of
the node. Destination nodes — like {{domxref("AudioDestinationNode") }} — have
a value of 0 for this attribute.
## Value
An integer ≥ 0.
## Examples
```js
const audioCtx = new AudioContext();
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillator.connect(gainNode).connect(audioCtx.destination);
console.log(oscillator.numberOfOutputs); // 1
console.log(gainNode.numberOfOutputs); // 1
console.log(audioCtx.destination.numberOfOutputs); // 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)
| 0 |
data/mdn-content/files/en-us/web/api/audionode | data/mdn-content/files/en-us/web/api/audionode/channelinterpretation/index.md | ---
title: "AudioNode: channelInterpretation property"
short-title: channelInterpretation
slug: Web/API/AudioNode/channelInterpretation
page-type: web-api-instance-property
browser-compat: api.AudioNode.channelInterpretation
---
{{ APIRef("Web Audio API") }}
The **`channelInterpretation`** property of the {{domxref("AudioNode")}} interface represents an enumerated value describing how input channels are mapped to output channels when the number of inputs/outputs is different. For example, this setting defines how a mono input will be up-mixed to a stereo or 5.1 channel output, or how a quad channel input will be down-mixed to a stereo or mono output.
The property has two options: `speakers` and `discrete`. These are documented in [Basic concepts behind Web Audio API > up-mixing and down-mixing](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#up-mixing_and_down-mixing).
## Value
The values are documented in [Basic concepts behind Web Audio API > up-mixing and down-mixing](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#up-mixing_and_down-mixing).
In summary:
- `speakers`
- : Use set of "standard" mappings for combinations of common speaker input and outputs setups (mono, stereo, quad, 5.1). For example, with this setting a mono channel input will output to both channels of a stereo output.
- `discrete`
- : Input channels are mapped to output channels in order. If there are more inputs that outputs the additional inputs are dropped; if there are fewer than the unused outputs are silent.
## Examples
```js
const audioCtx = new AudioContext();
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
oscillator.channelInterpretation = "discrete";
```
## 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/audionode | data/mdn-content/files/en-us/web/api/audionode/disconnect/index.md | ---
title: "AudioNode: disconnect() method"
short-title: disconnect()
slug: Web/API/AudioNode/disconnect
page-type: web-api-instance-method
browser-compat: api.AudioNode.disconnect
---
{{ APIRef("Web Audio API") }}
The **`disconnect()`** method of the {{ domxref("AudioNode") }} interface lets you disconnect one or more nodes from the node on which the method is called.
## Syntax
```js-nolint
disconnect()
```
### Parameters
There are several versions of the `disconnect()` method, which accept different combinations of parameters to control which nodes to disconnect from. If no parameters are provided, all outgoing connections are disconnected.
- `destination` {{optional_inline}}
- : An {{domxref("AudioNode")}} or {{domxref("AudioParam")}} specifying the node or nodes to disconnect from. If this value is an `AudioNode`, a single node is disconnected from, with any other, optional, parameters (`output` and/or `input`) further limiting which inputs and/or outputs should be disconnected. If this value is an `AudioParam`, then the connection to that `AudioParam` is terminated, and the node's contributions to that computed parameter become 0 going forward once the change takes effect.
- `output` {{optional_inline}}
- : An index describing which output from the current `AudioNode` is to be disconnected. The index numbers are defined according to the number of output channels (see [Audio channels](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#audio_channels)).
- `input` {{optional_inline}}
- : An index describing which input into the specified destination `AudioNode` is to be disconnected. The index numbers are defined according to the number of input channels (see [Audio channels](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#audio_channels)).
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- `IndexSizeError` {{domxref("DOMException")}}
- : Thrown if the value specified as `input` or `output` is invalid, referring to a node which doesn't exist or is outside the permitted range.
- `InvalidAccessError` {{domxref("DOMException")}}
- : Thrown if the node on which `disconnect()` is called isn't connected to the specified `destination` node.
## Examples
```js
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioCtx = new AudioContext();
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
gainNode.disconnect();
```
## 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/audionode | data/mdn-content/files/en-us/web/api/audionode/numberofinputs/index.md | ---
title: "AudioNode: numberOfInputs property"
short-title: numberOfInputs
slug: Web/API/AudioNode/numberOfInputs
page-type: web-api-instance-property
browser-compat: api.AudioNode.numberOfInputs
---
{{APIRef("Web Audio API")}}
The `numberOfInputs` property of
the {{domxref("AudioNode")}} interface returns the number of inputs feeding the
node. Source nodes are defined as nodes having a `numberOfInputs`
property with a value of 0.
## Value
An integer ≥ 0.
## Examples
```js
const audioCtx = new AudioContext();
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillator.connect(gainNode).connect(audioCtx.destination);
console.log(oscillator.numberOfInputs); // 0
console.log(gainNode.numberOfInputs); // 1
console.log(audioCtx.destination.numberOfInputs); // 1
```
## 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/gainnode/index.md | ---
title: GainNode
slug: Web/API/GainNode
page-type: web-api-interface
browser-compat: api.GainNode
---
{{ APIRef("Web Audio API") }}
The `GainNode` interface represents a change in volume. It is an {{domxref("AudioNode")}} audio-processing module that causes a given gain to be applied to the input data before its propagation to the output. A `GainNode` always has exactly one input and one output, both with the same number of channels.
The gain is a unitless value, changing with time, that is multiplied to each corresponding sample of all input channels. If modified, the new gain is instantly applied, causing unaesthetic 'clicks' in the resulting audio. To prevent this from happening, never change the value directly but use the exponential interpolation methods on the {{domxref("AudioParam")}} interface.

{{InheritanceDiagram}}
<table class="properties">
<tbody>
<tr>
<th scope="row">Number of inputs</th>
<td><code>1</code></td>
</tr>
<tr>
<th scope="row">Number of outputs</th>
<td><code>1</code></td>
</tr>
<tr>
<th scope="row">Channel count mode</th>
<td><code>"max"</code></td>
</tr>
<tr>
<th scope="row">Channel count</th>
<td><code>2</code> (not used in the default count mode)</td>
</tr>
<tr>
<th scope="row">Channel interpretation</th>
<td><code>"speakers"</code></td>
</tr>
</tbody>
</table>
## Constructor
- {{domxref("GainNode.GainNode", "GainNode()")}}
- : Creates and returns a new `GainNode` object. As an alternative, you can use the {{domxref("BaseAudioContext.createGain()")}} factory method; see [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode).
## Instance properties
_Inherits properties from its parent, {{domxref("AudioNode")}}_.
- {{domxref("GainNode.gain")}} {{ReadOnlyInline}}
- : An [a-rate](/en-US/docs/Web/API/AudioParam#a-rate) {{domxref("AudioParam")}} representing the amount of gain to apply. You have to set {{domxref("AudioParam.value")}} or use the methods of `AudioParam` to change the effect of gain.
## Instance methods
_No specific method; inherits methods from its parent, {{domxref("AudioNode")}}_.
## Example
See [`BaseAudioContext.createGain()`](/en-US/docs/Web/API/BaseAudioContext/createGain#examples) for example code showing how to use an `AudioContext` to create a `GainNode`.
## 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/gainnode | data/mdn-content/files/en-us/web/api/gainnode/gain/index.md | ---
title: "GainNode: gain property"
short-title: gain
slug: Web/API/GainNode/gain
page-type: web-api-instance-property
browser-compat: api.GainNode.gain
---
{{ APIRef("Web Audio API") }}
The `gain` property of the {{ domxref("GainNode") }} interface is an [a-rate](/en-US/docs/Web/API/AudioParam#a-rate) {{domxref("AudioParam")}} representing the amount of gain to apply.
## Value
An {{domxref("AudioParam")}}.
> **Note:** Though the `AudioParam` returned is read-only, the value it represents is not.
## Examples
See [`BaseAudioContext.createGain()`](/en-US/docs/Web/API/BaseAudioContext/createGain#examples) for example code showing how to use an `AudioContext` to create a `GainNode`, which is then used to mute and unmute the audio by changing the gain property value.
## 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/gainnode | data/mdn-content/files/en-us/web/api/gainnode/gainnode/index.md | ---
title: "GainNode: GainNode() constructor"
short-title: GainNode()
slug: Web/API/GainNode/GainNode
page-type: web-api-constructor
browser-compat: api.GainNode.GainNode
---
{{APIRef("Web Audio API")}}
The **`GainNode()`** constructor of the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) creates a new
{{domxref("GainNode")}} object which is an {{domxref("AudioNode")}} that represents a
change in volume.
## Syntax
```js-nolint
new GainNode(context, options)
```
### Parameters
- `context`
- : A reference to a {{domxref("BaseAudioContext")}}, e.g. an {{domxref("AudioContext")}}.
- `options` {{optional_inline}}
- : Options are as follows:
- `gain`
- : The amount of gain to apply. This parameter is a- `rate`
and it's nominal range is (-∞,+∞). The default is `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.)
### Return value
A new {{domxref("GainNode")}} object instance.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmlfieldsetelement/index.md | ---
title: HTMLFieldSetElement
slug: Web/API/HTMLFieldSetElement
page-type: web-api-interface
browser-compat: api.HTMLFieldSetElement
---
{{APIRef("HTML DOM")}}
The **`HTMLFieldSetElement`** interface provides special properties and methods (beyond the regular {{domxref("HTMLElement")}} interface it also has available to it by inheritance) for manipulating the layout and presentation of {{ HTMLElement("fieldset") }} elements.
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its parent, {{domxref("HTMLElement")}}._
- {{domxref("HTMLFieldSetElement.disabled")}}
- : A boolean value reflecting the [`disabled`](/en-US/docs/Web/HTML/Element/fieldset#disabled) HTML attribute, indicating whether the user can interact with the control.
- {{domxref("HTMLFieldSetElement.elements")}} {{ReadOnlyInline}}
- : The elements belonging to this field set. The type of this property depends on the version of the spec that is implemented by the browser.
- {{domxref("HTMLFieldSetElement.form")}} {{ReadOnlyInline}}
- : An {{domxref("HTMLFormControlsCollection")}} or {{domxref("HTMLCollection")}} referencing the containing form element, if this element is in a form.
If the field set is not a descendant of a form element, then the attribute can be the ID of any form element in the same document it is related to, or the `null` value if none matches.
- {{domxref("HTMLFieldSetElement.name")}}
- : A string reflecting the [`name`](/en-US/docs/Web/HTML/Element/fieldset#name) HTML attribute, containing the name of the field set. This can be used when accessing the field set in JavaScript. It is _not_ part of the data which is sent to the server.
- {{domxref("HTMLFieldSetElement.type")}} {{ReadOnlyInline}}
- : The string "`fieldset`".
- {{domxref("HTMLFieldSetElement.validationMessage")}}
- : A string representing a localized message that describes the validation constraints that the element does not satisfy (if any). This is the empty string if the element is not a candidate for constraint validation (`willValidate` is `false`), or it satisfies its constraints.
- {{domxref("HTMLFieldSetElement.validity")}}
- : A {{domxref("ValidityState")}} representing the validity states that this element is in.
- {{domxref("HTMLFieldSetElement.willValidate")}}
- : A boolean value `false`, because {{HTMLElement("fieldset")}} objects are never candidates for constraint validation.
## Instance methods
_Inherits methods from its parent, {{domxref("HTMLElement")}}._
- {{domxref("HTMLFieldSetElement.checkValidity()")}}
- : Always returns `true` because {{HTMLElement("fieldset")}} objects are never candidates for constraint validation.
- {{domxref("HTMLFieldSetElement.reportValidity()")}}
- : Always returns `true` because {{HTMLElement("fieldset")}} objects are never candidates for constraint validation.
- {{domxref("HTMLFieldSetElement.setCustomValidity()")}}
- : Sets a custom validity message for the field set. If this message is not the empty string, then the field set is suffering from a custom validity error, and does not validate.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The HTML element implementing this interface: {{ HTMLElement("fieldset") }}.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/xpathevaluator/index.md | ---
title: XPathEvaluator
slug: Web/API/XPathEvaluator
page-type: web-api-interface
browser-compat: api.XPathEvaluator
---
{{APIRef("DOM XPath")}}
The `XPathEvaluator` interface allows to compile and evaluate {{Glossary("XPath")}} expressions.
## Constructor
- {{domxref("XPathEvaluator.XPathEvaluator", "XPathEvaluator()")}}
- : Creates a new `XPathEvaluator` object.
## Instance methods
- {{DOMxRef("XPathEvaluator.createExpression()")}}
- : Creates a parsed XPath expression with resolved namespaces.
- {{DOMxRef("XPathEvaluator.createNSResolver()")}}
- : Adapts any DOM node to resolve namespaces allowing the XPath expression to be evaluated relative to the context of the node where it appeared within the document.
- {{DOMxRef("XPathEvaluator.evaluate()")}}
- : Evaluates an XPath expression string and returns a result of the specified type if possible.
## Example
### Count the number of `<div>` elements
The following example shows the use of the `XPathEvaluator` interface.
#### HTML
```html
<div>XPath example</div>
<div>Number of <div> elements: <output></output></div>
```
#### JavaScript
```js
const xpath = "//div";
const evaluator = new XPathEvaluator();
const expression = evaluator.createExpression(xpath);
const result = expression.evaluate(
document,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
);
document.querySelector("output").textContent = result.snapshotLength;
```
#### Result
{{EmbedLiveSample("count_the_number_of_div_elements", "100%", "40")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("document.createExpression()")}}
- {{domxref("XPathExpression")}}
| 0 |
data/mdn-content/files/en-us/web/api/xpathevaluator | data/mdn-content/files/en-us/web/api/xpathevaluator/createexpression/index.md | ---
title: "XPathEvaluator: createExpression() method"
short-title: createExpression()
slug: Web/API/XPathEvaluator/createExpression
page-type: web-api-instance-method
browser-compat: api.XPathEvaluator.createExpression
---
{{APIRef("DOM XPath")}}
This method compiles an {{domxref("XPathExpression")}} which can then be used for
(repeated) evaluations of the {{Glossary("XPath")}} expression.
## Syntax
```js-nolint
createExpression(expression)
createExpression(expression, resolver)
```
### Parameters
- `expression`
- : A string representing the XPath expression to be created.
- `resolver` {{optional_inline}}
- : Permits translation of all prefixes, including the `xml` namespace
prefix, within the XPath expression into appropriate namespace URIs.
### Return value
A {{domxref("XPathExpression")}} representing the compiled form of the XPath
expression.
### Exceptions
#### INVALID_EXPRESSION_ERR
If the expression is not legal according to the rules of the
`XPathEvaluator`, an {{domxref("XPathException")}} of type
`INVALID_EXPRESSION_ERR` is raised.
#### NAMESPACE_ERR
If the expression contains namespace prefixes which cannot be resolved by the specified
{{domxref("XPathNSResolver")}}, a {{domxref("DOMException")}} of type
`NAMESPACE_ERROR` is raised.
## Examples
The following example shows the use of the `evaluate()` method.
### HTML
```html
<div>XPath example</div>
<div>Number of <div>s: <output></output></div>
```
### JavaScript
```js
const xpath = "//div";
const evaluator = new XPathEvaluator();
const expression = evaluator.createExpression(xpath);
const result = expression.evaluate(
document,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
);
document.querySelector("output").textContent = result.snapshotLength;
```
### Result
{{EmbedLiveSample('Examples')}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{DOMxRef("Document.createExpression()")}}
- {{DOMxRef("XPathExpression")}}
| 0 |
data/mdn-content/files/en-us/web/api/xpathevaluator | data/mdn-content/files/en-us/web/api/xpathevaluator/evaluate/index.md | ---
title: "XPathEvaluator: evaluate() method"
short-title: evaluate()
slug: Web/API/XPathEvaluator/evaluate
page-type: web-api-instance-method
browser-compat: api.XPathEvaluator.evaluate
---
{{APIRef("DOM XPath")}}
The `evaluate()` method of the {{domxref("XPathEvaluator")}} interface
executes an XPath expression on the given node or document and returns an
{{domxref("XPathResult")}}.
## Syntax
```js-nolint
evaluate(expression, contextNode)
evaluate(expression, contextNode, resolver)
evaluate(expression, contextNode, resolver, type)
evaluate(expression, contextNode, resolver, type, result)
```
### Parameters
- `expression`
- : A string representing the XPath expression to be parsed and
evaluated.
- `contextNode`
- : A {{domxref("Node")}} representing the context to use for evaluating the expression.
- `resolver` {{optional_inline}}
- : Permits translation of all prefixes, including the `xml` namespace
prefix, within the XPath expression into appropriate namespace URIs.
- `type` {{optional_inline}}
- : Specifies the type of result to be returned by evaluating the expression. This must
be one of the {{domxref("XPathResult", "XPathResult", "Constants")}}.
- `result` {{optional_inline}}
- : Allows to specify a result object which may be reused and returned by this method.
If this is specified as `null` or the implementation does not reuse the
specified result, a new result object will be returned.
### Return value
An {{domxref("XPathResult")}} object representing the result of evaluating the XPath
expression.
### Exceptions
#### INVALID_EXPRESSION_ERR
If the expression is not legal according to the rules of the
{{domxref("XPathEvaluator")}}, an {{domxref("XPathException")}} of type
`INVALID_EXPRESSION_ERR` is raised.
#### TYPE_ERR
In case result cannot be converted to the specified type, an
{{domxref("XPathException")}} of type `TYPE_ERR` is raised.
#### NAMESPACE_ERR
If the expression contains namespace prefixes which cannot be resolved by the specified
{{domxref("XPathNSResolver")}}, a {{domxref("DOMException")}} of type
`NAMESPACE_ERROR` is raised.
#### WRONG_DOCUMENT_ERR
If the provided context node is from a document that is not supported by the
{{domxref("XPathEvaluator")}}, a {{domxref("DOMException")}} of type
`WRONG_DOCUMENT_ERR` is raised.
#### NOT_SUPPORTED_ERR
If the provided context node is not a type permitted as an XPath context node or the
request type is not permitted by the {{domxref("XPathEvaluator")}}, a
{{domxref("DOMException")}} of type `NOT_SUPPORTED_ERR` is raised.
## Examples
The following example shows the use of the `evaluate()` method.
### HTML
```html
<div>XPath example</div>
<div>Number of <div>s: <output></output></div>
```
### JavaScript
```js
const evaluator = new XPathEvaluator();
const result = evaluator.evaluate(
"//div",
document,
null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
);
document.querySelector("output").textContent = result.snapshotLength;
```
### Result
{{EmbedLiveSample('Examples')}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xpathevaluator | data/mdn-content/files/en-us/web/api/xpathevaluator/xpathevaluator/index.md | ---
title: "XPathEvaluator: XPathEvaluator() constructor"
short-title: XPathEvaluator()
slug: Web/API/XPathEvaluator/XPathEvaluator
page-type: web-api-constructor
browser-compat: api.XPathEvaluator.XPathEvaluator
---
{{APIRef('DOM XPath')}}
The **`XPathEvaluator()`** constructor creates a new {{domxref("XPathEvaluator")}}.
## Syntax
```js-nolint
new XPathEvaluator()
```
### Parameters
None.
### Return value
A new {{domxref("XPathEvaluator")}} object.
## Examples
### Count the number of `<div>` elements
The following example shows the use of the `XPathEvaluator` interface.
#### HTML
```html
<div>XPath example</div>
<div>Number of <div> elements: <output></output></div>
```
#### JavaScript
```js
const xpath = "//div";
const evaluator = new XPathEvaluator();
const expression = evaluator.createExpression(xpath);
const result = expression.evaluate(
document,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
);
document.querySelector("output").textContent = result.snapshotLength;
```
#### Result
{{EmbedLiveSample("count_the_number_of_div_elements", "100%", "50")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xpathevaluator | data/mdn-content/files/en-us/web/api/xpathevaluator/creatensresolver/index.md | ---
title: "XPathEvaluator: createNSResolver() method"
short-title: createNSResolver()
slug: Web/API/XPathEvaluator/createNSResolver
page-type: web-api-instance-method
browser-compat: api.XPathEvaluator.createNSResolver
---
{{APIRef("DOM XPath")}}
This method adapts any DOM node to resolve namespaces so that an XPath expression can
be easily evaluated relative to the context of the node where it appeared within the
document.
This adapter works like the DOM Level 3 method {{domxref("Node.lookupNamespaceURI",
"Node.lookupNamespaceURI()")}} in resolving the namespace URI from a given prefix using
the current information available in the node's hierarchy at the time the method is
called, also correctly resolving the implicit `xml` prefix.
## Syntax
```js-nolint
createNSResolver(nodeResolver)
```
### Parameters
- `nodeResolver`
- : A {{domxref("Node")}} to be used as a context for namespace resolution.
### Return value
An {{domxref("XPathNSResolver")}} object which resolves namespaces with respect to the
definitions in scope for a specified node.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{DOMxRef("Document.createNSResolver()")}}
- {{DOMxRef("XPathExpression")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/filesystementry/index.md | ---
title: FileSystemEntry
slug: Web/API/FileSystemEntry
page-type: web-api-interface
browser-compat: api.FileSystemEntry
---
{{APIRef("File and Directory Entries API")}}
The **`FileSystemEntry`** interface of the File and Directory Entries API represents a single entry in a file system. The entry can be a file or a directory (directories are represented by the {{domxref("FileSystemDirectoryEntry")}} interface). It includes methods for working with files—including copying, moving, removing, and reading files—as well as information about a file it points to—including the file name and its path from the root to the entry.
## Basic concepts
You don't create `FileSystemEntry` objects directly. Instead, you will receive an object based on this interface through other APIs. This interface serves as a base class for the {{domxref("FileSystemFileEntry")}} and {{domxref("FileSystemDirectoryEntry")}} interfaces, which provide features specific to file system entries representing files and directories, respectively.
The `FileSystemEntry` interface includes methods that you would expect for manipulating files and directories, but it also includes a convenient method for obtaining the URL of the entry: [`toURL()`](#tourl). It also introduces a new URL scheme: `filesystem:`.
You can use the `filesystem:` scheme on Google Chrome to see all the files and folders that are stored in the origin of your app. Just use `filesystem:` scheme for the root directory of the origin of the app. For example, if your app is in [`http://www.example.com`](https://www.example.com), open `filesystem:http://www.example.com/temporary/` in a tab. Chrome shows a read-only list of all the files and folders stored the origin of your app.
### Example
To see an example of how `toURL()` works, see the [method description](#tourl). The snippet below shows you how you can remove a file by name.
```js
// Taking care of the browser-specific prefixes.
window.requestFileSystem =
window.requestFileSystem || window.webkitRequestFileSystem;
// …
// Opening a file system with temporary storage
window.requestFileSystem(
TEMPORARY,
1024 * 1024 /*1MB*/,
(fs) => {
fs.root.getFile(
"log.txt",
{},
(fileEntry) => {
fileEntry.remove(() => {
console.log("File removed.");
}, onError);
},
onError,
);
},
onError,
);
```
## Instance properties
_This interface provides the following properties._
- {{domxref("FileSystemEntry.filesystem", "filesystem")}} {{ReadOnlyInline}}
- : A {{domxref("FileSystem")}} object representing the file system in which the entry is located.
- {{domxref("FileSystemEntry.fullPath", "fullPath")}} {{ReadOnlyInline}}
- : A string object which provides the full, absolute path from the file system's root to the entry; it can also be thought of as a path which is relative to the root directory, prepended with a "/" character.
- {{domxref("FileSystemEntry.isDirectory", "isDirectory")}} {{ReadOnlyInline}}
- : A boolean value which is `true` if the entry represents a directory; otherwise, it's `false`.
- {{domxref("FileSystemEntry.isFile", "isFile")}} {{ReadOnlyInline}}
- : A Boolean which is `true` if the entry represents a file. If it's not a file, this value is `false`.
- {{domxref("FileSystemEntry.name", "name")}} {{ReadOnlyInline}}
- : A string containing the name of the entry (the final part of the path, after the last "/" character).
## Instance methods
_This interface defines the following methods._
- {{domxref("FileSystemEntry.copyTo", "copyTo()")}} {{Deprecated_Inline}} {{Non-standard_Inline}}
- : Copies the file or directory to a new location on the file system.
- {{domxref("FileSystemEntry.getMetadata", "getMetadata()")}} {{Deprecated_Inline}} {{Non-standard_Inline}}
- : Obtains metadata about the file, such as its modification date and size.
- {{domxref("FileSystemEntry.getParent", "getParent()")}}
- : Returns a {{domxref("FileSystemDirectoryEntry")}} representing the entry's parent directory.
- {{domxref("FileSystemEntry.moveTo", "moveTo()")}} {{Deprecated_Inline}} {{Non-standard_Inline}}
- : Moves the file or directory to a new location on the file system, or renames the file or directory.
- {{domxref("FileSystemEntry.remove", "remove()")}} {{Deprecated_Inline}} {{Non-standard_Inline}}
- : Removes the specified file or directory. You can only remove directories which are empty.
- {{domxref("FileSystemEntry.toURL", "toURL()")}} {{Deprecated_Inline}} {{Non-standard_Inline}}
- : Creates and returns a URL which identifies the entry. This URL uses the URL scheme `"filesystem:"`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
- {{domxref("FileSystemFileEntry")}} and {{domxref("FileSystemDirectoryEntry")}} are based on `FileSystemEntry`.
| 0 |
data/mdn-content/files/en-us/web/api/filesystementry | data/mdn-content/files/en-us/web/api/filesystementry/name/index.md | ---
title: "FileSystemEntry: name property"
short-title: name
slug: Web/API/FileSystemEntry/name
page-type: web-api-instance-property
browser-compat: api.FileSystemEntry.name
---
{{APIRef("File and Directory Entries API")}}
The read-only **`name`** property of
the {{domxref("FileSystemEntry")}} interface returns a string
specifying the entry's name; this is the entry within its parent directory (the last
component of the path as indicated by the {{domxref("FileSystemEntry.fullPath",
"fullPath")}} property).
## Value
A string indicating the entry's name.
## Examples
This example shows a function called `isFileWithExtension()` which returns
true if the specified {{domxref("FileSystemEntry")}} is both a file and the file's name
ends with a given extension.
```js
function isFileWithExtension(entry, extension) {
return entry.isFile && entry.name.endsWith(`.${extension}`);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
- {{domxref("FileSystemEntry")}}
- {{domxref("FileSystemEntry.fullPath")}}
| 0 |
data/mdn-content/files/en-us/web/api/filesystementry | data/mdn-content/files/en-us/web/api/filesystementry/remove/index.md | ---
title: "FileSystemEntry: remove() method"
short-title: remove()
slug: Web/API/FileSystemEntry/remove
page-type: web-api-instance-method
status:
- deprecated
- non-standard
browser-compat: api.FileSystemEntry.remove
---
{{APIRef("File and Directory Entries API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The {{domxref("FileSystemEntry")}} interface's method
**`remove()`** deletes the file
or directory from the file system. Directories must be empty before they can be
removed.
To recursively remove a directory as well as all of its contents and its
subdirectories, call {{domxref("FileSystemDirectoryEntry.removeRecursively()")}}
instead.
## Syntax
```js-nolint
remove(successCallback)
remove(successCallback, errorCallback)
```
### Parameters
- `successCallback`
- : A function which is called once the file has been successfully removed.
- `errorCallback` {{optional_inline}}
- : An optional callback which is called if the attempt to remove the file fails.
### Return value
None ({{jsxref("undefined")}}).
### Errors
- `FileError.INVALID_MODIFICATION_ERR`
- : The specified entry was the file system's root directory, or the specified entry is
a directory which isn't empty.
- `FileError.INVALID_STATE_ERR`
- : The file system's cached state is inconsistent with its state on disk, so the file
could not be deleted for safety reasons.
- `FileError.NO_MODIFICATION_ALLOWED_ERR`
- : The file system's state doesn't permit removing the file or directory.
- `FileError.NOT_FOUND_ERR`
- : The file or directory doesn't exist.
- `FileError.SECURITY_ERR`
- : The entry couldn't be removed due to permissions or other access constraints, or
because there are too many calls being made on file resources.
## Examples
This example deletes a temporary work file.
```js
workingDirectory.getFile(
"tmp/workfile.json",
{},
(fileEntry) => {
fileEntry.remove(() => {
/* the file was removed successfully */
});
},
handleError,
);
```
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
- {{domxref("FileSystemDirectoryEntry.removeRecursively()")}}
| 0 |
data/mdn-content/files/en-us/web/api/filesystementry | data/mdn-content/files/en-us/web/api/filesystementry/copyto/index.md | ---
title: "FileSystemEntry: copyTo() method"
short-title: copyTo()
slug: Web/API/FileSystemEntry/copyTo
page-type: web-api-instance-method
status:
- deprecated
- non-standard
browser-compat: api.FileSystemEntry.copyTo
---
{{APIRef("File and Directory Entries API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The {{domxref("FileSystemEntry")}} interface's method
**`copyTo()`** copies the file
specified by the entry to a new location on the file system.
There are some
typical restrictions on what you can do:
- A directory can't be copied into itself.
- An entry can't be copied into its parent directory unless you specify a new name.
- When copying a directory, the copy is always recursive; you can't leave out
subfolders.
## Syntax
```js-nolint
copyTo(newParent)
copyTo(newParent, newName)
copyTo(newParent, newName, successCallback)
copyTo(newParent, newName, successCallback, errorCallback)
```
### Parameters
- `newParent`
- : A {{domxref("FileSystemDirectoryEntry")}} object specifying the destination
directory for the copy operation.
- `newName` {{optional_inline}}
- : If this parameter is provided, the copy is given this string as its new file or
directory name.
- `successCallback` {{optional_inline}}
- : A function which is called when the copy operation is successfully completed.
Receives a single input parameter: a {{domxref("FileSystemEntry")}} based object
providing the copied item's new details.
- `errorCallback` {{optional_inline}}
- : An optional callback which is executed if an error occurs while copying the items.
There's a single parameter: a {{domxref("FileError")}} describing what went wrong.
### Return value
None ({{jsxref("undefined")}}).
### Errors
- `FileError.INVALID_MODIFICATION_ERR`
- : The requested operation involves an impossible change, such as moving a directory
inside itself or one of its own child directories, or copying an item within the same
directory without renaming it.
- `FileError.QUOTA_EXCEEDED_ERR`
- : The operation exceeded the user's storage quota, or there isn't enough storage space
left to complete the operation.
## Examples
This example shows how a temporary log file might be moved into a more permanent "log"
directory.
```js
workingDirectory.getFile(
"tmp/log.txt",
{},
(fileEntry) => {
workingDirectory.getDirectory(
"log",
{},
(dirEntry) => {
fileEntry.copyTo(dirEntry);
},
handleError,
);
},
handleError,
);
```
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
| 0 |
data/mdn-content/files/en-us/web/api/filesystementry | data/mdn-content/files/en-us/web/api/filesystementry/moveto/index.md | ---
title: "FileSystemEntry: moveTo() method"
short-title: moveTo()
slug: Web/API/FileSystemEntry/moveTo
page-type: web-api-instance-method
status:
- deprecated
- non-standard
browser-compat: api.FileSystemEntry.moveTo
---
{{APIRef("File and Directory Entries API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The {{domxref("FileSystemEntry")}} interface's method
**`moveTo()`** moves the file
specified by the entry to a new location on the file system, or renames the file if
the destination directory is the same as the source.
There are some typical
restrictions on what you can do:
- A directory can't be moved into itself.
- An entry can't be moved into its parent directory unless you specify a new name.
Specifying a new name lets `moveTo()` double as a rename operation.
- When moving a directory, the move is always recursive; you can't leave out
subfolders.
- You can't move a file such that it replaces an existing directory, and you can't
move a directory such that it replaces an existing file. However, a file can replace a
file and a directory can replace a directory.
- You can only overwrite a directory if it's empty.
## Syntax
```js-nolint
moveTo(newParent, newName)
moveTo(newParent, newName, successCallback)
moveTo(newParent, newName, successCallback, errorCallback)
```
### Parameters
- `newParent`
- : A {{domxref("FileSystemDirectoryEntry")}} object specifying the destination
directory for the move operation.
- `newName` {{optional_inline}}
- : If this parameter is provided, the entry is renamed to have this string as its new
file or directory name.
- `successCallback` {{optional_inline}}
- : A function which is called when the move operation is successfully completed.
Receives a single input parameter: a {{domxref("FileSystemEntry")}} based object
providing the moved item's new details.
- `errorCallback` {{optional_inline}}
- : An optional callback which is executed if an error occurs while moving the items.
There's a single parameter: a {{domxref("FileError")}} describing what went wrong.
### Return value
None ({{jsxref("undefined")}}).
### Errors
- `FileError.INVALID_MODIFICATION_ERR`
- : The requested operation involves an impossible change, such as moving a directory
inside itself or one of its own child directories, or copying an item within the same
directory without renaming it.
- `FileError.QUOTA_EXCEEDED_ERR`
- : The operation exceeded the user's storage quota, or there isn't enough storage space
left to complete the operation.
## Examples
This example shows how a temporary log file might be moved into a more permanent "log"
directory when it exceeds a megabyte in size.
```js
workingDirectory.getFile(
"tmp/log.txt",
{},
(fileEntry) => {
fileEntry.getMetadata((metadata) => {
if (metadata.size > 1048576) {
workingDirectory.getDirectory(
"log",
{},
(dirEntry) => {
fileEntry.moveTo(dirEntry);
},
handleError,
);
}
});
},
handleError,
);
```
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
- {{domxref("FileSystemEntry.copyTo()")}}
| 0 |
data/mdn-content/files/en-us/web/api/filesystementry | data/mdn-content/files/en-us/web/api/filesystementry/getmetadata/index.md | ---
title: "FileSystemEntry: getMetadata() method"
short-title: getMetadata()
slug: Web/API/FileSystemEntry/getMetadata
page-type: web-api-instance-method
status:
- deprecated
- non-standard
browser-compat: api.FileSystemEntry.getMetadata
---
{{APIRef("File and Directory Entries API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The {{domxref("FileSystemEntry")}} interface's method
**`getMetadata()`** obtains a
{{domxref("Metadata")}} object with information about the file system entry, such as
its modification date and time and its size.
## Syntax
```js-nolint
getMetadata(successCallback)
getMetadata(successCallback, errorCallback)
```
### Parameters
- `successCallback`
- : A function which is called when the copy operation is successfully completed.
Receives a single input parameter: a {{domxref("Metadata")}} object with information
about the file.
- `errorCallback` {{optional_inline}}
- : An optional callback which is executed if an error occurs while looking up the
metadata. There's a single parameter: a {{domxref("FileError")}} describing what went
wrong.
### Return value
None ({{jsxref("undefined")}}).
### Errors
- `FileError.NOT_FOUND_ERR`
- : The {{domxref("FileSystemEntry")}} refers to an item which doesn't exist.
- `FileError.SECURITY_ERR`
- : Security restrictions prohibit obtaining the requested metadata.
## Examples
This example checks the size of a log file in a temporary folder and, if it exceeds a
megabyte, moves it into a different directory.
```js
workingDirectory.getFile(
"tmp/log.txt",
{},
(fileEntry) => {
fileEntry.getMetadata((metadata) => {
if (metadata.size > 1048576) {
workingDirectory.getDirectory(
"log",
{},
(dirEntry) => {
fileEntry.moveTo(dirEntry);
},
handleError,
);
}
});
},
handleError,
);
```
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
| 0 |
data/mdn-content/files/en-us/web/api/filesystementry | data/mdn-content/files/en-us/web/api/filesystementry/isfile/index.md | ---
title: "FileSystemEntry: isFile property"
short-title: isFile
slug: Web/API/FileSystemEntry/isFile
page-type: web-api-instance-property
browser-compat: api.FileSystemEntry.isFile
---
{{APIRef("File and Directory Entries API")}}
The read-only **`isFile`** property of
the {{domxref("FileSystemEntry")}} interface is `true` if the entry
represents a file (meaning it's a {{domxref("FileSystemFileEntry")}}) and
`false` if it's not.
You can also use {{domxref("FileSystemEntry.isDirectory", "isDirectory")}} to determine
if the entry is a directory.
> **Warning:** You should not assume that any entry which isn't a file is a directory or vice versa.
> There are other types of file descriptors on many operating systems. Be sure to use
> both `isDirectory` and `isFile` as needed to ensure that the
> entry is something you know how to work with.
## Value
A Boolean indicating whether or not the {{domxref("FileSystemEntry")}} is a file.
## Examples
This example shows how this property might be used to determine whether to process the
entry as a directory or file. If the entry is neither, an error handler is called with
an appropriate message.
```js
if (entry.isDirectory) {
processSubdirectory(entry);
} else if (entry.isFile) {
processFile(entry);
} else {
displayErrorMessage("Unsupported file system entry specified.");
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
- {{domxref("FileSystemEntry")}}
- {{domxref("FileSystemEntry.isDirectory")}}
- {{domxref("FileSystemFileEntry")}}
| 0 |
data/mdn-content/files/en-us/web/api/filesystementry | data/mdn-content/files/en-us/web/api/filesystementry/getparent/index.md | ---
title: "FileSystemEntry: getParent() method"
short-title: getParent()
slug: Web/API/FileSystemEntry/getParent
page-type: web-api-instance-method
browser-compat: api.FileSystemEntry.getParent
---
{{APIRef("File and Directory Entries API")}}
The {{domxref("FileSystemEntry")}} interface's method
**`getParent()`** obtains a
{{domxref("FileSystemDirectoryEntry")}}.
## Syntax
```js-nolint
getParent(successCallback, errorCallback)
getParent(successCallback)
```
### Parameters
- `successCallback`
- : A function which is called when the parent directory entry has been retrieved. The
callback receives a single input parameter: a {{domxref("FileSystemDirectoryEntry")}}
object representing the parent directory. The parent of the root directory is
considered to be the root directory, itself, so be sure to watch for that.
- `errorCallback` {{optional_inline}}
- : An optional callback which is executed if an error occurs. There's a single
parameter: a {{domxref("DOMException")}} describing what went wrong.
### Return value
None ({{jsxref("undefined")}}).
### Errors
- `FileError.INVALID_STATE_ERR`
- : The operation failed because the file system's state doesn't permit it. This can
happen, for example, if the file system's cached state differs from the actual state
of the file system.
- `FileError.NOT_FOUND_ERR`
- : The specified path could not be found.
- `FileError.SECURITY_ERR`
- : Security restrictions prohibit obtaining the parent directory's information.
## Examples
This example renames the file specified by the variable `fileEntry` to
`"newname.html"`.
```js
fileEntry.getParent(
(parent) => {
fileEntry.moveTo(parent, "newname.html", (updatedEntry) => {
console.log(`File ${fileEntry.name} renamed to newname.html.`);
});
},
(error) => {
console.error(
`An error occurred: Unable to rename ${fileEntry.name} to newname.html.`,
);
},
);
```
This is accomplished by first obtaining a {{domxref("FileSystemDirectoryEntry")}}
object representing the directory the file is currently located in. Then
{{domxref("FileSystemEntry.moveTo", "moveTo()")}} is used to rename the file within that
directory.
## Using promises
Currently, there isn't a {{jsxref("Promise")}}-based version of this method. You can,
however, create a simple helper function to adapt it, like this:
```js
function getParentPromise(entry) {
return new Promise((resolve, reject) => {
entry.getParent(resolve, reject);
});
}
```
A similar approach can be taken elsewhere in the File and Directory Entries API.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
| 0 |
data/mdn-content/files/en-us/web/api/filesystementry | data/mdn-content/files/en-us/web/api/filesystementry/isdirectory/index.md | ---
title: "FileSystemEntry: isDirectory property"
short-title: isDirectory
slug: Web/API/FileSystemEntry/isDirectory
page-type: web-api-instance-property
browser-compat: api.FileSystemEntry.isDirectory
---
{{APIRef("File and Directory Entries API")}}
The read-only **`isDirectory`**
property of the {{domxref("FileSystemEntry")}} interface is `true` if the
entry represents a directory (meaning it's a {{domxref("FileSystemDirectoryEntry")}})
and `false` if it's not.
You can also use {{domxref("FileSystemEntry.isFile", "isFile")}} to determine if the
entry is a file.
> **Warning:** You should not assume that any entry which isn't a directory is a file or vice versa.
> There are other types of file descriptors on many operating systems. Be sure to use
> both `isDirectory` and `isFile` as needed to ensure that the
> entry is something you know how to work with.
## Value
A Boolean indicating whether or not the {{domxref("FileSystemEntry")}} is a directory.
## Examples
This example shows how this property might be used to determine whether to process the
entry as a directory or file. If the entry is neither, an error handler is called with
an appropriate message.
```js
if (entry.isDirectory) {
processSubdirectory(entry);
} else if (entry.isFile) {
processFile(entry);
} else {
displayErrorMessage("Unsupported file system entry specified.");
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
- {{domxref("FileSystemEntry")}}
- {{domxref("FileSystemEntry.isFile")}}
- {{domxref("FileSystemDirectoryEntry")}}
| 0 |
data/mdn-content/files/en-us/web/api/filesystementry | data/mdn-content/files/en-us/web/api/filesystementry/tourl/index.md | ---
title: "FileSystemEntry: toURL() method"
short-title: toURL()
slug: Web/API/FileSystemEntry/toURL
page-type: web-api-instance-method
status:
- deprecated
- non-standard
browser-compat: api.FileSystemEntry.toURL
---
{{APIRef("File and Directory Entry API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The {{domxref("FileSystemEntry")}} interface's method
**`toURL()`** creates and
returns a string containing a URL which can be used to identify the file system entry.
This is done by exposing a new URL scheme—`filesystem:`—that can be used as
the value of `src` and `href` attributes.
## Syntax
```js-nolint
toURL()
toURL(mimeType)
```
### Parameters
- `mimeType` {{optional_inline}}
- : An optional string specifying the MIME type to use when interpreting the file. This
can be used to help deal with files whose types aren't recognized automatically by the
user agent. If this parameter is omitted, the user agent uses its standard algorithms
to identify the file.
### Return value
A string containing a URL that can then be used as a document
reference in HTML content, or an empty string if the URL can't be generated (such as if
the file system implementation doesn't support `toURL()`).
## Examples
If you have a {{domxref("FileSystemFileEntry")}} corresponding to an image file in a
file system available to your website or app, you can call `toURL()` to get
its URL for use in HTML. If your site is located at
`http://my-awesome-website.woot`, and you have a temporary file system that
contains an image file named `awesomesauce.jpg`, the URL returned by
`toURL()` might be (depending on the browser's implementation) something like
`"filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg"`.
Code that makes use of this might look like this:
```js
let img = document.createElement("img");
img.src = imageFileEntry.toURL();
document.body.appendChild(img);
```
Assuming the scenario mentioned before the code, the result would be HTML that looks
like this being appended to the end of the document:
```html
<img
src="filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg" />
```
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
- {{domxref("FileSystemDirectoryEntry.removeRecursively()")}}
| 0 |
data/mdn-content/files/en-us/web/api/filesystementry | data/mdn-content/files/en-us/web/api/filesystementry/filesystem/index.md | ---
title: "FileSystemEntry: filesystem property"
short-title: filesystem
slug: Web/API/FileSystemEntry/filesystem
page-type: web-api-instance-property
browser-compat: api.FileSystemEntry.filesystem
---
{{APIRef("File and Directory Entries API")}}
The read-only **`filesystem`**
property of the {{domxref("FileSystemEntry")}} interface contains a
{{domxref("FileSystem")}} object that represents the file system on which the entry
resides.
## Value
A {{domxref("FileSystem")}} representing the file system on which the file or directory
described by the `FileSystemEntry` is located.
## Examples
This example obtains a {{domxref("FileSystemDirectoryEntry")}} for the root directory
of the file system containing a file.
```js
let rootDirEntry = fileEntry.filesystem.root;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
- {{domxref("FileSystemEntry")}}
- {{domxref("FileSystem")}}
| 0 |
data/mdn-content/files/en-us/web/api/filesystementry | data/mdn-content/files/en-us/web/api/filesystementry/fullpath/index.md | ---
title: "FileSystemEntry: fullPath property"
short-title: fullPath
slug: Web/API/FileSystemEntry/fullPath
page-type: web-api-instance-property
browser-compat: api.FileSystemEntry.fullPath
---
{{APIRef("File and Directory Entries API")}}
The read-only **`fullPath`** property
of the {{domxref("FileSystemEntry")}} interface returns a string
specifying the full, absolute path from the file system's root to the file represented
by the entry.
This can also be thought of as a path which is relative to the root directory, with a
"/" prepended to it to make it absolute.
## Value
A string indicating the entry's full path.
## Examples
This example shows a function which is called with a file system; it then gets a
{{domxref("FileSystemFileEntry")}} for a file named `data.json` and returns
its full path.
```js
function gotFileSystem(fs) {
let path = "";
fs.root.getFile(
"data.json",
{ create: true, exclusive: true },
(entry) => {
path = fullPath;
},
handleError(error),
);
return path;
}
```
Obviously, this is somewhat contrived, since we know that the file's full path is
`"/data.json"`, having just looked it up ourselves, but the concept holds up
for scenarios in which you don't know it.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
- {{domxref("FileSystemEntry")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/xrframe/index.md | ---
title: XRFrame
slug: Web/API/XRFrame
page-type: web-api-interface
status:
- experimental
browser-compat: api.XRFrame
---
{{APIRef("WebXR Device API")}}{{SecureContext_Header}}{{SeeCompatTable}}
A [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API) **`XRFrame`** object is passed into the {{domxref("XRSession.requestAnimationFrame", "requestAnimationFrame()")}} callback function and provides access to the information needed in order to render a single frame of animation for an {{domxref("XRSession")}} describing a VR or AR scene. Events which communicate the tracking state of objects also provide an `XRFrame` reference as part of their structure.
In addition to providing a reference to the {{domxref("XRSession")}} for which this frame is to be rendered, the {{domxref("XRFrame.getViewerPose", "getViewerPose()")}} method is provided to obtain the {{domxref("XRViewerPose")}} describing the viewer's position and orientation in space, and {{domxref("XRFrame.getPose", "getPose()")}} can be used to create an {{domxref("XRPose")}} describing the relative position of one {{domxref("XRSpace")}} relative to another.
## Instance properties
- {{DOMxRef("XRFrame.session", "session")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : The {{DOMxRef("XRSession")}} that for which this `XRFrame` describes the tracking details for all objects. The information about a specific object can be obtained by calling one of the methods on the object.
- {{DOMxRef("XRFrame.trackedAnchors", "trackedAnchors")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : An {{domxref("XRAnchorSet")}} containing all anchors still tracked in the frame.
## Instance methods
- {{domxref("XRFrame.createAnchor()", "createAnchor()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} which resolves to a free-floating {{domxref("XRAnchor")}} object.
- {{domxref("XRFrame.fillJointRadii()", "fillJointRadii()")}} {{Experimental_Inline}}
- : Populates a {{jsxref("Float32Array")}} with radii for a list of hand joint spaces. Returns `true` if successful for all spaces.
- {{domxref("XRFrame.fillPoses()", "fillPoses()")}} {{Experimental_Inline}}
- : Populates a {{jsxref("Float32Array")}} with the matrices of the poses, relative to a given base space. Returns `true` if all spaces have a valid pose.
- {{domxref("XRFrame.getDepthInformation()", "getDepthInformation()")}} {{Experimental_Inline}}
- : Returns an {{domxref("XRCPUDepthInformation")}} object containing CPU depth information for the frame.
- {{domxref("XRFrame.getHitTestResults()", "getHitTestResults()")}} {{Experimental_Inline}}
- : Returns an array of {{domxref("XRHitTestResult")}} objects containing hit test results for a given {{domxref("XRHitTestSource")}}.
- {{domxref("XRFrame.getHitTestResultsForTransientInput()", "getHitTestResultsForTransientInput()")}} {{Experimental_Inline}}
- : Returns an array of {{domxref("XRTransientInputHitTestResult")}} objects containing hit test results for a given {{domxref("XRTransientInputHitTestSource")}}.
- {{domxref("XRFrame.getJointPose()", "getJointPose()")}} {{Experimental_Inline}}
- : Returns an {{domxref("XRJointPose")}} object providing the pose of a hand joint (see {{domxref("XRHand")}}) relative to a given base space.
- {{domxref("XRFrame.getLightEstimate()", "getLightEstimate()")}} {{Experimental_Inline}}
- : Returns an {{domxref("XRLightEstimate")}} object containing estimated lighting values for an {{domxref("XRLightProbe")}}.
- {{DOMxRef("XRFrame.getPose", "getPose()")}} {{Experimental_Inline}}
- : Returns an {{domxref("XRPose")}} object representing the spatial relationship between the two specified {{domxref("XRSpace")}} objects.
- {{DOMxRef("XRFrame.getViewerPose", "getViewerPose()")}} {{Experimental_Inline}}
- : Returns an {{domxref("XRViewerPose")}} describing the viewer's position and orientation in a given {{domxref("XRReferenceSpace")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API)
- [Spatial tracking in WebXR](/en-US/docs/Web/API/WebXR_Device_API/Spatial_tracking)
| 0 |
data/mdn-content/files/en-us/web/api/xrframe | data/mdn-content/files/en-us/web/api/xrframe/getdepthinformation/index.md | ---
title: "XRFrame: getDepthInformation() method"
short-title: getDepthInformation()
slug: Web/API/XRFrame/getDepthInformation
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRFrame.getDepthInformation
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`getDepthInformation()`** method of the {{domxref("XRFrame")}} interface returns an {{domxref("XRCPUDepthInformation")}} object containing CPU depth information for the active and animated frame.
## Syntax
```js-nolint
getDepthInformation(view)
```
### Parameters
- `view`
- : An {{domxref("XRView")}} object obtained from a viewer pose.
### Return value
An {{domxref("XRCPUDepthInformation")}} object.
### Exceptions
- `NotSupportedError` {{domxref("DOMException")}}
- : Thrown if `"depth-sensing"` is not in the list of enabled features for this {{domxref("XRSession")}}.
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if:
- the `XRFrame` is not active nor animated. Obtaining depth information is only valid within the {{domxref("XRSession.requestAnimationFrame()", "requestAnimationFrame()")}} callback.
- the session's {{domxref("XRSession.depthUsage", "depthUsage")}} is not `"cpu-optimized"`.
## Examples
### Obtaining CPU depth information
```js
// Make sure to request a session with depth-sensing enabled
const session = navigator.xr.requestSession("immersive-ar", {
requiredFeatures: ["depth-sensing"],
depthSensing: {
usagePreference: ["cpu-optimized", "gpu-optimized"],
formatPreference: ["luminance-alpha", "float32"],
},
});
// …
// Obtain depth information in an active and animated frame
function rafCallback(time, frame) {
session.requestAnimationFrame(rafCallback);
const pose = frame.getViewerPose(referenceSpace);
if (pose) {
for (const view of pose.views) {
const depthInformation = frame.getDepthInformation(view);
if (depthInformation) {
// Do something with the depth information
renderDepth(depthInformation);
}
}
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrframe | data/mdn-content/files/en-us/web/api/xrframe/getjointpose/index.md | ---
title: "XRFrame: getJointPose() method"
short-title: getJointPose()
slug: Web/API/XRFrame/getJointPose
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRFrame.getJointPose
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`getJointPose()`** method of the {{domxref("XRFrame")}} interface returns an {{domxref("XRJointPose")}} object providing the pose of a hand joint (see {{domxref("XRHand")}}) relative to a given base space.
## Syntax
```js-nolint
getJointPose(joint, baseSpace)
```
### Parameters
- `joint`
- : An {{domxref("XRJointSpace")}} specifying the hand joint space for which to obtain an {{domxref("XRJointPose")}} describing the item's position and orientation.
- `baseSpace`
- : An {{domxref("XRSpace")}} to use as the base or origin for the relative position and orientation.
### Return value
An {{domxref("XRJointPose")}} object specifying the position and orientation of the hand joint, relative to
the {{domxref("XRSpace")}} indicated by `baseSpace`.
## Examples
### Using `getJointPose()`
Call `getJointPose()` with an {{domxref("XRJointSpace")}} and an {{domxref("XRReferenceSpace")}} to get an {{domxref("XRJointPose")}} object.
```js
navigator.xr
.requestSession({ optionalFeatures: ["hand-tracking"] })
.then(/* … */);
function renderFrame(session, frame) {
// …
for (const inputSource of session.inputSources) {
if (inputSource.hand) {
const indexFingerTipJoint = inputSource.hand.get("index-finger-tip");
frame.getJointPose(indexFingerTipJoint, referenceSpace); // XRJointPose
}
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRHand")}}
- {{domxref("XRJointSpace")}}
- {{domxref("XRSpace")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrframe | data/mdn-content/files/en-us/web/api/xrframe/gethittestresults/index.md | ---
title: "XRFrame: getHitTestResults() method"
short-title: getHitTestResults()
slug: Web/API/XRFrame/getHitTestResults
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRFrame.getHitTestResults
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`getHitTestResults()`** method of the {{domxref("XRFrame")}} interface returns an array of {{domxref("XRHitTestResult")}} objects containing hit test results for a given {{domxref("XRHitTestSource")}}.
## Syntax
```js-nolint
getHitTestResults(hitTestSource)
```
### Parameters
- `hitTestSource`
- : An {{domxref("XRHitTestSource")}} object that contains hit test subscriptions.
### Return value
An array of {{domxref("XRHitTestResult")}} objects.
## Examples
### Getting hit test results
To request a hit test source, start an {{domxref("XRSession")}} with the `hit-test` session feature enabled. Next, request a the hit test source with {{domxref("XRSession.requestHitTestSource()")}} and store it for later use in the frame loop. Finally, call `getHitTestResults()` to obtain the result.
```js
const xrSession = navigator.xr.requestSession("immersive-ar", {
requiredFeatures: ["local", "hit-test"],
});
let hitTestSource = null;
xrSession
.requestHitTestSource({
space: viewerSpace, // obtained from xrSession.requestReferenceSpace("viewer");
offsetRay: new XRRay({ y: 0.5 }),
})
.then((viewerHitTestSource) => {
hitTestSource = viewerHitTestSource;
});
// frame loop
function onXRFrame(time, xrFrame) {
let hitTestResults = xrFrame.getHitTestResults(hitTestSource);
// do things with the hit test results
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRHitTestResult")}}
- {{domxref("XRHitTestSource")}}
- {{domxref("XRRay")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrframe | data/mdn-content/files/en-us/web/api/xrframe/getlightestimate/index.md | ---
title: "XRFrame: getLightEstimate() method"
short-title: getLightEstimate()
slug: Web/API/XRFrame/getLightEstimate
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRFrame.getLightEstimate
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`getLightEstimate()`** method of the {{domxref("XRFrame")}} interface returns an {{domxref("XRLightEstimate")}} object containing estimated lighting values for a given {{domxref("XRLightProbe")}}.
## Syntax
```js-nolint
getLightEstimate(lightProbe)
```
### Parameters
- `lightProbe`
- : An {{domxref("XRLightProbe")}} object containing the current lighting state for the frame.
### Return value
An {{domxref("XRLightEstimate")}} object or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) if the device cannot estimate lighting for this frame.
## Examples
### Getting light estimates for each frame
Given a session's {{domxref("XRLightProbe")}}, the `getLightEstimate()` method gets an {{domxref("XRLightEstimate")}} object containing the lighting values for each frame.
```js
const lightProbe = await xrSession.requestLightProbe();
// frame loop
function onXRFrame(time, xrFrame) {
let lightEstimate = xrFrame.getLightEstimate(lightProbe);
// Use light estimate data to light the scene
// Available properties
lightEstimate.sphericalHarmonicsCoefficients;
lightEstimate.primaryLightDirection;
lightEstimate.primaryLightIntensity;
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRLightEstimate")}}
- {{domxref("XRLightProbe")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrframe | data/mdn-content/files/en-us/web/api/xrframe/getviewerpose/index.md | ---
title: "XRFrame: getViewerPose() method"
short-title: getViewerPose()
slug: Web/API/XRFrame/getViewerPose
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRFrame.getViewerPose
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`getViewerPose()`** method, a member of the {{domxref("XRFrame")}} interface, returns a {{domxref("XRViewerPose")}} object which describes the viewer's pose (position and orientation) relative to the specified reference space.
See the {{domxref("XRFrame.getPose", "getPose()")}} method for a way to calculate a pose that represents the difference between two spaces.
## Syntax
```js-nolint
getViewerPose(referenceSpace)
```
### Parameters
- `referenceSpace`
- : An {{domxref("XRReferenceSpace")}} object specifying the space to use as the
reference point or base for the computation of the viewer's current pose.
### Return value
A {{domxref("XRViewerPose")}} describing the viewer's position and orientation relative
to the specified reference space.
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if `getViewerPose()` was not
called within the context of a callback to a
session's {{domxref("XRSession.requestAnimationFrame",
"XRSession.requestAnimationFrame()")}}.
## Examples
In this callback function for {{domxref("XRSession.requestAnimationFrame",
"requestAnimationFrame()")}}, the {{domxref("XRViewerPose")}} describing the viewer's
viewpoint on the world is obtained by calling `getViewerPose()` on the
{{domxref("XRFrame")}} passed into the callback.
```js
viewerPose = xrFrame.getViewerPose(xrReferenceSpace);
if (viewerPose) {
/* render the pose's views */
}
```
To see a complete example, take a look at [Movement, orientation, and motion](/en-US/docs/Web/API/WebXR_Device_API/Movement_and_motion).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrframe | data/mdn-content/files/en-us/web/api/xrframe/session/index.md | ---
title: "XRFrame: session property"
short-title: session
slug: Web/API/XRFrame/session
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRFrame.session
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
An `XRFrame` object's _read-only_ **`session`** property returns the {{domxref("XRSession")}} object that generated the frame.
## Value
A {{domxref("XRSession")}} object representing the WebXR session for which
this `XRFrame` describes the object positions and orientations.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrframe | data/mdn-content/files/en-us/web/api/xrframe/filljointradii/index.md | ---
title: "XRFrame: fillJointRadii() method"
short-title: fillJointRadii()
slug: Web/API/XRFrame/fillJointRadii
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRFrame.fillJointRadii
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`fillJointRadii()`** method of the {{domxref("XRFrame")}} interface populates a {{jsxref("Float32Array")}} with radii for a list of hand joint spaces and returns `true` if successful for all spaces.
## Syntax
```js-nolint
fillJointRadii(jointSpaces, radii)
```
### Parameters
- `jointSpaces`
- : An array of {{domxref("XRJointSpace")}} objects for which to obtain the radii.
- `radii`
- : A {{jsxref("Float32Array")}} that is populated with the radii of the `jointSpaces`.
### Return value
A boolean indicating if all of the spaces have a valid pose.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the length of `jointSpaces` is larger than the number of elements in `radii`.
## Examples
### Obtaining radii for all joints of a hand
To efficiently get all radii for all 25 joints of each {{domxref("XRHand")}}, you can use the `fillJointRadii()` method.
```js
let radii1 = new Float32Array(25);
let radii2 = new Float32Array(25);
function onXRFrame(xrFrame, renderer) {
let hand1 = xrFrame.session.inputSources[0].hand;
xrFrame.fillJointRadii(hand1.values(), radii1);
let hand2 = xrFrame.session.inputSources[1].hand;
xrFrame.fillJointRadii(hand2.values(), radii2);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRHand")}}
- {{domxref("XRJointSpace")}}
- {{jsxref("Float32Array")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrframe | data/mdn-content/files/en-us/web/api/xrframe/trackedanchors/index.md | ---
title: "XRFrame: trackedAnchors property"
short-title: trackedAnchors
slug: Web/API/XRFrame/trackedAnchors
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRFrame.trackedAnchors
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The read-only **`trackedAnchor`** property of the {{domxref("XRFrame")}} interface returns an {{domxref("XRAnchorSet")}} object containing all anchors still tracked in the frame.
## Value
An {{domxref("XRAnchorSet")}} object.
## Examples
### Updating anchors
```js
for (const anchor of frame.trackedAnchors) {
const pose = frame.getPose(anchor.anchorSpace, referenceSpace);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrframe | data/mdn-content/files/en-us/web/api/xrframe/getpose/index.md | ---
title: "XRFrame: getPose() method"
short-title: getPose()
slug: Web/API/XRFrame/getPose
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRFrame.getPose
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The {{domxref("XRFrame")}} method **`getPose()`** returns the relative position and
orientation—the pose—of one {{domxref("XRSpace")}} to that of another space. With this, you can observe the motion of objects relative to each other and to fixed locations throughout the scene.
For example, to get the position of a controller relative to the viewer's head, you would compare the controller's {{domxref("XRInputSource.gripSpace", "gripSpace")}} to the {{domxref("XRReferenceSpace")}} of type `viewer`.
## Syntax
```js-nolint
getPose(space, baseSpace)
```
### Parameters
- `space`
- : An {{domxref("XRSpace")}} specifying the space for which to obtain an
{{domxref("XRPose")}} describing the item's position and orientation.
- `baseSpace`
- : An {{domxref("XRSpace")}} to use as the base or origin for the purposes of computing
the relative position and orientation.
### Return value
An {{domxref("XRPose")}} object specifying the position and orientation, relative to
the {{domxref("XRSpace")}} indicated by `baseSpace`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrframe | data/mdn-content/files/en-us/web/api/xrframe/gethittestresultsfortransientinput/index.md | ---
title: "XRFrame: getHitTestResultsForTransientInput() method"
short-title: getHitTestResultsForTransientInput()
slug: Web/API/XRFrame/getHitTestResultsForTransientInput
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRFrame.getHitTestResultsForTransientInput
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`getHitTestResultsForTransientInput()`** method of the {{domxref("XRFrame")}} interface returns an array of {{domxref("XRTransientInputHitTestResult")}} objects containing transient input hit test results for a given {{domxref("XRTransientInputHitTestSource")}}.
## Syntax
```js-nolint
getHitTestResultsForTransientInput(hitTestSource)
```
### Parameters
- `hitTestSource`
- : An {{domxref("XRTransientInputHitTestSource")}} object that contains transient input hit test subscriptions.
### Return value
An array of {{domxref("XRTransientInputHitTestResult")}} objects.
## Examples
### Getting transient input hit test results
To request a transient input hit test source, start an {{domxref("XRSession")}} with the `hit-test` session feature enabled. Next, request the hit test source with {{domxref("XRSession.requestHitTestSourceForTransientInput()")}} and store it for later use in the frame loop. Finally, call `getHitTestResultsForTransientInput()` to obtain the result.
```js
const xrSession = navigator.xr.requestSession("immersive-ar", {
requiredFeatures: ["local", "hit-test"],
});
let transientHitTestSource = null;
xrSession
.requestHitTestSourceForTransientInput({
profile: "generic-touchscreen",
offsetRay: new XRRay(),
})
.then((touchScreenHitTestSource) => {
transientHitTestSource = touchScreenHitTestSource;
});
// frame loop
function onXRFrame(time, xrFrame) {
let hitTestResults = xrFrame.getHitTestResultsForTransientInput(
transientHitTestSource,
);
// do things with the transient hit test results
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRTransientInputHitTestResult")}}
- {{domxref("XRTransientInputHitTestSource")}}
- {{domxref("XRRay")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrframe | data/mdn-content/files/en-us/web/api/xrframe/createanchor/index.md | ---
title: "XRFrame: createAnchor() method"
short-title: createAnchor()
slug: Web/API/XRFrame/createAnchor
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRFrame.createAnchor
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`createAnchor()`** method of the {{domxref("XRFrame")}} interface creates a free-floating {{domxref("XRAnchor")}} which will be fixed relative to the real world.
See {{domxref("XRHitTestResult.createAnchor()")}} for creating an anchor from a hit test result that is attached to a real-world object.
## Syntax
```js-nolint
createAnchor(pose, space)
```
### Parameters
- `pose`
- : An {{domxref("XRRigidTransform")}} object with the initial pose where the anchor should be created. The system will make sure that the relationship with the physical world made at this moment in time is maintained as the tracking system's understanding of the world evolves.
- `space`
- : An {{domxref("XRSpace")}} object the pose is relative to.
### Return value
A {{jsxref("Promise")}} resolving to an {{domxref("XRAnchor")}} object.
## Examples
### Creating an anchor
```js
frame.createAnchor(anchorPose, referenceSpace).then(
(anchor) => {
// Do stuff with the anchor (assign objects that will be relative to this anchor)
},
(error) => {
console.error(`Could not create anchor: ${error}`);
},
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRHitTestResult.createAnchor()")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrframe | data/mdn-content/files/en-us/web/api/xrframe/fillposes/index.md | ---
title: "XRFrame: fillPoses() method"
short-title: fillPoses()
slug: Web/API/XRFrame/fillPoses
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRFrame.fillPoses
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`fillPoses()`** method of the {{domxref("XRFrame")}} interface populates a {{jsxref("Float32Array")}} with the matrices of the poses relative to a given base space and returns `true` if successful for all spaces.
## Syntax
```js-nolint
fillPoses(spaces, baseSpace, transforms)
```
### Parameters
- `spaces`
- : An array of {{domxref("XRSpace")}} objects for which to get the poses.
- `baseSpace`
- : An {{domxref("XRSpace")}} object to use as the base or origin for the relative position and orientation.
- `transforms`
- : A {{jsxref("Float32Array")}} that is populated with the matrices of the poses relative to the given `baseSpace`.
### Return value
A boolean indicating if all of the spaces have a valid pose.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the length of `spaces` multiplied by 16 is larger than the number of elements in `transforms`.
## Examples
### Obtaining poses for all joints of a hand
To efficiently get all poses for all 25 joints of each {{domxref("XRHand")}}, you can use the `fillPoses()` method.
```js
let poses1 = new Float32Array(16 * 25);
let poses2 = new Float32Array(16 * 25);
function onXRFrame(xrFrame, renderer) {
let hand1 = xrFrame.session.inputSources[0].hand;
xrFrame.fillPoses(hand1.values(), renderer.referenceSpace, poses1);
let hand2 = xrFrame.session.inputSources[1].hand;
xrFrame.fillPoses(hand2.values(), renderer.referenceSpace, poses2);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRHand")}}
- {{domxref("XRJointSpace")}}
- {{jsxref("Float32Array")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgfontfaceformatelement/index.md | ---
title: SVGFontFaceFormatElement
slug: Web/API/SVGFontFaceFormatElement
page-type: web-api-interface
status:
- deprecated
browser-compat: api.SVGFontFaceFormatElement
---
{{APIRef("SVG")}}{{deprecated_header}}
The **`SVGFontFaceFormatElement`** interface corresponds to the {{SVGElement("font-face-format")}} elements.
Object-oriented access to the attributes of the {{SVGElement("font-face-format")}} element via the SVG DOM is not possible.
{{InheritanceDiagram}}
## Instance properties
_This interface has no properties but inherits properties from its parent, {{domxref("SVGElement")}}._
## Instance methods
_This interface has no methods but inherits methods from its parent, {{domxref("SVGElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{SVGElement("font-face-format")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/syncmanager/index.md | ---
title: SyncManager
slug: Web/API/SyncManager
page-type: web-api-interface
status:
- experimental
browser-compat: api.SyncManager
---
{{APIRef("Background Sync")}}{{SeeCompatTable}}
The **`SyncManager`** interface of the {{domxref("Background Synchronization API", "", "", "nocode")}} provides an interface for registering and listing sync registrations.
## Instance properties
None.
## Instance methods
- {{domxref("SyncManager.register()")}} {{Experimental_Inline}}
- : Create a new sync registration and return a {{jsxref("Promise")}}.
- {{domxref("SyncManager.getTags()")}} {{Experimental_Inline}}
- : Return a list of developer-defined identifiers for `SyncManager` registrations.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/syncmanager | data/mdn-content/files/en-us/web/api/syncmanager/register/index.md | ---
title: "SyncManager: register() method"
short-title: register()
slug: Web/API/SyncManager/register
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.SyncManager.register
---
{{APIRef("Background Sync")}}{{SeeCompatTable}}
The **`register()`** method of the {{domxref("SyncManager")}} interface registers a synchronization event, triggering a {{domxref("ServiceWorkerGlobalScope.sync_event", "sync")}} event inside the associated service worker as soon as network connectivity is available.
## Syntax
```js-nolint
register(tag)
```
### Parameters
- `tag`
- : An identifier for this synchronization event. This will be the value of the `tag` property of the {{domxref("SyncEvent")}} that gets passed into the service worker's {{domxref("ServiceWorkerGlobalScope.sync_event", "sync")}} event handler.
### Return value
A {{jsxref("Promise")}} that resolves to {{jsxref("undefined")}}.
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if current service worker is not active.
- `NotAllowedError` {{domxref("DOMException")}}
- : Thrown if background sync has been disabled by the user.
## Examples
The following asynchronous function registers a background sync from a browsing context:
```js
async function syncMessagesLater() {
const registration = await navigator.serviceWorker.ready;
try {
await registration.sync.register("sync-messages");
} catch {
console.log("Background Sync could not be registered!");
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/syncmanager | data/mdn-content/files/en-us/web/api/syncmanager/gettags/index.md | ---
title: "SyncManager: getTags() method"
short-title: getTags()
slug: Web/API/SyncManager/getTags
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.SyncManager.getTags
---
{{APIRef("Background Sync")}}{{SeeCompatTable}}
The **`getTags()`** method of the
{{domxref("SyncManager")}} interface returns a list of developer-defined identifiers for
`SyncManager` registrations.
## Syntax
```js-nolint
getTags()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that resolves to an array of strings
containing developer-defined identifiers for `SyncManager` registrations.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/performancepainttiming/index.md | ---
title: PerformancePaintTiming
slug: Web/API/PerformancePaintTiming
page-type: web-api-interface
browser-compat: api.PerformancePaintTiming
---
{{APIRef("Performance API")}}
The **`PerformancePaintTiming`** interface provides timing information about "paint" (also called "render") operations during web page construction. "Paint" refers to conversion of the render tree to on-screen pixels.
There are two key paint moments this API provides:
- {{Glossary("First paint")}} (FP): Time when anything is rendered. Note that the marking of the first paint is optional, not all user agents report it.
- {{Glossary("First contentful paint")}} (FCP): Time when the first bit of DOM text or image content is rendered.
A third key paint moment is provided by the {{domxref("LargestContentfulPaint")}} API:
- {{Glossary("Largest contentful paint")}} (LCP): Render time of the largest image or text block visible within the viewport, recorded from when the page first begins to load.
The data this API provides helps you minimize the time that users have to wait before they can see the site's content start to appear. Decreasing the time until these key paint moments make sites feel more responsive, performant, and engaging for your users.
Like other Performance APIs, this API extends {{domxref("PerformanceEntry")}}.
{{InheritanceDiagram}}
## Instance properties
This interface has no properties but it extends the following {{domxref("PerformanceEntry")}} properties by qualifying and constraining the properties as follows:
- {{domxref("PerformanceEntry.entryType")}}
- : Returns "`paint`".
- {{domxref("PerformanceEntry.name")}}
- : Returns either `"first-paint"` or `"first-contentful-paint"`.
- {{domxref("PerformanceEntry.startTime")}}
- : Returns the {{domxref("DOMHighResTimeStamp","timestamp")}} when the paint occurred.
- {{domxref("PerformanceEntry.duration")}}
- : Returns 0.
## Instance methods
This interface has no methods.
## Examples
### Getting paint timings
Example using a {{domxref("PerformanceObserver")}}, which notifies of new `paint` performance entries as they are recorded in the browser's performance timeline. Use the `buffered` option to access entries from before the observer creation.
```js
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach((entry) => {
console.log(
`The time to ${entry.name} was ${entry.startTime} milliseconds.`,
);
// Logs "The time to first-paint was 386.7999999523163 milliseconds."
// Logs "The time to first-contentful-paint was 400.6999999284744 milliseconds."
});
});
observer.observe({ type: "paint", buffered: true });
```
Example using {{domxref("Performance.getEntriesByType()")}}, which only shows `paint` performance entries present in the browser's performance timeline at the time you call this method:
```js
const entries = performance.getEntriesByType("paint");
entries.forEach((entry) => {
console.log(`The time to ${entry.name} was ${entry.startTime} milliseconds.`);
// Logs "The time to first-paint was 386.7999999523163 milliseconds."
// Logs "The time to first-contentful-paint was 400.6999999284744 milliseconds."
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
### See also
- {{domxref("LargestContentfulPaint")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svganimatecolorelement/index.md | ---
title: SVGAnimateColorElement
slug: Web/API/SVGAnimateColorElement
page-type: web-api-interface
status:
- deprecated
browser-compat: api.SVGAnimateColorElement
---
{{APIRef("SVG")}}{{deprecated_header}}
The **`SVGAnimateColorElement`** interface corresponds to the `<animateColor>` 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/gamepadpose/index.md | ---
title: GamepadPose
slug: Web/API/GamepadPose
page-type: web-api-interface
status:
- experimental
browser-compat: api.GamepadPose
---
{{securecontext_header}}{{APIRef("Gamepad API")}}{{SeeCompatTable}}
The **`GamepadPose`** interface of the [Gamepad API](/en-US/docs/Web/API/Gamepad_API) represents the pose of a [WebVR](/en-US/docs/Web/API/WebVR_API) controller at a given timestamp (which includes orientation, position, velocity, and acceleration information).
This interface is accessible through the {{domxref("Gamepad.pose")}} property.
## Instance properties
- {{domxref("GamepadPose.hasOrientation")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a boolean indicating whether the gamepad is capable of returning orientation information (`true`) or not (`false`).
- {{domxref("GamepadPose.hasPosition")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a boolean indicating whether the gamepad is capable of returning position information (`true`) or not (`false`).
- {{domxref("GamepadPose.position")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the position of the {{domxref("Gamepad")}} as a 3D vector.
- {{domxref("GamepadPose.linearVelocity")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the linear velocity of the {{domxref("Gamepad")}}, in meters per second.
- {{domxref("GamepadPose.linearAcceleration")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the linear acceleration of the {{domxref("Gamepad")}}, in meters per second per second.
- {{domxref("GamepadPose.orientation")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the orientation of the {{domxref("Gamepad")}}, as a quarternion value.
- {{domxref("GamepadPose.angularVelocity")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the angular velocity of the {{domxref("Gamepad")}}, in radians per second.
- {{domxref("GamepadPose.angularAcceleration")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the angular acceleration of the {{domxref("Gamepad")}}, in meters per second per second.
## Examples
TBD.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
- [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepadpose | data/mdn-content/files/en-us/web/api/gamepadpose/hasposition/index.md | ---
title: "GamepadPose: hasPosition property"
short-title: hasPosition
slug: Web/API/GamepadPose/hasPosition
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GamepadPose.hasPosition
---
{{APIRef("WebVR API")}}{{SeeCompatTable}}
The **`hasPosition`** read-only property of the {{domxref("GamepadPose")}} interface returns a boolean value stating whether the {{domxref("Gamepad")}} can track and return position information.
## Value
A boolean value.
## Examples
TBD
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
- [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepadpose | data/mdn-content/files/en-us/web/api/gamepadpose/hasorientation/index.md | ---
title: "GamepadPose: hasOrientation property"
short-title: hasOrientation
slug: Web/API/GamepadPose/hasOrientation
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GamepadPose.hasOrientation
---
{{APIRef("WebVR API")}}{{SeeCompatTable}}
The **`hasOrientation`** read-only property of the {{domxref("GamepadPose")}} interface returns a boolean value stating whether the {{domxref("Gamepad")}} can track and return orientation information.
## Value
A boolean value.
## Examples
TBD
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
- [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepadpose | data/mdn-content/files/en-us/web/api/gamepadpose/position/index.md | ---
title: "GamepadPose: position property"
short-title: position
slug: Web/API/GamepadPose/position
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GamepadPose.position
---
{{APIRef("WebVR API")}}{{SeeCompatTable}}
The **`position`** read-only property of the {{domxref("GamepadPose")}} interface returns the position of the {{domxref("Gamepad")}} as a 3D vector.
The coordinate system is as follows:
- Positive X is to the user's right.
- Positive Y is up.
- Positive Z is behind the user.
Positions are measured in meters from an origin point — this point is the position the sensor was first read at.
## Value
A {{jsxref("Float32Array")}}, or `null` if the gamepad is not able to provide position data.
> **Note:** User agents may provide emulated position values through certain techniques; when doing so they should still report {{domxref("GamepadPose.hasPosition")}} as false.
## Examples
TBD
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
- [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepadpose | data/mdn-content/files/en-us/web/api/gamepadpose/orientation/index.md | ---
title: "GamepadPose: orientation property"
short-title: orientation
slug: Web/API/GamepadPose/orientation
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GamepadPose.orientation
---
{{APIRef("WebVR API")}}{{SeeCompatTable}}
The **`orientation`** read-only property of the {{domxref("GamepadPose")}} interface returns the orientation of the {{domxref("Gamepad")}}, as a quarternion value.
The value is a {{jsxref("Float32Array")}}, made up of the following values:
- pitch — rotation around the X axis.
- yaw — rotation around the Y axis.
- roll — rotation around the Z axis.
- w — the fourth dimension (usually 1).
The orientation yaw (rotation around the y axis) is relative to the initial yaw of the sensor when it was first read.
## Value
A {{jsxref("Float32Array")}}, or `null` if the VR sensor is not able to provide orientation data.
## Examples
TBD
> **Note:** An orientation of `{ x: 0, y: 0, z: 0, w: 1 }` is considered to be "forward".
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
- [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepadpose | data/mdn-content/files/en-us/web/api/gamepadpose/angularvelocity/index.md | ---
title: "GamepadPose: angularVelocity property"
short-title: angularVelocity
slug: Web/API/GamepadPose/angularVelocity
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GamepadPose.angularVelocity
---
{{APIRef("WebVR API")}}{{SeeCompatTable}}
The **`angularVelocity`** read-only property of the {{domxref("GamepadPose")}} interface returns an array representing the angular velocity vector of the {{domxref("Gamepad")}}, in radians per second.
In other words, the current velocity at which the sensor is rotating around the `x`, `y`, and `z` axes.
## Value
A {{jsxref("Float32Array")}}, or `null` if the gamepad is not able to provide angular velocity information.
## Examples
TBD
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
- [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepadpose | data/mdn-content/files/en-us/web/api/gamepadpose/angularacceleration/index.md | ---
title: "GamepadPose: angularAcceleration property"
short-title: angularAcceleration
slug: Web/API/GamepadPose/angularAcceleration
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GamepadPose.angularAcceleration
---
{{APIRef("WebVR API")}}{{SeeCompatTable}}
The **`angularAcceleration`** read-only property of the {{domxref("GamepadPose")}} interface returns an array representing the angular acceleration vector of the {{domxref("Gamepad")}}, in meters per second per second.
In other words, the current acceleration of the sensor's rotation around the `x`, `y`, and `z` axes.
## Value
A {{jsxref("Float32Array")}}, or `null` if the gamepad is not able to provide angular acceleration information.
## Examples
TBD
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
- [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepadpose | data/mdn-content/files/en-us/web/api/gamepadpose/linearvelocity/index.md | ---
title: "GamepadPose: linearVelocity property"
short-title: linearVelocity
slug: Web/API/GamepadPose/linearVelocity
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GamepadPose.linearVelocity
---
{{APIRef("WebVR API")}}{{SeeCompatTable}}
The **`linearVelocity`** read-only property of the {{domxref("GamepadPose")}} interface returns an array representing the linear velocity vector of the {{domxref("Gamepad")}}, in meters per second.
In other words, the current velocity at which the sensor is moving along the `x`, `y`, and `z` axes.
## Value
A {{jsxref("Float32Array")}}, or `null` if the gamepad is not able to provide linear velocity data.
## Examples
TBD
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
- [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepadpose | data/mdn-content/files/en-us/web/api/gamepadpose/linearacceleration/index.md | ---
title: "GamepadPose: linearAcceleration property"
short-title: linearAcceleration
slug: Web/API/GamepadPose/linearAcceleration
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GamepadPose.linearAcceleration
---
{{APIRef("WebVR API")}}{{SeeCompatTable}}
The **`linearAcceleration`** read-only property of the {{domxref("GamepadPose")}} interface returns an array representing the linear acceleration vector of the {{domxref("Gamepad")}}, in meters per second per second.
In other words, the current acceleration of the sensor, along the `x`, `y`, and `z` axes.
## Value
A {{jsxref("Float32Array")}}, or `null` if the gamepad is not able to provide linear acceleration data.
## Examples
TBD
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
- [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgimageelement/index.md | ---
title: SVGImageElement
slug: Web/API/SVGImageElement
page-type: web-api-interface
browser-compat: api.SVGImageElement
---
{{APIRef("SVG")}}
The **`SVGImageElement`** interface corresponds to the {{SVGElement("image")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface also inherits properties from its parent, {{domxref("SVGGraphicsElement")}}._
- {{domxref("SVGImageElement.href")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("href")}} or {{SVGAttr("xlink:href")}} {{deprecated_inline}} attribute of the given {{SVGElement("image")}} element.
- {{domxref("SVGImageElement.decoding")}}
- : Represents a hint given to the browser on how it should decode the image. If this value is provided, it must be one of the possible permitted values: `"sync"` to decode the image synchronously, `"async"` to decode it asynchronously, or `"auto"` to indicate no preference (which is the default).
- {{domxref("SVGImageElement.height")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("height")}} attribute of the given {{SVGElement("image")}} element.
- {{domxref("SVGImageElement.preserveAspectRatio")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedPreserveAspectRatio")}} corresponding to the {{SVGAttr("preserveAspectRatio")}} attribute of the given {{SVGElement("image")}} element.
- {{domxref("SVGImageElement.width")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("width")}} attribute of the given {{SVGElement("image")}} element.
- {{domxref("SVGImageElement.x")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x")}} attribute of the given {{SVGElement("image")}} element.
- {{domxref("SVGImageElement.y")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("y")}} attribute of the given {{SVGElement("image")}} element.
## Instance methods
_This interface also inherits methods from its parent interface, {{domxref("SVGGraphicsElement")}}._
- {{domxref("SVGImageElement.decode()")}}
- : Initiates asynchronous decoding of the image data. Returns a {{jsxref("Promise")}} which resolves once the image data is ready to be used.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/svgimageelement | data/mdn-content/files/en-us/web/api/svgimageelement/y/index.md | ---
title: "SVGImageElement: y property"
short-title: "y"
slug: Web/API/SVGImageElement/y
page-type: web-api-instance-property
browser-compat: api.SVGImageElement.y
---
{{APIRef("SVG")}}
The **`y`** read-only property of the
{{domxref("SVGImageElement")}} interface returns an {{domxref("SVGAnimatedLength")}}
corresponding to the {{SVGAttr("y")}} attribute of the given {{SVGElement("image")}}
element.
## Value
An {{domxref("SVGAnimatedLength")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/svgimageelement | data/mdn-content/files/en-us/web/api/svgimageelement/decoding/index.md | ---
title: "SVGImageElement: decoding property"
short-title: decoding
slug: Web/API/SVGImageElement/decoding
page-type: web-api-instance-property
browser-compat: api.SVGImageElement.decoding
---
{{APIRef("SVG")}}
The **`decoding`** property of the {{domxref("SVGImageElement")}} interface provides a hint to the browser as to whether it should perform image decoding synchronously or asynchronously.
## Value
A string representing the decoding hint. Possible values are:
- `"sync"`
- : Decode the image synchronously for atomic presentation with other content.
- `"async"`
- : Decode the image asynchronously and allow other content to be rendered before this completes.
- `"auto"`
- : No preference for the decoding mode; the browser decides what is best for the user. This is the default value, but different browsers have different defaults:
- Chromium defaults to `"sync"`.
- Firefox defaults to `"async"`.
- Safari defaults to `"sync"` except in a small number of circumstances.
## Usage notes
The `decoding` property provides a hint to the browser as to whether it should perform image decoding along with other tasks in a single step (`"sync"`), or allow other content to be rendered before this completes (`"async"`). In reality, the differences between the two values are often difficult to perceive and, where there are differences, there is often a better way.
For images that are inserted into the DOM inside the viewport, `"async"` can result in flashes of unstyled content, while `"sync"` can result in small amounts of [jank](/en-US/docs/Glossary/Jank). Using the {{domxref("SVGImageElement.decode()")}} method is usually a better way to achieve atomic presentation without holding up other content.
For images inserted into the DOM outside of the viewport, modern browsers will usually decode them before they are scrolled into view and there will be no noticeable difference using either value.
## Examples
In the below example, you'll likely get an empty image shown on the page as the image is downloaded. Setting `decoding` won't prevent that.
```js
const SVG_NS = "http://www.w3.org/2000/svg";
const svg = document.querySelector("svg");
const img = document.createElementNS(SVG_NS, "image");
img.decoding = "sync";
img.setAttribute("href", "img/logo.svg");
svg.appendChild(img);
```
Inserting an image after download can make the `decoding` property more relevant:
```js
async function loadImage(url, elem) {
return new Promise((resolve, reject) => {
elem.onload = () => resolve(elem);
elem.onerror = reject;
elem.src = url;
});
}
const SVG_NS = "http://www.w3.org/2000/svg";
const svg = document.querySelector("svg");
const img = document.createElementNS(SVG_NS, "image");
await loadImage("img/logo.svg", img);
// Using `sync` can ensure other content is only updated with the image
img.decoding = "sync";
svg.appendChild(img);
const text = document.createElementNS(SVG_NS, "text");
text.textContent = "Image is fully loaded!";
svg.appendChild(text);
```
A better solution, however, is to use the {{domxref("SVGImageElement.decode()")}} method to solve this problem. It provides a way to asynchronously decode an image, delaying inserting it into the DOM until it is fully downloaded and decoded, thereby avoiding the empty image problem mentioned above. This is particularly useful if you're dynamically swapping an existing image for a new one, and also prevents unrelated paints outside of this code from being held up while the image is decoding.
Using `img.decoding = "async"` may avoid holding up other content from displaying if the decoding time is long:
```js
const SVG_NS = "http://www.w3.org/2000/svg";
const svg = document.querySelector("svg");
const img = document.createElementNS(SVG_NS, "image");
img.decoding = "async";
img.setAttribute("href", "img/logo.svg");
svg.appendChild(img);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("SVGImageElement.decode()")}} method
- The SVG {{SVGElement("image")}} element {{SVGAttr("decoding")}} attribute.
| 0 |
data/mdn-content/files/en-us/web/api/svgimageelement | data/mdn-content/files/en-us/web/api/svgimageelement/x/index.md | ---
title: "SVGImageElement: x property"
short-title: x
slug: Web/API/SVGImageElement/x
page-type: web-api-instance-property
browser-compat: api.SVGImageElement.x
---
{{APIRef("SVG")}}
The **`x`** read-only property of the
{{domxref("SVGImageElement")}} interface returns an {{domxref("SVGAnimatedLength")}}
corresponding to the {{SVGAttr("x")}} attribute of the given {{SVGElement("image")}}
element.
## Value
An {{domxref("SVGAnimatedLength")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/svgimageelement | data/mdn-content/files/en-us/web/api/svgimageelement/decode/index.md | ---
title: "SVGImageElement: decode() method"
short-title: decode()
slug: Web/API/SVGImageElement/decode
page-type: web-api-instance-method
browser-compat: api.SVGImageElement.decode
---
{{APIRef("SVG")}}
The **`decode()`** method of the
{{domxref("SVGImageElement")}} interface initiates asynchronous decoding of an image,
returning a {{jsxref('Promise')}} that resolves once the image is decoded and it is safe to append
it to the DOM.
## Syntax
```js-nolint
decode()
```
### Parameters
None.
### Return value
A {{jsxref('Promise')}} that fulfills with `undefined` once the image data is ready to be used, for example by appending it to the DOM, replacing an existing image, and so forth.
### Exceptions
None.
## Examples
In the below example, you'll likely get an empty image shown on the page as the image is downloaded:
```js
const SVG_NS = "http://www.w3.org/2000/svg";
const svg = document.querySelector("svg");
const img = document.createElementNS(SVG_NS, "image");
img.src = "img/logo.svg";
svg.appendChild(img);
```
Using `decode()` will delay inserting the image into the DOM until it is fully downloaded and decoded, thereby avoiding the empty image problem:
```js
const SVG_NS = "http://www.w3.org/2000/svg";
const svg = document.querySelector("svg");
async function getImage() {
const img = document.createElementNS(SVG_NS, "image");
img.src = "img/logo.svg";
await img.decode();
svg.appendChild(img);
const text = document.createElementNS(SVG_NS, "text");
text.textContent = "Image is fully loaded!";
svg.appendChild(text);
}
```
This is particularly useful if you're dynamically swapping an existing image for a new one, and also prevents unrelated paints outside of this code from being held up while the image is decoding.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLImageElement.decode()")}}: The same thing, but for HTML `<img>` elements
- [What does the image decoding attribute actually do?](https://www.tunetheweb.com/blog/what-does-the-image-decoding-attribute-actually-do/) on tunetheweb.com (2023)
| 0 |
data/mdn-content/files/en-us/web/api/svgimageelement | data/mdn-content/files/en-us/web/api/svgimageelement/width/index.md | ---
title: "SVGImageElement: width property"
short-title: width
slug: Web/API/SVGImageElement/width
page-type: web-api-instance-property
browser-compat: api.SVGImageElement.width
---
{{APIRef("SVG")}}
The **`width`** read-only property of the
{{domxref("SVGImageElement")}} interface returns an {{domxref("SVGAnimatedLength")}}
corresponding to the {{SVGAttr("width")}} attribute of the given {{SVGElement("image")}}
element.
## Value
An {{domxref("SVGAnimatedLength")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/svgimageelement | data/mdn-content/files/en-us/web/api/svgimageelement/height/index.md | ---
title: "SVGImageElement: height property"
short-title: height
slug: Web/API/SVGImageElement/height
page-type: web-api-instance-property
browser-compat: api.SVGImageElement.height
---
{{APIRef("SVG")}}
The **`height`** read-only property of the
{{domxref("SVGImageElement")}} interface returns an {{domxref("SVGAnimatedLength")}}
corresponding to the {{SVGAttr("height")}} attribute of the given
{{SVGElement("image")}} element.
## Value
An {{domxref("SVGAnimatedLength")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/svgimageelement | data/mdn-content/files/en-us/web/api/svgimageelement/preserveaspectratio/index.md | ---
title: "SVGImageElement: preserveAspectRatio property"
short-title: preserveAspectRatio
slug: Web/API/SVGImageElement/preserveAspectRatio
page-type: web-api-instance-property
browser-compat: api.SVGImageElement.preserveAspectRatio
---
{{APIRef("SVG")}}
The **`preserveAspectRatio`** read-only
property of the {{domxref("SVGImageElement")}} interface returns an
{{domxref("SVGAnimatedPreserveAspectRatio")}} corresponding to the
{{SVGAttr("preserveAspectRatio")}} attribute of the given {{SVGElement("image")}}
element.
## Value
An {{domxref("SVGAnimatedPreserveAspectRatio")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svglineelement/index.md | ---
title: SVGLineElement
slug: Web/API/SVGLineElement
page-type: web-api-interface
browser-compat: api.SVGLineElement
---
{{APIRef("SVG")}}
The **`SVGLineElement`** interface provides access to the properties of {{ SVGElement("line") }} elements, as well as methods to manipulate them.
{{InheritanceDiagram}}
## Instance properties
_This interface also inherits properties from its parent, {{domxref("SVGGeometryElement")}}._
- {{domxref("SVGLineElement.x1")}} {{ReadOnlyInline}}
- : Returns an {{domxref("SVGAnimatedLength")}} that corresponds to attribute {{SVGAttr("x1")}} on the given {{SVGElement("line")}} element.
- {{domxref("SVGLineElement.y1")}} {{ReadOnlyInline}}
- : Returns an {{domxref("SVGAnimatedLength")}} that corresponds to attribute {{SVGAttr("y1")}} on the given {{SVGElement("line")}} element.
- {{domxref("SVGLineElement.x2")}} {{ReadOnlyInline}}
- : Returns an {{domxref("SVGAnimatedLength")}} that corresponds to attribute {{SVGAttr("x2")}} on the given {{SVGElement("line")}} element.
- {{domxref("SVGLineElement.y2")}} {{ReadOnlyInline}}
- : Returns an {{domxref("SVGAnimatedLength")}} that corresponds to attribute {{SVGAttr("y2")}} on the given {{SVGElement("line")}} element.
## Instance methods
_This interface doesn't implement any specific methods, but inherits methods from its parent interface, {{domxref("SVGGeometryElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{SVGElement("line")}} SVG Element
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/paymentrequestupdateevent/index.md | ---
title: PaymentRequestUpdateEvent
slug: Web/API/PaymentRequestUpdateEvent
page-type: web-api-interface
browser-compat: api.PaymentRequestUpdateEvent
---
{{securecontext_header}}{{APIRef("Payment Request API")}}
The **`PaymentRequestUpdateEvent`** interface is used for events sent to a {{domxref("PaymentRequest")}} instance when changes are made to shipping-related information for a pending {{domxref("PaymentRequest")}}. Those events are:
- {{domxref("PaymentRequest.shippingaddresschange_event", "shippingaddresschange")}}
- : Dispatched whenever the user changes their shipping address.
- {{domxref("PaymentRequest.shippingoptionchange_event", "shippingoptionchange")}}
- : Dispatched whenever the user changes a shipping option.
{{InheritanceDiagram}}
## Constructor
- {{domxref("PaymentRequestUpdateEvent.PaymentRequestUpdateEvent()","PaymentRequestUpdateEvent()")}}
- : Creates a new `PaymentRequestUpdateEvent` object.
## Instance properties
_Provides only the properties inherited from its parent interface, {{domxref("Event")}}._
## Instance methods
_In addition to methods inherited from the parent interface, {{domxref("Event")}}, `PaymentRequestUpdateEvent` offers the following methods:_
- {{domxref("PaymentRequestUpdateEvent.updateWith()")}}
- : If the event handler determines that information included in the payment request needs to be changed, or that new information needs to be added, it calls `updateWith()` with the information that needs to be replaced or added.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Payment Request API](/en-US/docs/Web/API/Payment_Request_API/Using_the_Payment_Request_API)
| 0 |
data/mdn-content/files/en-us/web/api/paymentrequestupdateevent | data/mdn-content/files/en-us/web/api/paymentrequestupdateevent/updatewith/index.md | ---
title: "PaymentRequestUpdateEvent: updateWith() method"
short-title: updateWith()
slug: Web/API/PaymentRequestUpdateEvent/updateWith
page-type: web-api-instance-method
browser-compat: api.PaymentRequestUpdateEvent.updateWith
---
{{APIRef("Payment Request API")}}{{securecontext_header}}
The **`updateWith()`** method of the
{{domxref("PaymentRequestUpdateEvent")}} interface updates the details of an existing
{{domxref("PaymentRequest")}}.
## Syntax
```js-nolint
updateWith(details)
```
### Parameters
- `details`
- : An object specifying the changes applied to the payment request:
- `displayItems` {{optional_inline}}
- : An array of objects, each describing one line item for the payment request. These represent the line items on a receipt or invoice, each with the following properties:
- `amount`
- : An object describing the monetary value of the item. This object includes the following fields:
- `currency`
- : A string containing a valid 3-letter [ISO 4217](https://www.iso.org/iso-4217-currency-codes.html) currency identifier ([ISO 4217](https://en.wikipedia.org/wiki/ISO_4217)) indicating the currency used for the payment `value`.
- `value`
- : A string containing a valid decimal value representing the mount of currency constituting the payment amount. This string must only contain an optional leading "-" to indicate a negative value, then one or more digits from 0 to 9, and an optional decimal point (".", regardless of locale) followed by at least one more digit. No whitespace is permitted.
- `label`
- : A string specifying a human-readable name or description of the item or service being charged for. This may be displayed to the user by the {{Glossary("user agent")}}, depending on the design of the interface.
- `pending`
- : A Boolean value which is `true` if the specified `amount` has not yet been finalized. This can be used to show items such as shipping or tax amounts that depend upon the selection of shipping address, shipping option, or so forth. The user agent may show this information but is not required to do so.
- `error` {{optional_inline}} {{deprecated_inline}} {{non-standard_inline}}
- : A string specifying an error message to present to the user*.* When calling `updateWith()`, including `error` in the updated data causes the {{Glossary("user agent")}} to display the text as a general error message. For address field-specific errors, use the `shippingAddressErrors` field.
- `modifiers` {{optional_inline}}
- : An {{jsxref("Array")}} of `PaymentDetailsModifier` objects, whose properties are described in {{domxref("PaymentRequestEvent.modifiers")}}.
For example, you can use one to adjust the total payment amount based on the selected payment method ("5% cash discount!").
- `shippingAddressErrors` {{optional_inline}} {{deprecated_inline}} {{non-standard_inline}}
- : An object which includes an error message for each property of the shipping address that could not be validated.
- `shippingOptions` {{optional_inline}} {{deprecated_inline}} {{non-standard_inline}}
- : An array of objects, each describing one available shipping option from which the user may choose.
- `total` {{optional_inline}}
- : An object with the same properties as the objects in `displayItems` providing an updated total for the payment. Make sure this equals the sum of all of the items in `displayItems`. _This is not calculated automatically_. You must update this value yourself anytime the total amount due changes. This lets you have flexibility for how to handle things like tax, discounts, and other adjustments to the total price charged.
### Return value
None ({{jsxref("undefined")}}).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/paymentrequestupdateevent | data/mdn-content/files/en-us/web/api/paymentrequestupdateevent/paymentrequestupdateevent/index.md | ---
title: "PaymentRequestUpdateEvent: PaymentRequestUpdateEvent() constructor"
short-title: PaymentRequestUpdateEvent()
slug: Web/API/PaymentRequestUpdateEvent/PaymentRequestUpdateEvent
page-type: web-api-constructor
browser-compat: api.PaymentRequestUpdateEvent.PaymentRequestUpdateEvent
---
{{APIRef("Payment Request API")}}{{securecontext_header}}
The **`PaymentRequestUpdateEvent()`** constructor creates a new
{{domxref("PaymentRequestUpdateEvent")}} object which enables a web page to update the
details of a {{domxref("PaymentRequest")}} in response to a user action. Actual updates
are made by passing options to the
{{domxref('PaymentRequestUpdateEvent.updateWith','updateWith()')}} method.
## Syntax
```js-nolint
new PaymentRequestUpdateEvent()
```
### Parameters
None.
### Return value
A new `PaymentRequestUpdateEvent`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/idle_detection_api/index.md | ---
title: Idle Detection API
slug: Web/API/Idle_Detection_API
page-type: web-api-overview
status:
- experimental
browser-compat: api.IdleDetector
---
{{securecontext_header}}{{DefaultAPISidebar("Idle Detection API")}}{{SeeCompatTable}}
The Idle Detection API provides a means to detect the user's idle status, active, idle, and locked, specifically, and to be notified of changes to idle status without polling from a script.
## Concepts and Usage
Native applications and browser extensions use idle detection base user experiences on when a user is interacting with a device. For example, chat applications can show other users of an application whether someone is available. Other applications might choose to show notifications only when a user is interacting with the app. A web application could use this API for similar use cases. Additionally, a progressive web app could use idle detection to trigger a service worker update when the app isn't being used.
## Interfaces
- {{domxref("IdleDetector")}} {{Experimental_Inline}}
- : Provides methods and events for detecting user activity on a device or screen.
## Examples
The following example shows creating a detector and logging changes to the
user's idle state. A button is used to get the necessary user activation before
requesting permission.
```js
const controller = new AbortController();
const signal = controller.signal;
startButton.addEventListener("click", async () => {
if ((await IdleDetector.requestPermission()) !== "granted") {
console.error("Idle detection permission denied.");
return;
}
try {
const idleDetector = new IdleDetector();
idleDetector.addEventListener("change", () => {
const userState = idleDetector.userState;
const screenState = idleDetector.screenState;
console.log(`Idle change: ${userState}, ${screenState}.`);
});
await idleDetector.start({
threshold: 60_000,
signal,
});
console.log("IdleDetector is active.");
} catch (err) {
// Deal with initialization errors like permission denied,
// running outside of top-level frame, etc.
console.error(err.name, err.message);
}
});
stopButton.addEventListener("click", () => {
controller.abort();
console.log("IdleDetector is stopped.");
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/cssmathsum/index.md | ---
title: CSSMathSum
slug: Web/API/CSSMathSum
page-type: web-api-interface
browser-compat: api.CSSMathSum
---
{{APIRef("CSS Typed Object Model API")}}
The **`CSSMathSum`** interface of the {{domxref('CSS_Object_Model#css_typed_object_model','','',' ')}} represents the result obtained by calling {{domxref('CSSNumericValue.add','add()')}}, {{domxref('CSSNumericValue.sub','sub()')}}, or {{domxref('CSSNumericValue.toSum','toSum()')}} on {{domxref('CSSNumericValue')}}.
A CSSMathSum is the object type returned when the [`StylePropertyMapReadOnly.get()`](/en-US/docs/Web/API/StylePropertyMapReadOnly/get) method is used on a CSS property whose value is created with a [`calc()`](/en-US/docs/Web/CSS/calc) function.
{{InheritanceDiagram}}
## Constructor
- {{domxref("CSSMathSum.CSSMathSum", "CSSMathSum()")}} {{Experimental_Inline}}
- : Creates a new `CSSMathSum` object.
## Instance properties
- {{domxref('CSSMathSum.values')}}
- : Returns a {{domxref('CSSNumericArray')}} object which contains one or more {{domxref('CSSNumericValue')}} objects.
## Static methods
_The interface may also inherit methods from its parent interface, {{domxref("CSSMathValue")}}._
## Instance methods
_The interface may also inherit methods from its parent interface, {{domxref("CSSMathValue")}}._
## Examples
We create an element with a [`width`](/en-US/docs/Web/CSS/width) determined using a [`calc()`](/en-US/docs/Web/CSS/calc) function, then {{domxref("console/log_static", "console.log()")}} the `operator` and `values`, and dig into the values a bit.
```html
<div>has width</div>
```
We assign a `width`
```css
div {
width: calc(30% - 20px);
}
```
We add the JavaScript
```js
const styleMap = document.querySelector("div").computedStyleMap();
console.log(styleMap.get("width")); // CSSMathSum {values: CSSNumericArray, operator: "sum"}
console.log(styleMap.get("width").operator); // 'sum'
console.log(styleMap.get("width").values); // CSSNumericArray {0: CSSUnitValue, 1: CSSUnitValue, length: 2}
console.log(styleMap.get("width").values[0]); // CSSUnitValue {value: 30, unit: "percent"}
console.log(styleMap.get("width").values[0].value); // 30
console.log(styleMap.get("width").values[0].unit); // 'percent'
console.log(styleMap.get("width").values[1]); // CSSUnitValue {value: -20, unit: "px"}
console.log(styleMap.get("width").values[1].value); // -20
console.log(styleMap.get("width").values[1].unit); // 'px'
```
{{EmbedLiveSample("Examples", 120, 300)}}
The specification is still evolving. In the future we may write the last three lines as:
```js
console.log(styleMap.get("width").values[1]); // CSSMathNegate {value: CSSUnitValue, operator: "negate"}
console.log(styleMap.get("width").values[1].value); // CSSUnitValue {value: 20, unit: "px"}
console.log(styleMap.get("width").values[1].value.unit); // 'px'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssmathsum | data/mdn-content/files/en-us/web/api/cssmathsum/values/index.md | ---
title: "CSSMathSum: values property"
short-title: values
slug: Web/API/CSSMathSum/values
page-type: web-api-instance-property
browser-compat: api.CSSMathSum.values
---
{{APIRef("CSS Typed Object Model API")}}
The **`CSSMathSum.values`** read-only property
of the {{domxref("CSSMathSum")}} interface returns a {{domxref('CSSNumericArray')}}
object which contains one or more {{domxref('CSSNumericValue')}} objects.
## Value
A {{domxref('CSSNumericArray')}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.