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/xrsession | data/mdn-content/files/en-us/web/api/xrsession/requestreferencespace/index.md | ---
title: "XRSession: requestReferenceSpace() method"
short-title: requestReferenceSpace()
slug: Web/API/XRSession/requestReferenceSpace
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRSession.requestReferenceSpace
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`requestReferenceSpace()`** method of the
{{DOMxRef("XRSession")}} interface returns a {{JSxRef("promise")}} that resolves with
an instance of either {{DOMxRef("XRReferenceSpace")}}
or {{DOMxRef("XRBoundedReferenceSpace")}} as appropriate given the type of reference
space requested.
## Syntax
```js-nolint
requestReferenceSpace(referenceSpaceType)
```
### Parameters
- `type`
- : A string specifying the type of reference space for which an instance is to be returned.
The string must be one of the values below.
### Return value
A {{JSxRef("Promise")}} that resolves with an {{DOMxRef("XRReferenceSpace")}} object.
The types of reference space are listed below, with brief information about their use cases and which interface is used to implement them.
- `bounded-floor`
- : An {{domxref("XRBoundedReferenceSpace")}} similar to the `local` type, except the user is not expected to move outside a predetermined boundary, given by the {{domxref("XRBoundedReferenceSpace.boundsGeometry", "boundsGeometry")}} in the returned object.
- `local`
- : An {{domxref("XRReferenceSpace")}} tracking space whose native origin is located near the viewer's position at the time the session was created. The exact position depends on the underlying platform and implementation. The user isn't expected to move much if at all beyond their starting position, and tracking is optimized for this use case. For devices with six degrees of freedom (6DoF) tracking, the `local` reference space tries to keep the origin stable relative to the environment.
- `local-floor`
- : An {{domxref("XRReferenceSpace")}} similar to the `local` type, except the starting position is placed in a safe location for the viewer to stand, where the value of the y axis is 0 at floor level. If that floor level isn't known, the {{Glossary("user agent")}} will estimate the floor level. If the estimated floor level is non-zero, the browser is expected to round it such a way as to avoid [fingerprinting](/en-US/docs/Glossary/Fingerprinting) (likely to the nearest centimeter).
- `unbounded`
- : An {{domxref("XRReferenceSpace")}} tracking space which allows the user total freedom of movement, possibly over extremely long distances from their origin point. The viewer isn't tracked at all; tracking is optimized for stability around the user's current position, so the native origin may drift as needed to accommodate that need.
- `viewer`
- : An {{domxref("XRReferenceSpace")}} tracking space whose native origin tracks the viewer's position and orientation. This is used for environments in which the user can physically move around, and is supported by all instances of {{domxref("XRSession")}}, both immersive and inline, though it's most useful for inline sessions. It's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces. Otherwise, typically, one of the other reference space types will be used more often.
### Exceptions
Rather than throwing true exceptions, `requestReferenceSpace()` rejects the
returned promise with a {{domxref("DOMException")}} whose name is found in the list
below:
- `NotSupportedError`
- : The requested reference space is not supported.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/visibilitychange_event/index.md | ---
title: "XRSession: visibilitychange event"
short-title: visibilitychange
slug: Web/API/XRSession/visibilitychange_event
page-type: web-api-event
status:
- experimental
browser-compat: api.XRSession.visibilitychange_event
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`visibilitychange`** event is sent to an {{domxref("XRSession")}} to inform it when it becomes visible or hidden, or when it becomes visible but not currently focused. Upon receiving the event, you can check the value of the session's {{domxref("XRSession.visibilityState", "visibilityState")}} property to determine the new visibility state.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("visibilitychange", (event) => {});
onvisibilitychange = (event) => {};
```
## Event type
An {{domxref("XRSessionEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("XRSessionEvent")}}
## Event properties
_In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._
- {{domxref("XRSessionEvent.session", "session")}} {{ReadOnlyInline}}
- : The {{domxref("XRSession")}} to which the event refers.
## Description
### Trigger
Triggered when an {{domxref("XRSession")}} becomes visible or hidden, or when it becomes visible but not currently focused.
When the `XRSession` receives this event, the visibility state has already been changed.
### Use cases
Upon receiving the event, you can check the value of the session's {{domxref("XRSession.visibilityState", "visibilityState")}} property to determine the new visibility state.
## Examples
This example demonstrates how to listen for a `visibilitychange` event on a WebXR session, using {{domxref("EventTarget.addEventListener", "addEventListener()")}} to begin listening for the event:
```js
navigator.xr.requestSession("inline").then((xrSession) => {
xrSession.addEventListener("visibilitychange", (e) => {
switch (e.session.visibilityState) {
case "visible":
case "visible-blurred":
mySessionVisible(true);
break;
case "hidden":
mySessionVisible(false);
break;
}
});
});
```
When a visibility state change occurs, the event is received and dispatched to a function `mySessionVisible()`, with a Boolean parameter indicating whether or not the session is presently being displayed to the user.
You can also create the event handler by assigning it to the {{domxref("XRSession")}}'s `onvisibilitychange` event handler property, like this:
```js
xrSession.onvisibilitychange = (e) => {
/* event handled here */
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/requesthittestsource/index.md | ---
title: "XRSession: requestHitTestSource() method"
short-title: requestHitTestSource()
slug: Web/API/XRSession/requestHitTestSource
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRSession.requestHitTestSource
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`requestHitTestSource()`** method of the
{{domxref("XRSession")}} interface returns a {{jsxref("Promise")}} that resolves with an {{domxref("XRHitTestSource")}} object that can be passed to {{domxref("XRFrame.getHitTestResults()")}}.
## Syntax
```js-nolint
requestHitTestSource(options)
```
### Parameters
- `options`
- : An object containing configuration options, specifically:
- `space`
- : The {{domxref("XRSpace")}} that will be tracked by the hit test source.
- `entityTypes` {{Optional_Inline}}
- : An {{jsxref("Array")}} specifying the types of entities to be used for hit test source creation. If no entity type is specified, the array defaults to a single element with the `plane` type. Possible types:
- `point`: Compute hit test results based on characteristic points detected.
- `plane`: Compute hit test results based on real-world planes detected.
- `mesh`: Compute hit test results based on meshes detected.
- `offsetRay` {{Optional_Inline}}
- : The {{domxref("XRRay")}} object that will be used to perform hit test. If no `XRRay` object has been provided, a new `XRRay` object is constructed without any parameters.
### Return value
A {{jsxref("Promise")}} that resolves with an {{domxref("XRHitTestSource")}} object.
### Exceptions
Rather than throwing true exceptions, `requestHitTestSource()` rejects the
returned promise with a {{domxref("DOMException")}}, specifically, one of the following:
- `NotSupportedError` {{domxref("DOMException")}}
- : Thrown if `hit-test` is not an enabled feature in {{domxref("XRSystem.requestSession()")}}.
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the session has already ended.
- `NotAllowedError` {{domxref("DOMException")}}
- : Thrown if there is an unreasonable amount of requests. Some user agents might limit usage for privacy reasons.
## Examples
### Requesting a hit test source
To request a hit test source, start an {{domxref("XRSession")}} with the `hit-test` session feature enabled. Next, configure the hit test source and store it for later use in the frame loop and call {{domxref("XRFrame.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("XRSession.requestHitTestSourceForTransientInput()")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/updaterenderstate/index.md | ---
title: "XRSession: updateRenderState() method"
short-title: updateRenderState()
slug: Web/API/XRSession/updateRenderState
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRSession.updateRenderState
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The `updateRenderState()` method of the {{DOMxRef("XRSession")}} interface of the [WebXR API](/en-US/docs/Web/API/WebXR_Device_API) schedules changes to be applied to the active render state ({{domxref("XRRenderState")}}) prior to rendering of the next frame.
## Syntax
```js-nolint
updateRenderState()
updateRenderState(state)
```
### Parameters
- `state` {{Optional_Inline}}
- : An optional object to configure the {{domxref("XRRenderState")}}. If none is provided, a default configuration will be used.
- `baseLayer` {{Optional_Inline}}: An {{domxref("XRWebGLLayer")}} object from which the WebXR compositor will obtain imagery. This is `null` by default. To specify other (or multiple) layers, see the `layers` option.
- `depthFar` {{Optional_Inline}}: A floating-point value specifying the distance in meters from the viewer to the far clip plane, which is a plane parallel to the display surface beyond which no further rendering will occur. All rendering will take place between the distances specified by `depthNear` and `depthFar`. This is 1000 meters (1 kilometer) by default.
- `depthNear` {{Optional_Inline}}: A floating-point value indicating the distance in meters from the viewer to a plane parallel to the display surface to be the **near clip plane**. No part of the scene on the viewer's side of this plane will be rendered. This is 0.1 meters (10 centimeters) by default.
- `inlineVerticalFieldOfView` {{Optional_Inline}}: A floating-point value indicating the default field of view, in radians, to be used when computing the projection matrix for an `inline` {{domxref("XRSession")}}. The projection matrix calculation also takes into account the output canvas's aspect ratio. This property _must not_ be specified for immersive sessions, so the value is `null` by default for immersive sessions. The default value is otherwise π \* 0.5 (half of the value of pi).
- `layers` {{Optional_Inline}}: An ordered array of {{domxref("XRLayer")}} objects specifying the layers that should be presented to the XR device. Setting `layers` will override the `baseLayer` if one is present, with `baseLayer` reporting `null`. The order of the layers given is "back-to-front". For alpha blending of layers, see the {{domxref("XRCompositionLayer.blendTextureSourceAlpha")}} property.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown in any of the following situations:
- The {{domxref("XRSession")}} has already ended, so you cannot change its render state.
- The `baseLayer` was created by an `XRSession` other than the one on which `updateRenderState()` was called.
- The `inlineVerticalFieldOfView` option was set, but the session is immersive, and therefore, does not allow this property to be used.
- `NotSupportedError` {{domxref("DOMException")}}
- : Thrown in any of the following situations:
- The `layers` option is used in a session that has been created without the `layers` feature.
- Both the `baseLayer` and `layers` options are specified.
- {{jsxref("TypeError")}}
- : Thrown if the `layers` option contains duplicate instances.
## Examples
### Adding a `baseLayer`
This example creates a WebGL context that is compatible with an immersive XR device and then uses it to create an {{DOMxRef("XRWebGLLayer")}}. The method `updateRenderState()` is then called to associate the new `XRWebGLLayer`.
```js
function onXRSessionStarted(xrSession) {
let glCanvas = document.createElement("canvas");
let gl = glCanvas.getContext("webgl", { xrCompatible: true });
loadWebGLResources();
xrSession.updateRenderState({
baseLayer: new XRWebGLLayer(xrSession, gl),
});
}
```
### Setting the `layers` array
To use WebXR layers, the XR session needs to be created with the `layers` feature descriptor (see {{domxref("XRSystem.requestSession()")}}). You can then create various WebXR layers such as
- {{domxref("XREquirectLayer")}}
- {{domxref("XRCubeLayer")}}
- {{domxref("XRCylinderLayer")}}
- {{domxref("XRQuadLayer")}}
Other layers, such as {{domxref("XRProjectionLayer")}} or {{domxref("XRWebGLLayer")}} are also available.
Layers will be presented in the order they are given in the `layers` array, with layers being given in "back-to-front" order.
```js
const xrSession = navigator.xr.requestSession("immersive-ar", {
optionalFeatures: ["layers"],
});
function onXRSessionStarted(xrSession) {
const glCanvas = document.createElement("canvas");
const gl = glCanvas.getContext("webgl", { xrCompatible: true });
const xrGlBinding = new XRWebGLBinding(xrSession, gl);
const projectionLayer = new XRWebGLLayer(xrSession, gl);
const quadLayer = xrGlBinding.createQuadLayer({
pixelWidth: 1024,
pixelHeight: 1024,
});
xrSession.updateRenderState({
layers: [projectionLayer, quadLayer],
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API)
- {{domxref("XRRenderState")}}
- {{domxref("XRSession.renderState")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/interactionmode/index.md | ---
title: "XRSession: interactionMode property"
short-title: interactionMode
slug: Web/API/XRSession/interactionMode
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRSession.interactionMode
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The {{domxref("XRSession")}} interface's _read-only_ **`interactionMode`** property
describes the best space (according to the user agent) for the application to draw an interactive UI for the current session.
## Value
A string describing the best space (according to the user agent) for the application to draw an interactive UI
for the current session.
Possible values are:
- `screen-space`
- : Indicates that the UI should be drawn directly to the screen without projection. This is typically the mode reported from handheld devices.
- `world-space`
- : Indicates that the UI should be drawn in the world, some distance from the user, so that they may interact with it using controllers. This is typically the mode reported from headworn devices.
## Examples
```js
if (xrSession.interactionMode === "world-space") {
// draw UI in the world
} else {
// draw UI directly to the screen
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/depthdataformat/index.md | ---
title: "XRSession: depthDataFormat property"
short-title: depthDataFormat
slug: Web/API/XRSession/depthDataFormat
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRSession.depthDataFormat
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The _read-only_ **`depthDataFormat`** property of an `immersive-ar`
{{DOMxRef("XRSession")}} describes which depth sensing data format is used.
## Value
This property can return the following values:
- `luminance-alpha`
- : 2-byte unsigned integer data buffers (`LUMINANCE_ALPHA` `GLEnum`).
CPU usage: interpret {{domxref("XRCPUDepthInformation.data")}} as {{jsxref("Uint8Array")}}.
GPU usage: inspect Luminance and Alpha channels to reassemble single value.
- `float32`
- : 4-byte floating point data buffers (`R32F` `GLEnum`).
CPU usage: interpret {{domxref("XRCPUDepthInformation.data")}} as {{jsxref("Float32Array")}}.
GPU usage: inspect Red channel and use the value.
## Examples
To request the desired data format, you need to specify a `dataFormatPreference` when requesting a session using {{domxref("XRSystem.requestSession()")}}. Here, the caller is able to handle both "luminance-alpha" and "float32" formats. The order indicates preference for "luminance-alpha":
```js
navigator.xr.requestSession("immersive-ar", {
requiredFeatures: ["depth-sensing"],
depthSensing: {
usagePreference: ["cpu-optimized", "gpu-optimized"],
formatPreference: ["luminance-alpha", "float32"],
},
});
```
To check which data format was selected by the user agent, you can call the `depthDataFormat` property:
```js
console.log(session.depthDataFormat); // either "luminance-alpha" or "float32"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/select_event/index.md | ---
title: "XRSession: select event"
short-title: select
slug: Web/API/XRSession/select_event
page-type: web-api-event
status:
- experimental
browser-compat: api.XRSession.select_event
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The WebXR **`select`** event is sent to an {{domxref("XRSession")}} when one of the session's input sources has completed a [primary action](/en-US/docs/Web/API/WebXR_Device_API/Inputs#primary_action).
The {{domxref("Element.beforexrselect_event", "beforexrselect")}} is fired before this event and can prevent this event from being raised.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("select", (event) => {});
onselect = (event) => {};
```
## Event type
An {{domxref("XRInputSourceEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("XRInputSourceEvent")}}
## Event properties
_In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._
- {{domxref("XRInputSourceEvent.frame", "frame")}} {{ReadOnlyInline}}
- : An {{domxref("XRFrame")}} object providing the needed information about the event frame during which the event occurred. This frame may have been rendered in the past rather than being a current frame. Because this is an _event_ frame, not an _animation_ frame, you cannot call {{domxref("XRFrame.getViewerPose", "XRFrame.getViewerPose()")}} on it; instead, use {{domxref("XRFrame.getPose", "getPose()")}}.
- {{domxref("XRInputSourceEvent.inputSource", "inputSource")}} {{ReadOnlyInline}}
- : An {{domxref("XRInputSource")}} object indicating which input source generated the input event.
## Description
### Trigger
Triggered when a user presses triggers or buttons, taps a touchpad, speaks a command or performs a recognizable gesture when using a video tracking system or handheld controller with an accelerometer.
### Use cases
The {{domxref("XRSession.selectstart_event", "selectstart")}} and {{domxref("XRSession.selectend_event", "selectend")}} events tell you when you might want to display something to the user indicating that the primary action is going on. This might be drawing a controller with the activated button in a new color, or showing the targeted object being grabbed and moved around, starting when `selectstart` arrives and stopping when `selectend` is received.
The `select` event tells your code that the user has completed an action. This might be as simple as throwing an object or pulling the trigger of a gun in a game, or as involved as placing a dragged object at a new location.
If your primary action is a simple trigger action and you don't need to animate anything while the trigger is engaged, you can ignore the `selectstart` and `selectend` events and act on the start event.
## Examples
The following example uses {{domxref("EventTarget.addEventListener", "addEventListener()")}} to set up a handler for the `select` event. The handler fetches the pose representing the target ray for `tracked-pointer` inputs and sends the pose's transform to a function called `myHandleSelectWithRay()`.
```js
xrSession.addEventListener("select", (event) => {
if (event.inputSource.targetRayMode === "tracked-pointer") {
let targetRayPose = event.frame.getPose(
event.inputSource.targetRaySpace,
myRefSpace,
);
if (targetRayPose) {
myHandleSelectWithRay(targetRayPose.transform);
}
}
});
```
You can also set up a handler for `select` events by setting the {{domxref("XRSession")}} object's `onselect` event handler property to a function that handles the event:
```js
xrSession.onselect = (event) => {
if (event.inputSource.targetRayMode === "tracked-pointer") {
let targetRayPose = event.frame.getPose(
event.inputSource.targetRaySpace,
myRefSpace,
);
if (targetRayPose) {
myHandleSelectWithRay(targetRayPose.transform);
}
}
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRSession.selectstart_event", "selectstart")}} and {{domxref("XRSession.selectend_event", "selectend")}}
- {{domxref("Element.beforexrselect_event", "beforexrselect")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/inputsourceschange_event/index.md | ---
title: "XRSession: inputsourceschange event"
short-title: inputsourceschange
slug: Web/API/XRSession/inputsourceschange_event
page-type: web-api-event
status:
- experimental
browser-compat: api.XRSession.inputsourceschange_event
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`inputsourceschange`** event is sent to an {{domxref("XRSession")}} when the set of available WebXR input devices changes.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("inputsourceschange", (event) => {});
oninputsourceschange = (event) => {};
```
## Event type
An {{domxref("XRInputSourcesChangeEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("XRInputSourcesChangeEvent")}}
## Event properties
_In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._
- {{domxref("XRInputSourcesChangeEvent.added", "added")}} {{ReadOnlyInline}}
- : An array of zero or more {{domxref("XRInputSource")}} objects, each representing an input device which has been recently connected or enabled.
- {{domxref("XRInputSourcesChangeEvent.removed", "removed")}} {{ReadOnlyInline}}
- : An array of zero or more {{domxref("XRInputSource")}} objects representing the input devices recently disconnected or disabled.
- {{domxref("XRInputSourcesChangeEvent.session", "session")}} {{ReadOnlyInline}}
- : The {{domxref("XRSession")}} to which this input source change event is being directed.
## Description
### Trigger
Triggered when the set of available WebXR input devices changes.
### Use cases
You can use this event to detect newly-available devices or when devices have become unavailable.
## Examples
The following example shows how to set up an event handler which uses `inputsourceschange` events to detect newly-available pointing devices and to load their models in preparation for displaying them in the next animation frame.
```js
xrSession.addEventListener("inputsourceschange", onInputSourcesChange);
function onInputSourcesChange(event) {
for (const input of event.added) {
if (input.targetRayMode === "tracked-pointer") {
loadControllerMesh(input);
}
}
}
```
You can also add a handler for `inputsourceschange` events by setting the `oninputsourceschange` event handler:
```js
xrSession.oninputsourceschange = onInputSourcesChange;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/renderstate/index.md | ---
title: "XRSession: renderState property"
short-title: renderState
slug: Web/API/XRSession/renderState
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRSession.renderState
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The
_read-only_ **`renderState`** property of an
{{DOMxRef("XRSession")}} object indicates the returns a {{DOMxRef("XRRenderState")}}
object describing how the user's environment which should be rendered. The
information provided covers the minimum and maximum distance at which to render objects,
the vertical field of view to use when rendering the in the `inline` session
mode, and the {{domxref("XRWebGLLayer")}} to render into for inline composition.
While this property is read only, you can call the {{domxref("XRSession")}} method
{{domxref("XRSession.updateRenderState", "updateRenderState()")}} to make changes.
## Value
An {{DOMxRef("XRRenderState")}} object describing how to render the scene.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/visibilitystate/index.md | ---
title: "XRSession: visibilityState property"
short-title: visibilityState
slug: Web/API/XRSession/visibilityState
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRSession.visibilityState
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The _read-only_ **`visibilityState`** property of the
{{DOMxRef("XRSession")}} interface is a string indicating whether the WebXR content is
currently visible to the user, and if it is, whether it's the primary focus.
Every time the visibility state changes, a
{{DOMxRef("XRSession.visibilitychange_event","visibilitychange")}} event is fired on the
{{DOMxRef("XRSession")}} object.
## Value
A string indicating whether or not the XR content is
visible to the user and if it is, whether or not it's currently the primary focus.
The possible values of `visibilityState` are:
- `hidden`
- : The virtual scene generated by the {{domxref("XRSession")}} is not currently visible to the user,
so its {{domxref("XRSession.requestAnimationFrame", "requestAnimationFrame()")}}
callbacks are _not_ being executed until the `visibilityState` changes.
Input controllers are _not_ being handled for the session.
- `visible`
- : The virtual scene rendered by the {{domxref("XRSession")}} is currently visible to the user
and is the primary focus of the user's attention. To that end, the session's
{{domxref("XRSession.requestAnimationFrame", "requestAnimationFrame()")}} callbacks are being processed
at the XR device's native refresh rate and input controllers are being processed as normal.
- `visible-blurred`
- : While the virtual scene rendered by the {{domxref("XRSession")}} may currently be visible to the user,
it is not the user's primary focus at the moment; it's also possible the session is not currently visible at all.
In order to optimize resource utilization, the {{Glossary("user agent")}} may be handling the session's
{{domxref("XRSession.requestAnimationFrame", "requestAnimationFrame()")}} callbacks at a throttled rate.
Input controllers are _not_ being processed for the session.
## Usage notes
It's important to keep in mind that because an immersive WebXR session is potentially
being shown using a different display than the HTML document in which it's running (such
as when being shown on a headset), the value of a
session's `visibilityState` may not necessarily be the same as the owning
_{{domxref("document")}}'s_ {{domxref("Document.visibilityState",
"visibilityState")}}. For instance, if the viewer is using a headset tethered to a
computer and the immersive scene is obscured by a configuration UI, the user could peek
out from behind the headset and still be able to see the document itself on their
computer's monitor.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{DOMxRef("XRSession.visibilitychange_event","visibilitychange")}} event
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/end/index.md | ---
title: "XRSession: end() method"
short-title: end()
slug: Web/API/XRSession/end
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRSession.end
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`end()`** method shuts down the
{{domxref("XRSession")}} on which it's called, returning a promise which resolves once
the session has fully shut down.
## Syntax
```js-nolint
end()
```
### Parameters
None.
### Return value
A {{jsxref("promise")}} that resolves without a value after any platform-specific steps
related to shutting down the session have completed. You can use the promise to do
things like update UI elements to reflect the shut down connection, trigger application
shut down, or whatever else you might need to do.
## Examples
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/squeezestart_event/index.md | ---
title: "XRSession: squeezestart event"
short-title: squeezestart
slug: Web/API/XRSession/squeezestart_event
page-type: web-api-event
status:
- experimental
browser-compat: api.XRSession.squeezestart_event
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The [WebXR](/en-US/docs/Web/API/WebXR_Device_API) event **`squeezestart`** is sent to an {{domxref("XRSession")}} when the user begins a [primary squeeze action](/en-US/docs/Web/API/WebXR_Device_API/Inputs#primary_squeeze_actions) on one of its input sources.
Primary squeeze actions are actions which are meant to represent gripping or squeezing using your hands, and may be simulated using triggers on hand controllers.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("squeezestart", (event) => {});
onsqueezestart = (event) => {};
```
## Event type
An {{domxref("XRInputSourceEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("XRInputSourceEvent")}}
## Event properties
_In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._
- {{domxref("XRInputSourceEvent.frame", "frame")}} {{ReadOnlyInline}}
- : An {{domxref("XRFrame")}} object providing the needed information about the event frame during which the event occurred. This frame may have been rendered in the past rather than being a current frame. Because this is an _event_ frame, not an _animation_ frame, you cannot call {{domxref("XRFrame.getViewerPose", "XRFrame.getViewerPose()")}} on it; instead, use {{domxref("XRFrame.getPose", "getPose()")}}.
- {{domxref("XRInputSourceEvent.inputSource", "inputSource")}} {{ReadOnlyInline}}
- : An {{domxref("XRInputSource")}} object indicating which input source generated the input event.
## Description
### Trigger
Triggered when users begin squeezing the controller, making a hand gesture that mimes grabbing something, or using (squeezing) a trigger.
### Use cases
The `squeezestart` event is sent indicating that the user has begun a squeeze action.
If the primary squeeze action ends successfully, the session is sent a {{domxref("XRSession.squeeze_event", "squeeze")}} event.
A {{domxref("XRSession.squeezeend_event", "squeezeend")}} event is sent to indicate that the squeeze action is no longer underway. This is sent whether the squeeze action succeeded or not.
## Examples
The following example uses {{domxref("EventTarget.addEventListener", "addEventListener()")}} to establish handlers for the squeeze events: `squeezestart`, {{domxref("XRSession.squeezeend_event", "squeezeend")}}, and {{domxref("XRSession.squeeze_event", "squeeze")}}. This snippet is the core of an event handler to allow the user to grab objects in the scene and move them around.
In this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. Only after completing those tasks does the `onSqueezeEvent()` function below dispatch the action out to a specialized function to handle things.
After checking to ensure that the received event is a `tracked-pointer` event (the only kind we handle here), the target ray's pose is obtained using {{domxref("XRFrame.getPose", "getPose()")}}.
If the target ray pose was fetched successfully, the code then uses the value of {{domxref("Event")}} property {{domxref("Event.type", "type")}} to route control to an appropriate function to handle the event which arrived:
- For `squeezestart` events, a `myBeginTracking()` function is called with the target ray pose's {{domxref("XRRigidTransform.matrix", "matrix")}}. The `myBeginTracking()` function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to pick up. `myBeginTracking()` returns an object representing the object the user has begun to drag.
- Upon receiving a `squeeze` event, the `myDropObject()` function is called with the target object, and the current target ray pose transform as inputs. This places the object into its new position in the world and triggers any effects that may arise, like scheduling an animation of a splash if dropped in water, etc.
- The `squeezeend` event results in a `myStopTracking()` function being called with the object being dragged and the final target ray pose's transform.
```js
xrSession.addEventListener("squeezestart", onSqueezeEvent);
xrSession.addEventListener("squeeze", onSqueezeEvent);
xrSession.addEventListener("squeezeend", onSqueezeEvent);
function onSqueezeEvent(event) {
let source = event.inputSource;
let targetObj = null;
if (source.targetRayMode !== "tracked-pointer") {
return;
}
let targetRayPose = event.frame.getPose(source.targetRaySpace, myRefSpace);
if (!targetRayPose) {
return;
}
switch (event.type) {
case "squeezestart":
targetObj = myBeginTracking(targetRayPose.matrix);
break;
case "squeeze":
myDropObject(targetObj, targetRayPose.matrix);
break;
case "squeezeend":
myStopTracking(targetObj, targetRayPose.matrix);
break;
}
}
```
You can also set up a handler for these events by setting the {{domxref("XRSession")}} object's event handler properties to a function that handles the event:
```js
xrSession.onsqueezestart = onSqueezeEvent;
xrSession.onsqueeze = onSqueezeEvent;
xrSession.onsqueezeend = onSqueezeEvent;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/squeeze_event/index.md | ---
title: "XRSession: squeeze event"
short-title: squeeze
slug: Web/API/XRSession/squeeze_event
page-type: web-api-event
status:
- experimental
browser-compat: api.XRSession.squeeze_event
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The WebXR **`squeeze`** event is sent to an {{domxref("XRSession")}} when one of the session's input sources has completed a [primary squeeze action](/en-US/docs/Web/API/WebXR_Device_API/Inputs#primary_squeeze_actions). Examples of common kinds of primary action are users pressing triggers or buttons, tapping a touchpad, speaking a command, or performing a recognizable gesture when using a video tracking system or handheld controller with an accelerometer.
For details on how the {{domxref("XRSession.squeezestart_event", "squeezestart")}}, `squeeze`, and {{domxref("XRSession.squeezeend_event", "squeezeend")}} events work, and how you should react to them, see [Inputs and input sources](/en-US/docs/Web/API/WebXR_Device_API/Inputs#input_sources).
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("squeeze", (event) => {});
onsqueeze = (event) => {};
```
## Event type
An {{domxref("XRInputSourceEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("XRInputSourceEvent")}}
## Event properties
_In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._
- {{domxref("XRInputSourceEvent.frame", "frame")}} {{ReadOnlyInline}}
- : An {{domxref("XRFrame")}} object providing the needed information about the event frame during which the event occurred. This frame may have been rendered in the past rather than being a current frame. Because this is an _event_ frame, not an _animation_ frame, you cannot call {{domxref("XRFrame.getViewerPose", "XRFrame.getViewerPose()")}} on it; instead, use {{domxref("XRFrame.getPose", "getPose()")}}.
- {{domxref("XRInputSourceEvent.inputSource", "inputSource")}} {{ReadOnlyInline}}
- : An {{domxref("XRInputSource")}} object indicating which input source generated the input event.
## Description
### Trigger
Triggered when users are squeezing the controller, making a hand gesture that mimes grabbing something, or using (squeezing) a trigger.
### Use cases
The {{domxref("XRSession.squeezestart_event", "squeezestart")}} event indicates that the user has begun a squeeze action.
If the primary squeeze action ends successfully, the session is sent a `squeeze` event.
A {{domxref("XRSession.squeezeend_event", "squeezeend")}} event is sent to indicate that the squeeze action is no longer underway. This is sent whether the squeeze action succeeded or not.
## Examples
The following example uses {{domxref("EventTarget.addEventListener", "addEventListener()")}} to set up a handler for the `squeeze` event. The handler fetches the pose representing the target ray for `tracked-pointer` inputs and sends the pose's transform to a function called `myHandleSqueezeWithRay()`.
This code treats the squeeze as an instantaneous action that doesn't involve tracking an ongoing activity. If you need to track a squeeze action that isn't instantaneous, listen for the {{domxref("XRSession.squeezestart_event", "squeezestart")}} and {{domxref("XRSession.squeezeend_event", "squeezeend")}} events to sense when the squeeze action begins and ends.
```js
xrSession.addEventListener("squeeze", (event) => {
if (event.inputSource.targetRayMode === "tracked-pointer") {
let targetRayPose = event.frame.getPose(
event.inputSource.targetRaySpace,
myRefSpace,
);
if (targetRayPose) {
myHandleSqueezeWithRay(targetRayPose.transform);
}
}
});
```
You can also set up a handler for `squeeze` events by setting the {{domxref("XRSession")}} object's `onsqueeze` event handler property to a function that handles the event:
```js
xrSession.onsqueeze = (event) => {
if (event.inputSource.targetRayMode === "tracked-pointer") {
let targetRayPose = event.frame.getPose(
event.inputSource.targetRaySpace,
myRefSpace,
);
if (targetRayPose) {
myHandleSqueezeWithRay(targetRayPose.transform);
}
}
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRSession.squeezestart_event", "squeezestart")}} and {{domxref("XRSession.squeezeend_event", "squeezeend")}} event
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/cancelanimationframe/index.md | ---
title: "XRSession: cancelAnimationFrame() method"
short-title: cancelAnimationFrame()
slug: Web/API/XRSession/cancelAnimationFrame
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRSession.cancelAnimationFrame
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`cancelAnimationFrame()`** method of
the {{domxref("XRSession")}} interface cancels an animation frame which was previously
requested by calling {{DOMxRef("XRSession.requestAnimationFrame",
"requestAnimationFrame")}}.
## Syntax
```js-nolint
cancelAnimationFrame(handle)
```
### Parameters
- `handle`
- : The unique value returned by the call
to {{DOMxRef("XRSession.requestAnimationFrame", "requestAnimationFrame()")}} that
previously scheduled the animation callback.
### Return value
None ({{jsxref("undefined")}}).
## Usage notes
This function has no effect if the specified `handle` cannot be found.
## Examples
In the example below we see code which starts up a WebXR session if immersive VR mode
is supported. Once started, the session schedules its first frame to be rendered by
calling {{DOMxRef("XRSession.requestAnimationFrame", "requestAnimationFrame()")}}.
The `pauseXR()` function shown at the bottom can be called to suspend the
WebVR session, in essence, by canceling any pending animation frame callback. Since each
frame callback schedules the next one, removing the callback terminates updating of the
WebXR scene.
```js
const XR = navigator.xr;
let requestHandle = null;
let xrSession = null;
if (XR) {
XR.isSessionSupported("immersive-vr").then((isSupported) => {
if (isSupported) {
startXR();
}
});
}
function frameCallback(time, xrFrame) {
xrSession.requestAnimationFrame(frameCallback);
// Update and render the frame
}
async function startXR() {
xrSession = XR.requestSession("immersive-vr");
if (xrSession) {
stopButton.onclick = stopXR;
requestHandle = xrSession.requestAnimationFrame(frameCallback);
}
}
function pauseXR() {
if (xrSession && requestHandle) {
xrSession.cancelAnimationFrame(requestHandle);
requestHandle = null;
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{DOMxRef("Window.cancelAnimationFrame")}}
- {{domxref("XRSession.requestAnimationFrame")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/requestanimationframe/index.md | ---
title: "XRSession: requestAnimationFrame() method"
short-title: requestAnimationFrame()
slug: Web/API/XRSession/requestAnimationFrame
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRSession.requestAnimationFrame
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The {{domxref("XRSession")}}
method **`requestAnimationFrame()`**, much like the
{{domxref("Window")}} method of the same name, schedules a callback to be executed the
next time the browser is ready to paint the session's virtual environment to the XR
display. The specified callback is executed once before the next repaint; if
you wish for it to be executed for the following repaint, you must
call `requestAnimationFrame()` again. This can be done from within the
callback itself.
The callback takes two parameters as inputs: an {{DOMxRef("XRFrame")}} describing the
state of all tracked objects for the session, and a timestamp you can use to compute
any animation updates needed.
You can cancel a previously scheduled animation by calling
{{DOMxRef("XRSession.cancelAnimationFrame", "cancelAnimationFrame()")}}.
> **Note:** Despite the obvious similarities between these methods and the
> global {{domxref("Window.requestAnimationFrame", "requestAnimationFrame()")}} function
> provided by the `Window` interface, you _must not_ treat these as
> interchangeable. There is _no_ guarantee that the latter will work at all while
> an immersive XR session is underway.
## Syntax
```js-nolint
requestAnimationFrame(animationFrameCallback)
```
### Parameters
- `animationFrameCallback`
- : A function which is called before the next repaint in order to allow you to update
and render the XR scene based on elapsed time, animation, user input changes, and so
forth. The callback receives as input two parameters:
- `time`
- : A {{domxref("DOMHighResTimeStamp")}} indicating the time offset at which the
updated viewer state was received from the WebXR device.
- `xrFrame`
- : An {{domxref("XRFrame")}} object describing the state of the objects being
tracked by the session. This can be used to obtain the poses of the viewer and the
scene itself, as well as other information needed to render a frame of an AR or VR
scene.
### Return value
An integer value which serves as a unique, non-zero ID or handle you may pass to
{{domxref("XRSession.cancelAnimationFrame", "cancelAnimationFrame()")}} if you need to
remove the pending animation frame request.
## Examples
The following example requests `XRSession` with "inline" mode so that it can
be displayed in an HTML element (without the need for a separate AR or VR device).
> **Note:** A real application should check that the device and the User
> Agent support WebXR API at all and then that they both support the desired session
> type via {{DOMxRef("XRSystem.isSessionSupported()")}}.
```js
// Obtain XR object
const XR = navigator.xr;
// Request a new XRSession
XR.requestSession("inline").then((xrSession) => {
xrSession.requestAnimationFrame((time, xrFrame) => {
const viewer = xrFrame.getViewerPose(xrReferenceSpace);
gl.bindFramebuffer(xrWebGLLayer.framebuffer);
for (const xrView of viewer.views) {
const xrViewport = xrWebGLLayer.getViewport(xrView);
gl.viewport(
xrViewport.x,
xrViewport.y,
xrViewport.width,
xrViewport.height,
);
// WebGL draw calls will now be rendered into the appropriate viewport.
}
});
});
```
The following example was taken directly from the spec draft. This example demonstrates
a design pattern that ensures seamless transition between non-immersive animations
created via {{DOMxRef("Window.requestAnimationFrame")}} and immersive XR animations.
```js
let xrSession = null;
function onWindowAnimationFrame(time) {
window.requestAnimationFrame(onWindowAnimationFrame);
// This may be called while an immersive session is running on some devices,
// such as a desktop with a tethered headset. To prevent two loops from
// rendering in parallel, skip drawing in this one until the session ends.
if (!xrSession) {
renderFrame(time, null);
}
}
// The window animation loop can be started immediately upon the page loading.
window.requestAnimationFrame(onWindowAnimationFrame);
function onXRAnimationFrame(time, xrFrame) {
xrSession.requestAnimationFrame(onXRAnimationFrame);
renderFrame(time, xrFrame);
}
function renderFrame(time, xrFrame) {
// Shared rendering logic.
}
// Assumed to be called by a user gesture event elsewhere in code.
function startXRSession() {
navigator.xr.requestSession("immersive-vr").then((session) => {
xrSession = session;
xrSession.addEventListener("end", onXRSessionEnded);
// Do necessary session setup here.
// Begin the session's animation loop.
xrSession.requestAnimationFrame(onXRAnimationFrame);
});
}
function onXRSessionEnded() {
xrSession = null;
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{DOMxRef("Window.requestAnimationFrame()")}}
- {{domxref("XRSession.cancelAnimationFrame()")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/requestlightprobe/index.md | ---
title: "XRSession: requestLightProbe() method"
short-title: requestLightProbe()
slug: Web/API/XRSession/requestLightProbe
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRSession.requestLightProbe
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`requestLightProbe()`** method of the
{{domxref("XRSession")}} interface returns a {{jsxref("Promise")}} that resolves with an {{domxref("XRLightProbe")}} object that estimates lighting information at a given point in the user's environment.
## Syntax
```js-nolint
requestLightProbe()
requestLightProbe(options)
```
### Parameters
- `options` {{Optional_Inline}}
- : An object containing configuration options, specifically:
- `reflectionFormat`
- : The internal reflection format indicating how the texture data is represented, either `srgba8` (default value) or `rgba16f`. See also {{domxref("XRSession.preferredReflectionFormat")}}.
### Return value
A {{jsxref("Promise")}} that resolves with an {{domxref("XRLightProbe")}} object.
### Exceptions
Rather than throwing true exceptions, `requestLightProbe()` rejects the
returned promise with a {{domxref("DOMException")}}, specifically, one of the following:
- `NotSupportedError` {{domxref("DOMException")}}
- : Thrown if `lighting-estimation` is not an enabled feature in {{domxref("XRSystem.requestSession()")}} or if the `reflectionFormat` is not `srgb8` or the `preferredReflectionFormat`.
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the session has already ended.
## Examples
### Requesting a light probe with the system's preferred format
The default format is `srgb8`, however, some rendering engines may use other (high dynamic range) formats. You can request the light probe with {{domxref("XRSession.preferredReflectionFormat")}} which reports the preferred internal format.
```js
const lightProbe = await xrSession.requestLightProbe({
reflectionFormat: xrSession.preferredReflectionFormat,
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRSession.preferredReflectionFormat")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/preferredreflectionformat/index.md | ---
title: "XRSession: preferredReflectionFormat property"
short-title: preferredReflectionFormat
slug: Web/API/XRSession/preferredReflectionFormat
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRSession.preferredReflectionFormat
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The _read-only_ **`preferredReflectionFormat`** property of the {{DOMxRef("XRSession")}} interface returns this session's preferred reflection format used for lighting estimation texture data.
## Value
A string representing the reflection format. Possible values:
| XRReflectionFormat | WebGL Format | WebGL Internal Format | WebGPU Format | HDR |
| ------------------ | ------------ | --------------------- | ----------------- | --- |
| "srgba8" | RGBA | SRGB8_ALPHA8 | "rgba8unorm-srgb" | |
| "rgba16f" | RGBA | RGBA16F | "rgba16float" | ✓ |
## Examples
### Requesting a light probe with the system's preferred format
You can request a light probe with {{domxref("XRSession.requestLightProbe()")}} and specify the system's preferred format by setting the `reflectionFormat` option equal to `XRSession.preferredReflectionFormat`.
```js
const lightProbe = await xrSession.requestLightProbe({
reflectionFormat: xrSession.preferredReflectionFormat,
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRSession.requestLightProbe()")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/inputsources/index.md | ---
title: "XRSession: inputSources property"
short-title: inputSources
slug: Web/API/XRSession/inputSources
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRSession.inputSources
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The read-only **`inputSources`** property of the
{{DOMxRef("XRSession")}} interface returns an {{domxref("XRInputSourceArray")}} object
which lists all controllers and input devices which are expressly associated with the
XR device and are currently available. These controllers may include handheld
controllers, XR-equipped gloves, optically tracked hands, and gaze-based input methods.
Keyboards, gamepads, and mice are _not_ considered WebXR input sources.
> **Note:** Traditional gamepad controllers are supported using the [Gamepad API](/en-US/docs/Web/API/Gamepad_API).
## Value
An {{domxref("XRInputSourceArray")}} object listing all of the currently-connected
input controllers which are linked specifically to the XR device currently in use. The
returned object is **live**; as devices are connected to and removed from
the user's system, the list's contents update to reflect the changes.
## Usage notes
You can add a handler for the `XRSession` event
{{domxref("XRSession.inputsourceschange_event", "inputsourceschange")}} to be advised
when the contents of the session's connected devices list changes. You can then either
get the value of `inputSources` to examine the list, or you can refer to a
reference to the list that you've previously saved.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{DOMxRef("XRInputSource")}}
- The {{DOMxRef("XRSession.inputsourceschange_event", "inputsourceschange")}} event
- [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/end_event/index.md | ---
title: "XRSession: end event"
short-title: end
slug: Web/API/XRSession/end_event
page-type: web-api-event
status:
- experimental
browser-compat: api.XRSession.end_event
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
An `end` event is fired at an {{DOMxRef("XRSession")}} object when the WebXR session has ended, either because the web application has chosen to stop the session, or because the {{Glossary("user agent")}} terminated the session.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("end", (event) => {});
onend = (event) => {};
```
## Event type
An {{domxref("XRSessionEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("XRSessionEvent")}}
## Event properties
_In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._
- {{domxref("XRSessionEvent.session", "session")}} {{ReadOnlyInline}}
- : The {{domxref("XRSession")}} to which the event refers.
## Description
### Trigger
Triggered when the WebXR session has ended, either because the web application has chosen to stop the session, or because the {{Glossary("user agent")}} terminated the session.
This event is not cancelable and does not bubble.
### Use cases
You can use this event to react to the ending of an WebXR session. You may want to display a UI element informing about the termination of the session, for example.
## Examples
To be informed when a WebXR session comes to an end, you can add a handler to your {{domxref("XRSession")}} instance using {{domxref("EventTarget.addEventListener", "addEventListener()")}}, like this:
```js
XRSession.addEventListener("end", (event) => {
/* the session has shut down */
});
```
Alternatively, you can use the `XRSession.onend` event handler property to establish a handler for the `end` event:
```js
XRSession.onend = (event) => {
/* the session has shut down */
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/environmentblendmode/index.md | ---
title: "XRSession: environmentBlendMode property"
short-title: environmentBlendMode
slug: Web/API/XRSession/environmentBlendMode
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRSession.environmentBlendMode
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The {{domxref("XRSession")}} interface's _read-only_ **`environmentBlendMode`**
property identifies if, and to what degree, the computer-generated imagery is overlaid atop the real world.
This is used to differentiate between fully-immersive VR sessions and AR sessions which render
over a pass-through image of the real world, possibly partially transparently.
## Value
A string defining if and how virtual, rendered content is overlaid atop the image of the real world.
Possible values are:
- `opaque`
- : The rendered image is drawn without allowing any pass-through imagery. This is primarily used by fully-immersive VR headsets, which totally obscure the surrounding environment, with none of the real world shown to the user at all. The alpha values specified in the {{domxref("XRSession")}}'s {{domxref("XRSession.renderState", "renderState")}} property's `baseLayer` field are ignored since the alpha values for the rendered imagery are all treated as being 1.0 (fully opaque).
- `additive`
- : Primarily used by AR devices with transparent lenses which directly allow reality to pass through to the user's eyes, the `additive` blending mode is designed to be used in a situation in which the device has no control over the background and its brightness, since that isn't being digitally controlled. All the device can do is add more light to the image; it can't make things get darker. Therefore, black is rendered as fully transparent, and there's no way to make a pixel fully opaque. As with the `opaque` setting, alpha values specified are ignored and treated as if they were 1.0.
- `alpha-blend`
- : Used by headsets or goggles which use cameras to capture the real world and display it digitally on the screen or screens used to render the content for the user to see, this offers a way to create an AR presentation using a VR device. Alpha blending can also be used by non-wearable devices that provide AR modes, such as phones or tablets using cameras to capture the real world for use in AR apps. Since the real world is being digitally presented, the brightness of each pixel can be controlled, whether it's reality or the rendered XR image, the user's environment can be blended with the virtual environment with each pixel having its color and brightness precisely controlled.
In this mode, the `XRSession`'s `renderState.baseLayer` property provides relative weights of the artificial layer during the compositing process. Pixels whose alpha value is 1.0 are rendered fully opaque, totally obscuring the real world, while pixels with an alpha of 0.0 are totally transparent, leaving the surrounding environment to pass through.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/depthusage/index.md | ---
title: "XRSession: depthUsage property"
short-title: depthUsage
slug: Web/API/XRSession/depthUsage
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRSession.depthUsage
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The _read-only_ **`depthUsage`** property of an `immersive-ar`
{{DOMxRef("XRSession")}} describes which depth-sensing usage is used.
## Value
This property can return the following values:
- `cpu-optimized`
- : The depth data is intended to be used on the CPU; see the {{domxref("XRCPUDepthInformation")}} interface.
- `gpu-optimized`
- : The depth data is intended to be used on the GPU; see the {{domxref("XRWebGLDepthInformation")}} interface.
## Examples
To request the desired usage method, you need to specify a `usagePreference` when requesting a session using {{domxref("XRSystem.requestSession()")}}. Here, the caller is able to handle both CPU- and GPU-optimized usage. The order indicates preference for CPU:
```js
navigator.xr.requestSession("immersive-ar", {
requiredFeatures: ["depth-sensing"],
depthSensing: {
usagePreference: ["cpu-optimized", "gpu-optimized"],
formatPreference: ["luminance-alpha", "float32"],
},
});
```
To check which usage was selected by the user agent, you can call the `depthUsage` property:
```js
console.log(session.depthUsage); // either "cpu-optimized" or "gpu-optimized"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/squeezeend_event/index.md | ---
title: "XRSession: squeezeend event"
short-title: squeezeend
slug: Web/API/XRSession/squeezeend_event
page-type: web-api-event
status:
- experimental
browser-compat: api.XRSession.squeezeend_event
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The WebXR event **`squeezeend`** is sent to an {{domxref("XRSession")}} when one of its input sources ends its [primary action](/en-US/docs/Web/API/WebXR_Device_API/Inputs#primary_squeeze_actions) or when an input source that's in the process of handling an ongoing primary action is disconnected without successfully completing the action.
Primary squeeze actions include things like users pressing triggers or buttons, tapping a touchpad, speaking a command, or performing a recognizable gesture when using a video tracking system or handheld controller with an accelerometer.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("squeezeend", (event) => {});
onsqueezeend = (event) => {};
```
## Event type
An {{domxref("XRInputSourceEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("XRInputSourceEvent")}}
## Event properties
_In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._
- {{domxref("XRInputSourceEvent.frame", "frame")}} {{ReadOnlyInline}}
- : An {{domxref("XRFrame")}} object providing the needed information about the event frame during which the event occurred. This frame may have been rendered in the past rather than being a current frame. Because this is an _event_ frame, not an _animation_ frame, you cannot call {{domxref("XRFrame.getViewerPose", "XRFrame.getViewerPose()")}} on it; instead, use {{domxref("XRFrame.getPose", "getPose()")}}.
- {{domxref("XRInputSourceEvent.inputSource", "inputSource")}} {{ReadOnlyInline}}
- : An {{domxref("XRInputSource")}} object indicating which input source generated the input event.
## Description
### Trigger
Triggered when users stop squeezing the controller, making a hand gesture that mimes grabbing something, or using (squeezing) a trigger.
### Use cases
The {{domxref("XRSession.squeezestart_event", "squeezestart")}} event is sent indicating that the user has begun a squeeze action.
If the primary squeeze action ends successfully, the session is sent a {{domxref("XRSession.squeeze_event", "squeeze")}} event.
A `squeezeend` event is sent to indicate that the squeeze action is no longer underway. This is sent whether the squeeze action succeeded or not.
## Examples
See the [`squeezestart`](/en-US/docs/Web/API/XRSession/squeezestart_event#examples) event for example code.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/selectstart_event/index.md | ---
title: "XRSession: selectstart event"
short-title: selectstart
slug: Web/API/XRSession/selectstart_event
page-type: web-api-event
status:
- experimental
browser-compat: api.XRSession.selectstart_event
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The [WebXR](/en-US/docs/Web/API/WebXR_Device_API) **`selectstart`** event is sent to an {{domxref("XRSession")}} when the user begins a [primary action](/en-US/docs/Web/API/WebXR_Device_API/Inputs#primary_action) on one of its input sources.
The {{domxref("Element.beforexrselect_event", "beforexrselect")}} is fired before this event and can prevent this event from being raised.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("selectstart", (event) => {});
onselectstart = (event) => {};
```
## Event type
An {{domxref("XRInputSourceEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("XRInputSourceEvent")}}
## Event properties
_In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._
- {{domxref("XRInputSourceEvent.frame", "frame")}} {{ReadOnlyInline}}
- : An {{domxref("XRFrame")}} object providing the needed information about the event frame during which the event occurred. This frame may have been rendered in the past rather than being a current frame. Because this is an _event_ frame, not an _animation_ frame, you cannot call {{domxref("XRFrame.getViewerPose", "XRFrame.getViewerPose()")}} on it; instead, use {{domxref("XRFrame.getPose", "getPose()")}}.
- {{domxref("XRInputSourceEvent.inputSource", "inputSource")}} {{ReadOnlyInline}}
- : An {{domxref("XRInputSource")}} object indicating which input source generated the input event.
## Description
### Trigger
Triggered when the user presses triggers or buttons, taps a touchpad, speaks a command, or performs a recognizable gesture when using a video tracking system or handheld controller with an accelerometer.
### Use cases
The `selectstart` and {{domxref("XRSession.selectend_event", "selectend")}} events tell you when you might want to display something to the user indicating that the primary action is going on. This might be drawing a controller with the activated button in a new color, or showing the targeted object being grabbed and moved around, starting when `selectstart` arrives and stopping when `selectend` is received.
The {{domxref("XRSession.select_event", "select")}} event tells your code that the user has completed the action they want to complete. This might be as simple as throwing an object or pulling the trigger of a gun in a game, or as involved as placing a dragged object in a new location.
If your primary action is a simple trigger action and you don't need to animate anything while the trigger is engaged, you can ignore the `selectstart` and `selectend` events and act on the start event.
## Examples
The following example uses {{domxref("EventTarget.addEventListener", "addEventListener()")}} to establish handlers for the selection events: `selectstart`, {{domxref("XRSession.selectend_event", "selectend")}}, and {{domxref("XRSession.select_event", "select")}}. This snippet is the core of an event handler to allow the user to grab objects in the scene and move them around.
In this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. Only after completing those tasks does the `onSelectionEvent()` function below dispatch the action out to a specialized function to handle things.
After checking to ensure that the received event is a `tracked-pointer` event (the only kind we handle here), the target ray's pose is obtained using {{domxref("XRFrame.getPose", "getPose()")}}.
If the target ray pose was fetched successfully, the code then uses the value of {{domxref("Event")}} property {{domxref("Event.type", "type")}} to route control to an appropriate function to handle the event which arrived:
- For `selectstart` events, a `myBeginTracking()` function is called with the target ray pose's {{domxref("XRRigidTransform.matrix", "matrix")}}. The `myBeginTracking()` function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to pick up. `myBeginTracking()` returns an object representing the object the user has begun to drag.
- Upon receiving a `select` event, the `myDropObject()` function is called with the target object, and the current target ray pose transform as inputs. This places the object into its new position in the world and triggers any effects that may arise, like scheduling an animation of a splash if dropped in water, etc.
- The `selectend` event results in a `myStopTracking()` function being called with the object being dragged and the final target ray pose's transform.
```js
xrSession.addEventListener("selectstart", onSelectionEvent);
xrSession.addEventListener("select", onSelectionEvent);
xrSession.addEventListener("selectend", onSelectionEvent);
function onSelectionEvent(event) {
let source = event.inputSource;
let targetObj = null;
if (source.targetRayMode !== "tracked-pointer") {
return;
}
let targetRayPose = event.frame.getPose(source.targetRaySpace, myRefSpace);
if (!targetRayPose) {
return;
}
switch (event.type) {
case "selectstart":
targetObj = myBeginTracking(targetRayPose.matrix);
break;
case "select":
myDropObject(targetObj, targetRayPose.matrix);
break;
case "selectend":
myStopTracking(targetObj, targetRayPose.matrix);
break;
}
}
```
You can also set up a handler for `selectend` events by setting the {{domxref("XRSession")}} object's `onselectend` event handler property to a function that handles the event:
```js
xrSession.onselectstart = onSelectionEvent;
xrSession.onselect = onSelectionEvent;
xrSession.onselectend = onSelectionEvent;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRSession.select_event", "select")}} and {{domxref("XRSession.selectend_event", "selectend")}}
- {{domxref("Element.beforexrselect_event", "beforexrselect")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/selectend_event/index.md | ---
title: "XRSession: selectend event"
short-title: selectend
slug: Web/API/XRSession/selectend_event
page-type: web-api-event
status:
- experimental
browser-compat: api.XRSession.selectend_event
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The WebXR event **`selectend`** is sent to an {{domxref("XRSession")}} when one of its input sources ends its [primary action](/en-US/docs/Web/API/WebXR_Device_API/Inputs#primary_actions) or when an input source that's in the process of handling an ongoing primary action is disconnected without successfully completing the action.
The {{domxref("Element.beforexrselect_event", "beforexrselect")}} is fired before this event and can prevent this event from being raised.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("selectend", (event) => {});
onselectend = (event) => {};
```
## Event type
An {{domxref("XRInputSourceEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("XRInputSourceEvent")}}
## Event properties
_In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._
- {{domxref("XRInputSourceEvent.frame", "frame")}} {{ReadOnlyInline}}
- : An {{domxref("XRFrame")}} object providing the needed information about the event frame during which the event occurred. This frame may have been rendered in the past rather than being a current frame. Because this is an _event_ frame, not an _animation_ frame, you cannot call the {{domxref("XRFrame")}} method {{domxref("XRFrame.getViewerPose", "getViewerPose()")}} on it; instead, use {{domxref("XRFrame.getPose", "getPose()")}}.
- {{domxref("XRInputSourceEvent.inputSource", "inputSource")}} {{ReadOnlyInline}}
- : An {{domxref("XRInputSource")}} object indicating which input source generated the input event.
## Description
### Trigger
Triggered when the user stops to press triggers or buttons, taps a touchpad, speaks a command, or performs a recognizable gesture when using a video tracking system or handheld controller with an accelerometer.
### Use cases
The `selectend` and {{domxref("XRSession.selectstart_event", "selectstart")}} events tell you when you might want to display something to the user indicating that the primary action is going on. This might be drawing a controller with the activated button in a new color, or showing the targeted object being grabbed and moved around, starting when `selectstart` arrives and stopping when `selectend` is received.
The {{domxref("XRSession.select_event", "select")}} event is the event that tells your code that the user has completed the action they want to complete. This might be as simple as throwing an object or pulling the trigger of a gun in a game, or as involved as placing a dragged object in a new location.
If your primary action is a simple trigger action and you don't need to animate anything while the trigger is engaged, you can ignore the `selectstart` and `selectend` events and act on the start event.
## Examples
See the [`selectstart`](/en-US/docs/Web/API/XRSession/selectstart_event#examples) event for example code.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRSession.select_event", "select")}} and {{domxref("XRSession.selectstart_event", "selectstart")}}
- {{domxref("Element.beforexrselect_event", "beforexrselect")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/requesthittestsourcefortransientinput/index.md | ---
title: "XRSession: requestHitTestSourceForTransientInput() method"
short-title: requestHitTestSourceForTransientInput()
slug: Web/API/XRSession/requestHitTestSourceForTransientInput
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRSession.requestHitTestSourceForTransientInput
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`requestHitTestSourceForTransientInput()`** method of the
{{domxref("XRSession")}} interface returns a {{jsxref("Promise")}} that resolves with an {{domxref("XRTransientInputHitTestSource")}} object that can be passed to {{domxref("XRFrame.getHitTestResultsForTransientInput()")}}.
## Syntax
```js-nolint
requestHitTestSourceForTransientInput(options)
```
### Parameters
- `options`
- : An object containing configuration options, specifically:
- `profile`
- : A string specifying the [input profile name](/en-US/docs/Web/API/XRInputSource) of the transient input source that will be used to compute hit test results.
- `entityTypes` {{Optional_Inline}}
- : An {{jsxref("Array")}} specifying the types of entities to be used for hit test source creation. If no entity type is specified, the array defaults to a single element with the `plane` type. Possible types:
- `point`: Compute hit test results based on characteristic points detected.
- `plane`: Compute hit test results based on real-world planes detected.
- `mesh`: Compute hit test results based on meshes detected.
- `offsetRay` {{Optional_Inline}}
- : The {{domxref("XRRay")}} object that will be used to perform hit test. If no `XRRay` object has been provided, a new `XRRay` object is constructed without any parameters.
### Return value
A {{jsxref("Promise")}} that resolves with an {{domxref("XRTransientInputHitTestSource")}} object.
### Exceptions
Rather than throwing true exceptions, `requestHitTestSourceForTransientInput()` rejects the
returned promise with a {{domxref("DOMException")}}, specifically, one of the following:
- `NotSupportedError` {{domxref("DOMException")}}
- : Thrown if `hit-test` is not an enabled feature in {{domxref("XRSystem.requestSession()")}}.
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the session has already ended.
- `NotAllowedError` {{domxref("DOMException")}}
- : Thrown if there is an unreasonable amount of requests. Some user agents might limit usage for privacy reasons.
## Examples
### Requesting a transient hit test source
To request a hit test source, start an {{domxref("XRSession")}} with the `hit-test` session feature enabled. Next, configure the hit test source and store it for later use in the frame loop and call {{domxref("XRFrame.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("XRSession.requestHitTestSource()")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrsession | data/mdn-content/files/en-us/web/api/xrsession/domoverlaystate/index.md | ---
title: "XRSession: domOverlayState property"
short-title: domOverlayState
slug: Web/API/XRSession/domOverlayState
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRSession.domOverlayState
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The _read-only_ **`domOverlayState`** property of an `immersive-ar`
{{DOMxRef("XRSession")}} provides information about the DOM overlay, if the feature is enabled.
## Value
Returns [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) if the DOM overlay feature is not supported or not enabled or an object containing information about the DOM overlay state with the following properties:
- `type`
- : A string indicating how the DOM overlay is being displayed. Possible values:
- `screen`
- : The overlay is drawn on the entire screen-based device (for handheld AR devices).
- `head-locked`
- : The overlay is drawn at a head-locked UI that fills the renderable viewport and follows the user's head movement.
- `floating`
- : The overlay appears as a rectangle floating in space that's kept in front of the user. It doesn't necessarily fill up the entire space and/or is strictly head-locked.
## Examples
### Checking which DOM overlay got enabled
```js
if (session.domOverlayState) {
console.log(session.domOverlayState.type);
} else {
console.log("DOM overlay not supported or enabled!");
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Element.beforexrselect_event", "beforexrselect")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/file_and_directory_entries_api/index.md | ---
title: File and Directory Entries API
slug: Web/API/File_and_Directory_Entries_API
page-type: web-api-overview
browser-compat: api.FileSystem
---
{{DefaultAPISidebar("File and Directory Entries API")}}
The File and Directory Entries API simulates a local file system that web apps can navigate within and access files in. You can develop apps which read, write, and create files and/or directories in a virtual, sandboxed file system.
## Getting access to a file system
There are two ways to get access to file systems defined in the current specification draft:
- When handling a {{domxref("HTMLElement/drop_event", "drop")}} event for drag and drop, you can call {{domxref("DataTransferItem.webkitGetAsEntry()")}} to get the {{domxref("FileSystemEntry")}} for a dropped item. If the result isn't `null`, then it's a dropped file or directory, and you can use file system calls to work with it.
- The {{domxref("HTMLInputElement.webkitEntries")}} property lets you access the {{domxref("FileSystemFileEntry")}} objects for the currently selected files, but only if they are dragged-and-dropped onto the file chooser ([Firefox bug 1326031](https://bugzil.la/1326031)). If {{domxref("HTMLInputElement.webkitdirectory")}} is `true`, the {{HTMLElement("input")}} element is instead a directory picker, and you get {{domxref("FileSystemDirectoryEntry")}} objects for each selected directory.
## Interfaces
The File and Directory Entries API includes the following interfaces:
- {{domxref("FileSystem")}}
- : Represents a file system.
- {{domxref("FileSystemEntry")}}
- : The basic interface representing a single entry in a file system. This is implemented by other interfaces which represent files or directories.
- {{domxref("FileSystemFileEntry")}}
- : Represents a single file in a file system.
- {{domxref("FileSystemDirectoryEntry")}}
- : Represents a single directory in a file system.
- {{domxref("FileSystemDirectoryReader")}}
- : Created by calling {{domxref("FileSystemDirectoryEntry.createReader()")}}, this interface provides the functionality which lets you read the contents of a directory.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
- [File and Directory Entries API support in Firefox](/en-US/docs/Web/API/File_and_Directory_Entries_API/Firefox_support)
| 0 |
data/mdn-content/files/en-us/web/api/file_and_directory_entries_api | data/mdn-content/files/en-us/web/api/file_and_directory_entries_api/firefox_support/index.md | ---
title: File and Directory Entries API support in Firefox
slug: Web/API/File_and_Directory_Entries_API/Firefox_support
page-type: guide
---
{{DefaultAPISidebar("File and Directory Entries API")}}
The original File System API was created to let browsers implement support for accessing a sandboxed virtual file system on the user's storage device. Work to standardize the specification was abandoned back in 2012, but by that point, Google Chrome included its own implementation of the API. Over time, a number of popular sites and Web applications came to use it, often without providing any means of falling back to standard APIs or even checking to be sure the API is available before using it. Mozilla instead opted to implement other APIs which can be used to solve many of the same problems, such as [IndexedDB](/en-US/docs/Web/API/IndexedDB_API); see the blog post [Why no FileSystem API in Firefox?](https://hacks.mozilla.org/2012/07/why-no-filesystem-api-in-firefox/) for more insights.
This has caused a number of popular websites not to work properly on browsers other than Chrome. Because of that, an attempt was made to create a spec offering the features of Google's API which consensus could be reached on. The result was the [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API). This subset of the API provided by Chrome is still not fully specified; however, for web compatibility reasons, it was decided to implement a subset of the API in Firefox; this was introduced in Firefox 50.
This article describes how the Firefox implementation of the File and Directory Entries API differs from other implementations and/or the specification.
## Chrome deviations from the specification
The largest compatibility issue still remaining is that Chrome is still using older names for many of the interfaces in the API, since they implemented a related but different specification:
<table class="standard-table">
<thead>
<tr>
<th scope="row">Name in specification</th>
<th scope="col">Name in Google Chrome</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>FileSystemDirectoryEntry</code></td>
<td><code>DirectoryEntry</code></td>
</tr>
<tr>
<td><code>FileSystemDirectoryEntrySync</code></td>
<td><code>DirectoryEntrySync</code></td>
</tr>
<tr>
<td><code>FileSystemDirectoryReader</code></td>
<td><code>DirectoryReader</code></td>
</tr>
<tr>
<td><code>FileSystemDirectoryReaderSync</code></td>
<td><code>DirectoryReaderSync</code></td>
</tr>
<tr>
<td><code>FileSystemEntry</code></td>
<td><code>Entry</code></td>
</tr>
<tr>
<td><code>FileSystemEntrySync</code></td>
<td><code>EntrySync</code></td>
</tr>
<tr>
<td><code>FileSystemFileEntry</code></td>
<td><code>FileEntry</code></td>
</tr>
<tr>
<td><code>FileSystemFileEntrySync</code></td>
<td><code>FileEntrySync</code></td>
</tr>
</tbody>
</table>
Be sure to account for this in your code by allowing for both names. Hopefully Chrome will be updated soon to use the newer names!
To ensure your code will work in both Chrome and other browsers, you can include code similar to the following:
```js
const FileSystemDirectoryEntry =
window.FileSystemDirectoryEntry || window.DirectoryEntry;
const FileSystemEntry = window.FileSystemEntry || window.Entry;
```
## Limitations in Firefox
Next, let's look at limitations of the Firefox implementation of the API. In broad strokes, those limitations can be summarized as follows:
- Content scripts can't create file systems or initiate access to a file system. There are only two ways to get access to file system entries at this time:
- The {{HTMLElement("input")}} element, using the {{domxref("HTMLInputElement.webkitEntries")}} property to access an array of {{domxref("FileSystemEntry")}} objects describing file system entries you can then read.
- Using drag and drop by calling the {{domxref("DataTransferItem.webkitGetAsEntry")}} method, which lets you get a {{domxref("FileSystemFileEntry")}} or {{domxref("FileSystemDirectoryEntry")}} for files dropped on a drop zone.
- Firefox doesn't support the `"filesystem:"` URL scheme.
## 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)
- [File and Directory Entries API](https://wicg.github.io/entries-api/) specification
- Original specification for the [File API: Directories and System](https://dev.w3.org/2009/dap/file-system/file-dir-sys.html) (often called the "FileSystem API"); Google Chrome was the only browser to implement this **abandoned** API.
| 0 |
data/mdn-content/files/en-us/web/api/file_and_directory_entries_api | data/mdn-content/files/en-us/web/api/file_and_directory_entries_api/introduction/index.md | ---
title: Introduction to the File and Directory Entries API
slug: Web/API/File_and_Directory_Entries_API/Introduction
page-type: guide
browser-compat: api.FileSystem
---
{{DefaultAPISidebar("File and Directory Entries API")}}
The [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API) simulates a local file system that web apps can navigate around. You can develop apps that can read, write, and create files and directories in a sandboxed, virtual file system.
The File and Directory Entries API interacts with other related APIs. It was built on the File Writer API, which, in turn, was built on File API. Each of the APIs adds different functionality. These APIs are a giant evolutionary leap for web apps, which can now cache and process large amounts of data.
## About this document
This introduction discusses essential concepts and terminology in the File and Directory Entries API. It gives you the big picture and orients you to [key concepts](#big_concepts). It also describes [restrictions](#restrictions) that raise security errors if you ignore them. To learn more about terminology used in this API, see the [Definitions](#definitions) section.
For the reference documentation on the File and Directory Entries API, see the [reference](/en-US/docs/Web/API/FileSystem) landing page and its subpages.
The specification is still being defined and is subject to change.
## Overview
The File and Directory Entries API includes both [asynchronous and synchronous versions](#asynchronous_and_synchronous_versions) of the interfaces. The asynchronous API can be used in cases where you don't want an outstanding operation to block the UI. The synchronous API, on the other hand, allows for simpler programming model, but it must be used with [WebWorkers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers).
### Usefulness of the API
The File and Directory Entries API is an important API for the following reasons:
- It lets apps have offline and storage features that involve large binary blobs.
- It can improve performance by letting an app pre-fetch assets in the background and cache locally.
- It lets users of your web app directly edit a binary file that's in their local file directory.
- It provides a storage API that is already familiar to your users, who are used to working with file systems.
For examples of features you can create with this app, see the [Sample use cases](#sample_use_cases) section.
### The File and Directory Entries API and other storage APIs
The File and Directory Entries API is an alternative to other storage APIs such as [IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Basic_Terminology). The API is a better choice for apps that deal with blobs for the following reasons:
- The File and Directory Entries API offers client-side storage for use cases that are not addressed by databases. If you want to have large mutable chunks of data, the File and Directory Entries API is a much more efficient storage solution than a database.
- While Firefox supports blob storage for IndexedDB, Chrome currently does not (Chrome is still implementing support for blob storage in IndexedDB). If you are targeting Chrome for your app and you want to store blobs, the File and Directory Entries API and App Cache are your only choices. However, AppCache storage isn't locally mutable, and doesn't allow for fine-grained client-side management.
- In Chrome, you can use the File and Directory Entries API with the [Quota Management API](https://developer.chrome.com/docs/apps/offline_storage/), which lets you ask for more storage and manage your storage quota.
### Sample use cases
The following are just a few examples of how you can use the File and Directory Entries API:
- Apps with persistent uploader
- When a file or directory is selected for upload, you can copy the file into a local sandbox and upload a chunk at a time.
- The app can restart uploads after an interruption, such as the browser being closed or crashing, connectivity getting interrupted, or the computer getting shut down.
- Video game or other apps with lots of media assets
- The app downloads one or several large tarballs and expands them locally into a directory structure.
- The app pre-fetches assets in the background, so the user can go to the next task or game level without waiting for a download.
- Audio or photo editor with offline access or local cache (great for performance and speed)
- The app can write to files in place (for example, overwriting just the ID3/EXIF tags and not the entire file).
- Offline video viewer
- The app can download large files (>1GB) for later viewing.
- The app can access partially downloaded files (so that you can watch the first chapter of your DVD, even if the app is still downloading the rest of the content or if the app didn't complete the download because you had to run to catch a train).
- Offline web mail client
- The client downloads attachments and stores them locally.
- The client caches attachments for later upload.
## Big concepts
Before using the File and Directory Entries API, you must understand a few concepts.
### Virtualized file system
The API doesn't give you access to the local file system, nor is the sandbox really a section of the file system. Instead, it is a virtualized file system that looks like a full-fledged file system to the web app. It does not necessarily have a relationship to the local file system outside the browser.
What this means is that a web app and a desktop app cannot share the same file at the same time. The API does not let your web app reach outside the browser to files that desktop apps can also work on. You can, however, export a file from a web app to a desktop app. For example, you can use the File API, create a blob, redirect an iframe to the blob, and invoke the download manager.
### Different storage types
An application can request temporary or persistent storage. Temporary storage is easier to get, because the browser just gives it to you, but it is limited and can be deleted by the browser when it runs out of space. Persistent storage, on the other hand, might offer you larger space that can only be deleted by the user, but it requires the user to grant you permission.
Use temporary storage for caching and persistent storage for data that you want your app to keep—such as user-generated or unique data.
### Storage quotas
To prevent a web app from using up the entire disk, browsers might impose a quota for each app and allocate storage among web apps.
How storage space is granted or allocated and how you can manage storage are idiosyncratic to the browser, so you need to check the respective documentation of the browser. Google Chrome, for example, allows temporary storage beyond the 5 MB required in the specifications and supports the Quota Management API. To learn more about the Chrome-specific implementation, see [Managing HTML Offline Storage](https://developer.chrome.com/docs/apps/offline_storage/).
### Asynchronous and synchronous versions
The File and Directory Entries API comes with asynchronous and synchronous versions. Both versions of the API offer the same capabilities and features. In fact, they are almost alike, except for a few differences.
- WebWorkers
- : The asynchronous API can be used in either the document or [WebWorkers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) context, while the synchronous API is for use with WebWorkers only.
- Callbacks
- : The asynchronous API doesn't give you data by returning values; instead, you have to pass a callback function. You send requests for operations to happen, and get notified by callbacks. In contrast, the synchronous API does not use callbacks because the API methods return values.
- Global methods of the asynchronous and synchronous APIs
- : The asynchronous API has the following global methods: `requestFileSystem()` and `resolveLocalFileSystemURL()`. These methods are members of both the window object and the worker global scope. The synchronous API, on the other hand, uses the following methods: `requestFileSystemSync()` and `resolveLocalFileSystemSyncURL()`. These synchronous methods are members of the worker's global scope only, not the window object.
The synchronous API can be simpler for some tasks. Its direct, in-order programming model can make code easier to read. The drawback of synchronous API has to do with its interactions with Web Workers, which has some limitations.
### Using the error callbacks for asynchronous API
When using the asynchronous API, always use the error callbacks. Although the error callbacks for the methods are optional parameters, they are not optional for your sanity. You want to know why your calls failed. At minimum, handle the errors to provide error messages, so you'll have an idea of what's going on.
### Interacting with other APIs
The File and Directory Entries API is designed to be used with other APIs and elements on the web platform. For example, you are likely to use one of the following:
- {{domxref("fetch()")}}
- Drag and Drop API
- Web Workers (for the synchronous version of the File and Directory Entries API)
- The `input` element (to programmatically obtain a list of files from the element)
### Case-sensitive
The filesystem API is case-sensitive, and case-preserving.
## Restrictions
For security reasons, browsers impose restrictions on file access. If you ignore them, you will get security errors.
### Adhering to the same-origin policy
An origin is the domain, application layer protocol, and port of a URL of the document where the script is being executed. Each origin has its own associated set of file systems.
The security boundary imposed on file system prevents applications from accessing data with a different origin. This protects private data by preventing access and deletion. For example, while an app or a page in `http://www.example.com/app/` can access files from `http://www.example.com/dir/`, because they have the same origin, it cannot retrieve files from `http://www.example.com:8080/dir/` (different port) or `https://www.example.com/dir/` (different protocol).
### Unable to create and rename executable files
To prevent malicious apps from running hostile executables, you cannot create executable files within the sandbox of the File and Directory Entries API.
### Sandboxed file system
Because the file system is sandboxed, a web app cannot access another app's files. You also cannot read or write files to an arbitrary folder (for example, My Pictures and My Documents) on the user's hard drive.
### You cannot run your app from file://
You cannot run your app locally from `file://`. If you do so, the browser throws errors or your app fails silently. This restriction also applies to many of the file APIs, including Blob and FileReader.
For testing purposes, you can bypass the restriction on Chrome by starting the browser with the `--allow-file-access-from-files` flag. Use this flag only for this purpose.
## Definitions
This section defines and explains terms used in the File and Directory Entries API.
- blob
- : Stands for binary large object. A blob is a set of binary data that is stored as a single object. It is a general-purpose way to reference binary data in web applications. A blob can be an image or an audio file.
- Blob
- : Blob—with a capital B—is a data structure that is immutable, which means that binary data referenced by a Blob cannot be modified directly. This makes Blobs act predictably when they are passed to asynchronous APIs.
- persistent storage
- : Persistent storage is storage that stays in the browser unless the user expunges it or the app deletes it.
- temporary storage
- : Transient storage is available to any web app. It is automatic and does not need to be requested, but the browser can delete the storage without warning.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Read files in JavaScript](https://web.dev/articles/read-files) (web.dev)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svganimatedboolean/index.md | ---
title: SVGAnimatedBoolean
slug: Web/API/SVGAnimatedBoolean
page-type: web-api-interface
browser-compat: api.SVGAnimatedBoolean
---
{{APIRef("SVG")}}
## SVG animated boolean interface
The `SVGAnimatedBoolean` interface is used for attributes of type boolean which can be animated.
### Interface overview
<table class="no-markdown">
<tbody>
<tr>
<th scope="row">Also implement</th>
<td><em>None</em></td>
</tr>
<tr>
<th scope="row">Methods</th>
<td><em>None</em></td>
</tr>
<tr>
<th scope="row">Properties</th>
<td>
<ul>
<li>readonly boolean <code>baseVal</code></li>
<li>readonly boolean <code>animVal</code></li>
</ul>
</td>
</tr>
<tr>
<th scope="row">Normative document</th>
<td>
<a
href="https://www.w3.org/TR/SVG11/types.html#InterfaceSVGAnimatedBoolean"
>SVG 1.1 (2nd Edition)</a
>
</td>
</tr>
</tbody>
</table>
## Instance properties
<table class="no-markdown">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>baseVal</code></td>
<td>boolean</td>
<td>
The base value of the given attribute before applying any animations.
</td>
</tr>
<tr>
<td><code>animVal</code></td>
<td>boolean</td>
<td>
If the given attribute or property is being animated, contains the
current animated value of the attribute or property. If the given
attribute or property is not currently being animated, contains the same
value as <code>baseVal</code>.
</td>
</tr>
</tbody>
</table>
## Instance methods
The `SVGAnimatedBoolean` interface do not provide any specific methods.
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svglengthlist/index.md | ---
title: SVGLengthList
slug: Web/API/SVGLengthList
page-type: web-api-interface
browser-compat: api.SVGLengthList
---
{{APIRef("SVG")}}
## SVG length list interface
The `SVGLengthList` defines a list of {{ domxref("SVGLength") }} objects.
An `SVGLengthList` object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown.
An `SVGLengthList` is indexable and can be accessed like an array.
### Interface overview
<table class="standard-table">
<tbody>
<tr>
<th scope="row">Also implement</th>
<td><em>None</em></td>
</tr>
<tr>
<th scope="row">Methods</th>
<td>
<ul>
<li><code>void clear()</code></li>
<li>
{{ domxref("SVGLength") }}
<code
>initialize(in {{ domxref("SVGLength") }}
<em>newItem</em>)</code
>
</li>
<li>
{{ domxref("SVGLength") }}
<code>getItem(in unsigned long <em>index</em>)</code>
</li>
<li>
{{ domxref("SVGLength") }}
<code
>insertItemBefore(in {{ domxref("SVGLength") }}
<em>newItem</em>, in unsigned long <em>index</em>)</code
>
</li>
<li>
{{ domxref("SVGLength") }} <code>replaceItem(</code
><code
>in {{ domxref("SVGLength") }} <em>newItem</em>, in
unsigned long <em>index</em></code
><code>)</code>
</li>
<li>
{{ domxref("SVGLength") }}
<code>removeItem(in unsigned long <em>index</em>)</code>
</li>
<li>
{{ domxref("SVGLength") }}
<code
>appendItem(in {{ domxref("SVGLength") }}
<em>newItem</em>)</code
>
</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">Properties</th>
<td>
<ul>
<li>readonly unsigned long <code>numberOfItems</code></li>
<li>
readonly unsigned long
<code>length</code> {{ non-standard_inline() }}
</li>
</ul>
</td>
</tr>
<tr>
<th scope="row">Normative document</th>
<td>
<a href="https://www.w3.org/TR/SVG11/types.html#InterfaceSVGLengthList"
>SVG 1.1 (2nd Edition)</a
>
</td>
</tr>
</tbody>
</table>
## Instance properties
| Name | Type | Description |
| ------------------------------------ | ------------- | -------------------------------- |
| `numberOfItems` | unsigned long | The number of items in the list. |
| `length` {{ non-standard_inline() }} | unsigned long | The number of items in the list. |
## Instance methods
<table class="standard-table">
<thead>
<tr>
<th>Name & Arguments</th>
<th>Return</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<code><strong>clear</strong>()</code>
</td>
<td><em>void</em></td>
<td>
<p>
Clears all existing current items from the list, with the result being
an empty list.
</p>
<p><strong>Exceptions:</strong></p>
<ul>
<li>
a {{ domxref("DOMException") }} with code
<code>NO_MODIFICATION_ALLOWED_ERR</code> is raised when the list
corresponds to a read only attribute or when the object itself is
read only.
</li>
</ul>
</td>
</tr>
<tr>
<td>
<code><strong>initialize</strong>(</code
><code>in {{ domxref("SVGLength") }} <em>newItem</em></code
><code>)</code>
</td>
<td>{{ domxref("SVGLength") }}</td>
<td>
<p>
Clears all existing current items from the list and re-initializes the
list to hold the single item specified by the parameter. If the
inserted item is already in a list, it is removed from its previous
list before it is inserted into this list. The inserted item is the
item itself and not a copy. The return value is the item inserted into
the list.
</p>
<p><strong>Exceptions:</strong></p>
<ul>
<li>
a {{ domxref("DOMException") }} with code
<code>NO_MODIFICATION_ALLOWED_ERR</code> is raised when the list
corresponds to a read only attribute or when the object itself is
read only.
</li>
</ul>
</td>
</tr>
<tr>
<td>
<code><strong>getItem</strong>(in unsigned long <em>index</em>)</code>
</td>
<td>{{ domxref("SVGLength") }}</td>
<td>
<p>
Returns the specified item from the list. The returned item is the
item itself and not a copy. Any changes made to the item are
immediately reflected in the list. The first item is number 0.
</p>
<p><strong>Exceptions:</strong></p>
<ul>
<li>
a {{ domxref("DOMException") }} with code
<code>NO_MODIFICATION_ALLOWED_ERR</code> is raised when the list
corresponds to a read only attribute or when the object itself is
read only.
</li>
</ul>
</td>
</tr>
<tr>
<td>
<code
><strong>insertItemBefore</strong>(in
{{ domxref("SVGLength") }} <em>newItem</em>, in unsigned
long <em>index</em>)</code
>
</td>
<td>{{ domxref("SVGLength") }}</td>
<td>
<p>
Inserts a new item into the list at the specified position. The first
item is number 0. If <code>newItem</code> is already in a list, it is
removed from its previous list before it is inserted into this list.
The inserted item is the item itself and not a copy. If the item is
already in this list, note that the index of the item to insert before
is before the removal of the item. If the <code>index</code> is equal
to 0, then the new item is inserted at the front of the list. If the
index is greater than or equal to <code>numberOfItems</code>, then the
new item is appended to the end of the list.
</p>
<p><strong>Exceptions:</strong></p>
<ul>
<li>
a {{ domxref("DOMException") }} with code
<code>NO_MODIFICATION_ALLOWED_ERR</code> is raised when the list
corresponds to a read only attribute or when the object itself is
read only.
</li>
</ul>
</td>
</tr>
<tr>
<td>
<code><strong>replaceItem</strong>(</code
><code
>in {{ domxref("SVGLength") }} <em>newItem</em>, in unsigned
long <em>index</em></code
><code>)</code>
</td>
<td>{{ domxref("SVGLength") }}</td>
<td>
<p>
Replaces an existing item in the list with a new item. If
<code>newItem</code> is already in a list, it is removed from its
previous list before it is inserted into this list. The inserted item
is the item itself and not a copy. If the item is already in this
list, note that the index of the item to replace is before the removal
of the item.
</p>
<p><strong>Exceptions:</strong></p>
<ul>
<li>
a {{ domxref("DOMException") }} with code
<code>NO_MODIFICATION_ALLOWED_ERR</code> is raised when the list
corresponds to a read only attribute or when the object itself is
read only.
</li>
<li>
a {{ domxref("DOMException") }} with code
<code>INDEX_SIZE_ERR</code> is raised if the index number is greater
than or equal to <code>numberOfItems</code>.
</li>
</ul>
</td>
</tr>
<tr>
<td>
<code
><strong>removeItem</strong>(in unsigned long <em>index</em>)</code
>
</td>
<td>{{ domxref("SVGLength") }}</td>
<td>
<p>Removes an existing item from the list.</p>
<p><strong>Exceptions:</strong></p>
<ul>
<li>
a {{ domxref("DOMException") }} with code
<code>NO_MODIFICATION_ALLOWED_ERR</code> is raised when the list
corresponds to a read only attribute or when the object itself is
read only.
</li>
<li>
a {{ domxref("DOMException") }} with code
<code>INDEX_SIZE_ERR</code> is raised if the index number is greater
than or equal to <code>numberOfItems</code>.
</li>
</ul>
</td>
</tr>
<tr>
<td>
<code
><strong>appendItem</strong>(in {{ domxref("SVGLength") }}
<em>newItem</em>)</code
>
</td>
<td>{{ domxref("SVGLength") }}</td>
<td>
<p>
Inserts a new item at the end of the list. If <code>newItem</code> is
already in a list, it is removed from its previous list before it is
inserted into this list. The inserted item is the item itself and not
a copy.
</p>
<p><strong>Exceptions:</strong></p>
<ul>
<li>
a {{ domxref("DOMException") }} with code
<code>NO_MODIFICATION_ALLOWED_ERR</code> is raised when the list
corresponds to a read only attribute or when the object itself is
read only.
</li>
</ul>
</td>
</tr>
</tbody>
</table>
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/xrtransientinputhittestsource/index.md | ---
title: XRTransientInputHitTestSource
slug: Web/API/XRTransientInputHitTestSource
page-type: web-api-interface
status:
- experimental
browser-compat: api.XRTransientInputHitTestSource
---
{{APIRef("WebXR Device API")}} {{secureContext_header}}{{SeeCompatTable}}
The **`XRTransientInputHitTestSource`** interface of the [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API) handles transient input hit test subscriptions. You can get an `XRTransientInputHitTestSource` object by calling the {{domxref("XRSession.requestHitTestSourceForTransientInput()")}}.
This object doesn't itself contain transient input hit test results, but it is used to compute hit tests for each {{domxref("XRFrame")}} by calling {{domxref("XRFrame.getHitTestResultsForTransientInput()")}}, which returns {{domxref("XRTransientInputHitTestResult")}} objects.
## Instance properties
None.
## Instance methods
- {{domxref("XRTransientInputHitTestSource.cancel()")}} {{Experimental_Inline}}
- : Unsubscribes from the transient input hit test.
## Examples
### Getting an `XRTransientInputHitTestSource` object for a session
Use the {{domxref("XRSession.requestHitTestSourceForTransientInput()")}} method to get a transient input hit test source.
```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
}
```
### Unsubscribe from a transient input hit test
To unsubscribe from a transient input hit test source, use the {{domxref("XRTransientInputHitTestSource.cancel()")}} method. Since the object will no longer be usable, you can clean up and set the `XRTransientInputHitTestSource` object to [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null).
```js
transientHitTestSource.cancel();
transientHitTestSource = null;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRTransientInputHitTestResult")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrtransientinputhittestsource | data/mdn-content/files/en-us/web/api/xrtransientinputhittestsource/cancel/index.md | ---
title: "XRTransientInputHitTestSource: cancel() method"
short-title: cancel()
slug: Web/API/XRTransientInputHitTestSource/cancel
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRTransientInputHitTestSource.cancel
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`cancel()`** method of the {{domxref("XRTransientInputHitTestSource")}} interface unsubscribes a transient input hit test.
## Syntax
```js-nolint
cancel()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Examples
### Unsubscribe from hit test
The `cancel()` method unsubscribes from a transient input hit test source. Since the {{domxref("XRTransientInputHitTestSource")}} object will no longer be usable, you can clean up and set it to [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null).
```js
transientHitTestSource.cancel();
transientHitTestSource = null;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgfeturbulenceelement/index.md | ---
title: SVGFETurbulenceElement
slug: Web/API/SVGFETurbulenceElement
page-type: web-api-interface
browser-compat: api.SVGFETurbulenceElement
---
{{APIRef("SVG")}}
The **`SVGFETurbulenceElement`** interface corresponds to the {{SVGElement("feTurbulence")}} element.
{{InheritanceDiagram}}
## Constants
### Turbulence types
<table class="no-markdown">
<tbody>
<tr>
<th>Name</th>
<th>Value</th>
<th>Description</th>
</tr>
<tr>
<td><code>SVG_TURBULENCE_TYPE_UNKNOWN</code></td>
<td>0</td>
<td>
The type is not one of predefined types. It is invalid to attempt to
define a new value of this type or to attempt to switch an existing
value to this type.
</td>
</tr>
<tr>
<td><code>SVG_TURBULENCE_TYPE_FRACTALNOISE</code></td>
<td>1</td>
<td>Corresponds to the <code>fractalNoise</code> value.</td>
</tr>
<tr>
<td><code>SVG_TURBULENCE_TYPE_TURBULENCE</code></td>
<td>2</td>
<td>Corresponds to <code>turbulence</code> value.</td>
</tr>
</tbody>
</table>
### Stitch options
<table class="no-markdown">
<tbody>
<tr>
<th>Name</th>
<th>Value</th>
<th>Description</th>
</tr>
<tr>
<td><code>SVG_STITCHTYPE_UNKNOWN</code></td>
<td>0</td>
<td>
The type is not one of predefined types. It is invalid to attempt to
define a new value of this type or to attempt to switch an existing
value to this type.
</td>
</tr>
<tr>
<td><code>SVG_STITCHTYPE_STITCH</code></td>
<td>1</td>
<td>Corresponds to the <code>stitch</code> value.</td>
</tr>
<tr>
<td><code>SVG_STITCHTYPE_NOSTITCH</code></td>
<td>2</td>
<td>Corresponds to <code>noStitch</code> value.</td>
</tr>
</tbody>
</table>
## Instance properties
_This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._
- {{domxref("SVGFETurbulenceElement.baseFrequencyX")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedNumber")}} corresponding to the X component of the {{SVGAttr("baseFrequency")}} attribute of the given element.
- {{domxref("SVGFETurbulenceElement.baseFrequencyY")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedNumber")}} corresponding to the Y component of the {{SVGAttr("baseFrequency")}} attribute of the given element.
- {{domxref("SVGFETurbulenceElement.height")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("height")}} attribute of the given element.
- {{domxref("SVGFETurbulenceElement.numOctaves")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedInteger")}} corresponding to the {{SVGAttr("numOctaves")}} attribute of the given element.
- {{domxref("SVGFETurbulenceElement.result")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("result")}} attribute of the given element.
- {{domxref("SVGFETurbulenceElement.seed")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("seed")}} attribute of the given element.
- {{domxref("SVGFETurbulenceElement.stitchTiles")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("stitchTiles")}} attribute of the given element. It takes one of the `SVG_STITCHTYPE_*` constants defined on this interface.
- {{domxref("SVGFETurbulenceElement.type")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("type")}} attribute of the given element. It takes one of the `SVG_TURBULENCE_TYPE_*` constants defined on this interface.
- {{domxref("SVGFETurbulenceElement.width")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("width")}} attribute of the given element.
- {{domxref("SVGFETurbulenceElement.x")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x")}} attribute of the given element.
- {{domxref("SVGFETurbulenceElement.y")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("y")}} attribute of the given element.
## Instance methods
_This interface does not provide any specific methods, but implements those of its parent, {{domxref("SVGElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{SVGElement("feTurbulence")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/window_controls_overlay_api/index.md | ---
title: Window Controls Overlay API
slug: Web/API/Window_Controls_Overlay_API
page-type: web-api-overview
status:
- experimental
browser-compat: api.WindowControlsOverlay
spec-urls: https://wicg.github.io/window-controls-overlay/
---
{{DefaultAPISidebar("Window Controls Overlay API")}}{{SeeCompatTable}}
The Window Controls Overlay API gives Progressive Web Apps installed on desktop operating systems the ability to hide the default window title bar and display their own content
over the full surface area of the app window, turning the control buttons (maximize, minimize, and close) into an overlay.
## Opting-in to the feature
Before using this feature, the following conditions must be true:
- The Web App Manifest's [`display_override`](/en-US/docs/Web/Manifest/display_override) member must be set to `window-controls-overlay`.
- The Progressive Web App must be installed on a desktop operating system.
## Main concepts
Progressive Web Apps installed on desktop devices can be displayed in standalone app windows, just like native apps. Here is what an application window looks like:

As seen above, the app window is made of two main areas:
- The title bar area at the top.
- The application content area at the bottom, which displays the HTML content from the PWA.
The title bar area contains the system-critical maximize, minimize, and close buttons (their position may vary across operating systems), the name of the application (which comes from the `<title>` HTML element in the page), and possibly user-agent-specific PWA buttons.
With the Window Controls Overlay feature, Progressive Web Apps can display their web content over the whole app window surface area. Because the window control buttons and user-agent-specific PWA buttons must remain visible, they get turned into an overlay displayed on top of the web content.

The part of the title bar that normally contains the application name is hidden, and the area that it normally occupies becomes available via the Window Controls Overlay API.
PWAs can use the API to position content in this area, and avoid having content hidden behind the control buttons overlay, similar to how web authors can account for the presence of notches on certain mobile devices.
## CSS environment variables
Progressive Web Apps can position their web content in the area that the title bar normally occupies by using the `titlebar-area-x`, `titlebar-area-y`, `titlebar-area-width`, and `titlebar-area-height` CSS environment variables.
See [Using env() to ensure content is not obscured by window control buttons in desktop PWAs](/en-US/docs/Web/CSS/env#using_env_to_ensure_content_is_not_obscured_by_window_control_buttons_in_desktop_pwas).
## Interfaces
- {{domxref("WindowControlsOverlay")}} {{Experimental_Inline}}
- : Provides information about the visibility and geometry of the title bar and an event to know whenever it changes.
- {{domxref("WindowControlsOverlayGeometryChangeEvent")}} {{Experimental_Inline}}
- : Represents events providing information related to the desktop Progress Web App's title var region when its size or visibility changes.
### Extensions to other interfaces
- {{domxref("Navigator.windowControlsOverlay")}}
- : Returns the {{domxref("WindowControlsOverlay")}} interface, which exposes information about the title bar geometry in desktop Progressive Web Apps.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Customize the window controls overlay of your PWA's title bar](https://web.dev/articles/window-controls-overlay)
- [Breaking Out of the Box](https://alistapart.com/article/breaking-out-of-the-box/)
- [Display content in the title bar](https://docs.microsoft.com/microsoft-edge/progressive-web-apps-chromium/how-to/window-controls-overlay)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/xpathnsresolver/index.md | ---
title: XPathNSResolver
slug: Web/API/XPathNSResolver
page-type: web-api-interface
browser-compat: api.XPathNSResolver
---
{{APIRef("DOM XPath")}}
The `XPathNSResolver` interface permits prefix strings in an {{Glossary("XPath")}} expression to be properly bound to namespace URI strings.
The {{domxref("XPathEvaluator")}} interface can construct an implementation of `XPathNSResolver` from a node, or the interface may be implemented by any application.
## Instance methods
- {{DOMxRef("XPathNSResolver.lookupNamespaceURI()")}}
- : Looks up the namespace URI associated to the given namespace prefix.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XPathEvaluator")}}
| 0 |
data/mdn-content/files/en-us/web/api/xpathnsresolver | data/mdn-content/files/en-us/web/api/xpathnsresolver/lookupnamespaceuri/index.md | ---
title: "XPathNSResolver: lookupNamespaceURI() method"
short-title: lookupNamespaceURI()
slug: Web/API/XPathNSResolver/lookupNamespaceURI
page-type: web-api-instance-method
browser-compat: api.XPathNSResolver.lookupNamespaceURI
---
{{APIRef("DOM XPath")}}
The `lookupNamespaceURI` method looks up the namespace URI associated to the
given namespace prefix within an {{Glossary("XPath")}} expression evaluated by the
{{domxref("XPathEvaluator")}} interface.
## Syntax
```js-nolint
lookupNamespaceURI(prefix)
```
### Parameters
- `prefix`
- : A string representing the prefix to look for.
### Return value
A string representing the associated namespace URI or
`null` if none is found.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XPathEvaluator")}}
- {{domxref("Node.lookupNamespaceURI()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmlstyleelement/index.md | ---
title: HTMLStyleElement
slug: Web/API/HTMLStyleElement
page-type: web-api-interface
browser-compat: api.HTMLStyleElement
---
{{APIRef("HTML DOM")}}
The **`HTMLStyleElement`** interface represents a {{HTMLElement("style")}} element. It inherits properties and methods from its parent, {{domxref("HTMLElement")}}.
This interface doesn't allow to manipulate the CSS it contains (in most case). To manipulate CSS, see [Using dynamic styling information](/en-US/docs/Web/API/CSS_Object_Model/Using_dynamic_styling_information) for an overview of the objects used to manipulate specified CSS properties using the DOM.
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its parent, {{domxref("HTMLElement")}}._
- {{domxref("HTMLStyleElement.media")}}
- : A string reflecting the HTML attribute representing the intended destination medium for style information.
- {{domxref("HTMLStyleElement.type")}} {{deprecated_inline}}
- : A string reflecting the HTML attribute representing the type of style being applied by this statement.
- {{domxref("HTMLStyleElement.disabled")}}
- : A boolean value indicating whether or not the associated stylesheet is disabled.
- {{domxref("HTMLStyleElement.sheet")}} {{ReadOnlyInline}}
- : Returns the {{domxref("CSSStyleSheet")}} object associated with the given element, or `null` if there is none.
## Instance methods
_No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The HTML element implementing this interface: {{HTMLElement("style")}}.
- [Using dynamic styling information](/en-US/docs/Web/API/CSS_Object_Model/Using_dynamic_styling_information) to see how to manipulate CSS.
| 0 |
data/mdn-content/files/en-us/web/api/htmlstyleelement | data/mdn-content/files/en-us/web/api/htmlstyleelement/media/index.md | ---
title: "HTMLStyleElement: media property"
short-title: media
slug: Web/API/HTMLStyleElement/media
page-type: web-api-instance-property
browser-compat: api.HTMLStyleElement.media
---
{{APIRef("HTML DOM")}}
The **`HTMLStyleElement.media`** property specifies the
intended destination medium for style information.
## Value
A string describing a single medium or a comma-separated list.
## Examples
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Test page</title>
<link
id="LinkedStyle"
rel="stylesheet"
href="document.css"
media="screen" />
<style id="InlineStyle" rel="stylesheet" media="screen, print">
p {
color: blue;
}
</style>
</head>
<body>
<script>
alert("LinkedStyle: " + document.getElementById("LinkedStyle").media); // 'screen'
alert("InlineStyle: " + document.getElementById("InlineStyle").media); // 'screen, print'
</script>
</body>
</html>
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlstyleelement | data/mdn-content/files/en-us/web/api/htmlstyleelement/sheet/index.md | ---
title: "HTMLStyleElement: sheet property"
short-title: sheet
slug: Web/API/HTMLStyleElement/sheet
page-type: web-api-instance-property
browser-compat: api.HTMLStyleElement.sheet
---
{{APIRef("HTML DOM")}}
The read-only **`sheet`** property of the {{domxref("HTMLStyleElement")}} interface
contains the stylesheet associated with that element.
An {{DOMxref("StyleSheet")}} is always associated with a {{domxref("HTMLStyleElement")}}, unless its `type` attribute is not `text/css`.
## Value
A {{DOMxRef("StyleSheet")}} object, or `null` if none is associated with the element.
## Examples
```html
<html>
<header>
<style media="print" />
…
</header>
</html>
```
The `sheet` property of the associated `HTMLStyleElement` object will return the {{domxref("StyleSheet")}} object describing it.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlstyleelement | data/mdn-content/files/en-us/web/api/htmlstyleelement/disabled/index.md | ---
title: "HTMLStyleElement: disabled property"
short-title: disabled
slug: Web/API/HTMLStyleElement/disabled
page-type: web-api-instance-property
browser-compat: api.HTMLStyleElement.disabled
---
{{APIRef("HTML DOM")}}
The **`HTMLStyleElement.disabled`** property can be used to get and set whether the stylesheet is disabled (`true`) or not (`false`).
Note that there is no corresponding `disabled` attribute on the [HTML `<style>` element](/en-US/docs/Web/HTML/Element/style).
## Value
Returns `true` if the stylesheet is disabled, or there is no associated stylesheet; otherwise `false`.
The value is `false` by default (if there is an associated stylesheet).
The property can be used to enable or disable an associated stylesheet.
Setting the property to `true` when there is no associated stylesheet has no effect.
## Examples
### Disabling an inline style
This example demonstrates programmatically setting the disabled property on a style that was defined in the HTML using the [HTML `<style>` element](/en-US/docs/Web/HTML/Element/style).
Note that you can also access any/all stylesheets in the document using [`Document.styleSheets`](/en-US/docs/Web/API/Document/styleSheets).
#### HTML
The HTML contains an HTML [`<style>`](/en-US/docs/Web/HTML/Element/style) element that makes paragraph elements blue, a paragraph element, and a button that will be used to enabled and disable the style.
```html
<button>Enable</button>
<style id="InlineStyle">
p {
color: blue;
}
</style>
<p>Text is black when style is disabled; blue when enabled.</p>
<p></p>
```
#### JavaScript
The code below gets the `style` element using its id, and then sets it as disabled.
As the style already exists, as it is defined in the SVG, this should succeed.
```js
const style = document.getElementById("InlineStyle");
style.disabled = true;
```
We then add an event handler for the button that toggles the `disabled` value and button text.
```js
const button = document.querySelector("button");
button.addEventListener("click", () => {
style.disabled = !style.disabled;
const buttonText = style.disabled ? "Enable" : "Disable";
button.innerText = buttonText;
});
```
#### Result
The result is shown below.
Press the button to toggle the `disabled` property value on the style used for the paragraph text.
{{EmbedLiveSample("Disabling a style defined in the SVG")}}
### Disabling a programmatically defined style
This example is very similar to the one above, except that the style is defined programmatically.
#### HTML
The HTML is similar to the previous case, but the definition does not include any default styling.
```html
<button>Enable</button>
<p>Text is black when style is disabled; blue when enabled.</p>
<p></p>
```
#### JavaScript
First we create the new style element on the HTML.
This is done by first creating a style element using [`Document.createElement()`](/en-US/docs/Web/API/Document/createElement), creating and appending a text node with the style definition, and then appending the style element to the document body.
```js
// Create the `style` element
const style = document.createElement("style");
const node = document.createTextNode("p { color: blue; }");
style.appendChild(node);
document.body.appendChild(style);
```
We can then disable the style as shown below.
Note that this is the earliest point at which setting the property to `true` will succeed.
Before this point the document did not have an associated style, and so the value defaults to `false`.
```js
//Disable the style
style.disabled = true;
```
Last of all we add an event handler for the button that toggles the disabled state and button text (this is the same as in the previous example).
```js
const button = document.querySelector("button");
button.addEventListener("click", () => {
style.disabled = !style.disabled;
const buttonText = style.disabled ? "Enable" : "Disable";
button.innerText = buttonText;
});
```
#### Result
The result is shown below.
Press the button to toggle the `disabled` state on the style used for the text.
{{EmbedLiveSample("Disabling a programmatically defined style")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("SVGStyleElement.disabled")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlstyleelement | data/mdn-content/files/en-us/web/api/htmlstyleelement/type/index.md | ---
title: "HTMLStyleElement: type property"
short-title: type
slug: Web/API/HTMLStyleElement/type
page-type: web-api-instance-property
status:
- deprecated
browser-compat: api.HTMLStyleElement.type
---
{{APIRef("HTML DOM")}} {{Deprecated_Header}}
The **`HTMLStyleElement.type`** property returns the type of the current style.
The value mirrors the [HTML `<style>` element's `type` attribute](/en-US/docs/Web/HTML/Element/style#type).
Authors should not use this property or rely on the value.
## Value
The permitted values are an empty string or a case-insensitive match for "text/css".
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("SVGStyleElement.type")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/oes_texture_float_linear/index.md | ---
title: OES_texture_float_linear extension
short-title: OES_texture_float_linear
slug: Web/API/OES_texture_float_linear
page-type: webgl-extension
browser-compat: api.OES_texture_float_linear
---
{{APIRef("WebGL")}}
The **`OES_texture_float_linear`** extension is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and allows linear filtering with floating-point pixel types for textures.
WebGL extensions are available using the {{domxref("WebGLRenderingContext.getExtension()")}} method. For more information, see also [Using Extensions](/en-US/docs/Web/API/WebGL_API/Using_Extensions) in the [WebGL tutorial](/en-US/docs/Web/API/WebGL_API/Tutorial).
> **Note:** This extension is available to both, {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}} and {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}} contexts.
## Linear filtering
The {{domxref("OES_texture_float")}} extension alone does not allow linear filtering with floating-point textures. This extension enables this ability.
With the help of this extension, you can now set the magnification or minification filter in the {{domxref("WebGLRenderingContext.texParameter()")}} method to one of `gl.LINEAR`, `gl.LINEAR_MIPMAP_NEAREST`, `gl.NEAREST_MIPMAP_LINEAR`, or `gl.LINEAR_MIPMAP_LINEAR`, and use floating-point textures.
## Examples
```js
gl.getExtension("OES_texture_float");
gl.getExtension("OES_texture_float_linear");
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.FLOAT, image);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("WebGLRenderingContext.getExtension()")}}
- {{domxref("WebGLRenderingContext.texImage2D()")}}
- {{domxref("WebGLRenderingContext.texSubImage2D()")}}
- {{domxref("OES_texture_float")}}
- {{domxref("OES_texture_half_float")}}
- {{domxref("OES_texture_half_float_linear")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/sharedstoragerunoperation/index.md | ---
title: SharedStorageRunOperation
slug: Web/API/SharedStorageRunOperation
page-type: web-api-interface
status:
- experimental
browser-compat: api.SharedStorageRunOperation
---
{{APIRef("Shared Storage API")}}{{SeeCompatTable}}
The **`SharedStorageRunOperation`** interface of the {{domxref("Shared Storage API", "Shared Storage API", "", "nocode")}} represents a [Run output gate](/en-US/docs/Web/API/Shared_Storage_API#run) operation.
{{InheritanceDiagram}}
## Instance methods
- {{domxref("SharedStorageRunOperation.run", "run()")}} {{Experimental_Inline}}
- : Defines the structure to which the `run()` method defined inside a Run output gate operation should conform.
## Examples
In this example, a class called `ReachMeasurementOperation` is defined in a worklet and is registered using {{domxref("SharedStorageWorkletGlobalScope.register()")}} with the name `reach-measurement`. `SharedStorageRunOperation` defines the structure to which this class must conform, essentially defining the parameters required for the `run()` method. Other than this requirement, the functionality of the class can be defined flexibly.
```js
// reach-measurement-worklet.js
const SCALE_FACTOR = 65536;
function convertContentIdToBucket(contentId) {
return BigInt(contentId);
}
class ReachMeasurementOperation {
async run(data) {
const { contentId } = data;
// Read from Shared Storage
const key = "has-reported-content";
const hasReportedContent = (await this.sharedStorage.get(key)) === "true";
// Do not report if a report has been sent already
if (hasReportedContent) {
return;
}
// Generate the aggregation key and the aggregatable value
const bucket = convertContentIdToBucket(contentId);
const value = 1 * SCALE_FACTOR;
// Send an aggregatable report via the Private Aggregation API
privateAggregation.sendHistogramReport({ bucket, value });
// Set the report submission status flag
await this.sharedStorage.set(key, true);
}
}
// Register the operation
register("reach-measurement", ReachMeasurementOperation);
```
> **Note:** It is possible to define and register multiple operations in the same shared storage worklet module script with different names. See {{domxref("SharedStorageOperation")}} for an example.
In the main browsing context, the `reach-measurement` operation is invoked using the {{domxref("WindowSharedStorage.run()")}} method:
```js
async function measureUniqueReach() {
// Load the Shared Storage worklet
await window.sharedStorage.worklet.addModule("reach-measurement-worklet.js");
// Run the reach measurement operation
await window.sharedStorage.run("reach-measurement", {
data: { contentId: "1234" },
});
}
measureUniqueReach();
```
For more details about this example, see [Unique reach measurement](https://developer.chrome.com/docs/privacy-sandbox/shared-storage/unique-reach/). See [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API) for more examples.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API)
| 0 |
data/mdn-content/files/en-us/web/api/sharedstoragerunoperation | data/mdn-content/files/en-us/web/api/sharedstoragerunoperation/run/index.md | ---
title: "SharedStorageRunOperation: run() method"
short-title: run()
slug: Web/API/SharedStorageRunOperation/run
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.SharedStorageRunOperation.run
---
{{APIRef("Shared Storage API")}}{{SeeCompatTable}}
The **`run()`** method of the
{{domxref("SharedStorageRunOperation")}} interface defines the structure to which the `run()` method defined inside a Run output gate operation should conform.
## Syntax
```js-nolint
run(data)
```
### Parameters
- `data`
- : An object representing any data required for executing the operation.
### Return value
A {{jsxref("Promise")}} that fulfills with `undefined`.
## Examples
See the main {{domxref("SharedStorageRunOperation")}} page for an example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/treewalker/index.md | ---
title: TreeWalker
slug: Web/API/TreeWalker
page-type: web-api-interface
browser-compat: api.TreeWalker
---
{{ APIRef("DOM") }}
The **`TreeWalker`** object represents the nodes of a document subtree and a position within them.
A `TreeWalker` can be created using the {{domxref("Document.createTreeWalker()")}} method.
## Instance properties
_This interface doesn't inherit any property._
- {{domxref("TreeWalker.root")}} {{ReadOnlyInline}}
- : Returns a {{domxref("Node")}} representing the root node as specified when the `TreeWalker` was created.
- {{domxref("TreeWalker.whatToShow")}} {{ReadOnlyInline}}
- : Returns an `unsigned long` being a bitmask made of constants describing the types of {{domxref("Node")}} that must be presented. Non-matching nodes are skipped, but their children may be included, if relevant. The possible values are:
| Constant | Numerical value | Description |
| -------------------------------------------------------- | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `NodeFilter.SHOW_ALL` | `4294967295` (that is the max value of `unsigned long`) | Shows all nodes. |
| `NodeFilter.SHOW_ATTRIBUTE` {{deprecated_inline}} | `2` | Shows attribute {{ domxref("Attr") }} nodes. This is meaningful only when creating a {{ domxref("TreeWalker") }} with an {{ domxref("Attr") }} node as its root. In this case, it means that the attribute node will appear in the first position of the iteration or traversal. Since attributes are never children of other nodes, they do not appear when traversing over the document tree. |
| `NodeFilter.SHOW_CDATA_SECTION` {{deprecated_inline}} | `8` | Shows {{ domxref("CDATASection") }} nodes. |
| `NodeFilter.SHOW_COMMENT` | `128` | Shows {{ domxref("Comment") }} nodes. |
| `NodeFilter.SHOW_DOCUMENT` | `256` | Shows {{ domxref("Document") }} nodes. |
| `NodeFilter.SHOW_DOCUMENT_FRAGMENT` | `1024` | Shows {{ domxref("DocumentFragment") }} nodes. |
| `NodeFilter.SHOW_DOCUMENT_TYPE` | `512` | Shows {{ domxref("DocumentType") }} nodes. |
| `NodeFilter.SHOW_ELEMENT` | `1` | Shows {{ domxref("Element") }} nodes. |
| `NodeFilter.SHOW_ENTITY` {{deprecated_inline}} | `32` | Legacy, no more usable. |
| `NodeFilter.SHOW_ENTITY_REFERENCE` {{deprecated_inline}} | `16` | Legacy, no more usable. |
| `NodeFilter.SHOW_NOTATION` {{deprecated_inline}} | `2048` | Legacy, no more usable. |
| `NodeFilter.SHOW_PROCESSING_INSTRUCTION` | `64` | Shows {{ domxref("ProcessingInstruction") }} nodes. |
| `NodeFilter.SHOW_TEXT` | `4` | Shows {{ domxref("Text") }} nodes. |
- {{domxref("TreeWalker.filter")}} {{ReadOnlyInline}}
- : Returns a `NodeFilter` used to select the relevant nodes.
- {{domxref("TreeWalker.currentNode")}}
- : Is the {{domxref("Node")}} on which the `TreeWalker` is currently pointing at.
## Instance methods
_This interface doesn't inherit any method._
> **Note:** in the context of a `TreeWalker`, a node is _visible_ if it exists in the logical view determined by the `whatToShow` and `filter` parameter arguments. (Whether or not the node is visible on the screen is irrelevant.)
- {{domxref("TreeWalker.parentNode()")}}
- : Moves the current {{domxref("Node")}} to the first _visible_ ancestor node in the document order, and returns the found node. It also moves the current node to this one. If no such node exists, or if it is before that the _root node_ defined at the object construction, returns `null` and the current node is not changed.
- {{domxref("TreeWalker.firstChild()")}}
- : Moves the current {{domxref("Node")}} to the first _visible_ child of the current node, and returns the found child. It also moves the current node to this child. If no such child exists, returns `null` and the current node is not changed. Note that the node returned by `firstChild()` is dependent on the value of `whatToShow` set during instantiation of the `TreeWalker` object. Assuming the following HTML tree, and if you set the `whatToShow` to `NodeFilter.SHOW_ALL` a call to `firstChild()` will return a `Text` node and not an `HTMLDivElement` object.
```html
<!DOCTYPE html>
<html lang="en">
<head><title>Demo</title>
<body>
<div id="container"></div>
</body>
</html>
```
```js
let walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ALL);
let node = walker.firstChild(); // nodeName: "#text"
```
But if we do:
```js
let walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
);
let node = walker.firstChild(); // nodeName: "DIV"
```
The same applies to `nextSibling()`, `previousSibling()`, `firstChild()` and `lastChild()`
- {{domxref("TreeWalker.lastChild()")}}
- : Moves the current {{domxref("Node")}} to the last _visible_ child of the current node, and returns the found child. It also moves the current node to this child. If no such child exists, `null` is returned and the current node is not changed.
- {{domxref("TreeWalker.previousSibling()")}}
- : Moves the current {{domxref("Node")}} to its previous sibling, if any, and returns the found sibling. If there is no such node, return `null` and the current node is not changed.
- {{domxref("TreeWalker.nextSibling()")}}
- : Moves the current {{domxref("Node")}} to its next sibling, if any, and returns the found sibling. If there is no such node, `null` is returned and the current node is not changed.
- {{domxref("TreeWalker.previousNode()")}}
- : Moves the current {{domxref("Node")}} to the previous _visible_ node in the document order, and returns the found node. It also moves the current node to this one. If no such node exists, or if it is before that the _root node_ defined at the object construction, returns `null` and the current node is not changed.
- {{domxref("TreeWalker.nextNode()")}}
- : Moves the current {{domxref("Node")}} to the next _visible_ node in the document order, and returns the found node. It also moves the current node to this one. If no such node exists, returns `null` and the current node is not changed.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The creator method: {{domxref("Document.createTreeWalker()")}}.
- Related interface: {{domxref("NodeIterator")}}.
| 0 |
data/mdn-content/files/en-us/web/api/treewalker | data/mdn-content/files/en-us/web/api/treewalker/previousnode/index.md | ---
title: "TreeWalker: previousNode() method"
short-title: previousNode()
slug: Web/API/TreeWalker/previousNode
page-type: web-api-instance-method
browser-compat: api.TreeWalker.previousNode
---
{{ APIRef("DOM") }}
The **`TreeWalker.previousNode()`** method moves the current
{{domxref("Node")}} to the previous _visible_ node in the document order, and
returns the found node. If no such node
exists, or if it is before that the _root node_ defined at the object
construction, it returns `null` and the current node is not changed.
## Syntax
```js-nolint
previousNode()
```
### Parameters
None.
### Return value
A {{domxref("Node")}} object or `null`.
## Examples
```js
const treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
{
acceptNode(node) {
return NodeFilter.FILTER_ACCEPT;
},
},
false,
);
const node = treeWalker.previousNode(); // returns null as there is no parent
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("TreeWalker")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/treewalker | data/mdn-content/files/en-us/web/api/treewalker/whattoshow/index.md | ---
title: "TreeWalker: whatToShow property"
short-title: whatToShow
slug: Web/API/TreeWalker/whatToShow
page-type: web-api-instance-property
browser-compat: api.TreeWalker.whatToShow
---
{{ APIRef("DOM") }}
The **`TreeWalker.whatToShow`** read-only property returns a
bitmask that indicates the types of
[nodes](/en-US/docs/Web/API/Node) to show. Non-matching nodes are skipped, but their
children may be included, if relevant. The possible values are:
<table class="no-markdown">
<thead>
<tr>
<th>Constant</th>
<th>Numerical value</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>NodeFilter.SHOW_ALL</code></td>
<td>
<code>4294967295</code> (that is the max value of <code>unsigned long</code>)
</td>
<td>Shows all nodes.</td>
</tr>
<tr>
<td>
<code>NodeFilter.SHOW_ATTRIBUTE</code> {{deprecated_inline}}
</td>
<td><code>2</code></td>
<td>
Shows attribute {{ domxref("Attr") }} nodes. This is meaningful
only when creating a {{ domxref("TreeWalker") }} with an
{{ domxref("Attr") }} node as its root; in this case, it means
that the attribute node will appear in the first position of the
iteration or traversal. Since attributes are never children of other
nodes, they do not appear when traversing over the document tree.
</td>
</tr>
<tr>
<td>
<code>NodeFilter.SHOW_CDATA_SECTION</code> {{deprecated_inline}}
</td>
<td><code>8</code></td>
<td>Shows {{ domxref("CDATASection") }} nodes.</td>
</tr>
<tr>
<td><code>NodeFilter.SHOW_COMMENT</code></td>
<td><code>128</code></td>
<td>Shows {{ domxref("Comment") }} nodes.</td>
</tr>
<tr>
<td><code>NodeFilter.SHOW_DOCUMENT</code></td>
<td><code>256</code></td>
<td>Shows {{ domxref("Document") }} nodes.</td>
</tr>
<tr>
<td><code>NodeFilter.SHOW_DOCUMENT_FRAGMENT</code></td>
<td><code>1024</code></td>
<td>Shows {{ domxref("DocumentFragment") }} nodes.</td>
</tr>
<tr>
<td><code>NodeFilter.SHOW_DOCUMENT_TYPE</code></td>
<td><code>512</code></td>
<td>Shows {{ domxref("DocumentType") }} nodes.</td>
</tr>
<tr>
<td><code>NodeFilter.SHOW_ELEMENT</code></td>
<td><code>1</code></td>
<td>Shows {{ domxref("Element") }} nodes.</td>
</tr>
<tr>
<td><code>NodeFilter.SHOW_ENTITY</code> {{deprecated_inline}}</td>
<td><code>32</code></td>
<td>Legacy, no more used.</td>
</tr>
<tr>
<td>
<code>NodeFilter.SHOW_ENTITY_REFERENCE</code>
{{deprecated_inline}}
</td>
<td><code>16</code></td>
<td>Legacy, no more used.</td>
</tr>
<tr>
<td>
<code>NodeFilter.SHOW_NOTATION</code> {{deprecated_inline}}
</td>
<td><code>2048</code></td>
<td>Legacy, no more used.</td>
</tr>
<tr>
<td><code>NodeFilter.SHOW_PROCESSING_INSTRUCTION</code></td>
<td><code>64</code></td>
<td>Shows {{ domxref("ProcessingInstruction") }} nodes.</td>
</tr>
<tr>
<td><code>NodeFilter.SHOW_TEXT</code></td>
<td><code>4</code></td>
<td>Shows {{ domxref("Text") }} nodes.</td>
</tr>
</tbody>
</table>
## Value
A bitmask.
## Examples
```js
const treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT + NodeFilter.SHOW_COMMENT + NodeFilter.SHOW_TEXT,
{ acceptNode: (node) => NodeFilter.FILTER_ACCEPT },
false,
);
if (
treeWalker.whatToShow === NodeFilter.SHOW_ALL ||
treeWalker.whatToShow % (NodeFilter.SHOW_COMMENT * 2) >=
NodeFilter.SHOW_COMMENT
) {
// treeWalker will show comments
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("TreeWalker")}} interface.
| 0 |
data/mdn-content/files/en-us/web/api/treewalker | data/mdn-content/files/en-us/web/api/treewalker/nextnode/index.md | ---
title: "TreeWalker: nextNode() method"
short-title: nextNode()
slug: Web/API/TreeWalker/nextNode
page-type: web-api-instance-method
browser-compat: api.TreeWalker.nextNode
---
{{ APIRef("DOM") }}
The **`TreeWalker.nextNode()`** method moves the current
{{domxref("Node")}} to the next _visible_ node in the document order, and returns
the found node. If no such node exists, it returns `null` and the current node is not changed.
## Syntax
```js-nolint
nextNode()
```
### Parameters
None.
### Return value
A {{domxref("Node")}} object or `null`.
## Examples
```js
const treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
{
acceptNode(node) {
return NodeFilter.FILTER_ACCEPT;
},
},
false,
);
const node = treeWalker.nextNode(); // returns the first child of root, as it is the next node in document order
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("TreeWalker")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/treewalker | data/mdn-content/files/en-us/web/api/treewalker/nextsibling/index.md | ---
title: "TreeWalker: nextSibling() method"
short-title: nextSibling()
slug: Web/API/TreeWalker/nextSibling
page-type: web-api-instance-method
browser-compat: api.TreeWalker.nextSibling
---
{{ APIRef("DOM") }}
The **`TreeWalker.nextSibling()`** method moves the current
{{domxref("Node")}} to its next sibling, if any, and returns the found sibling. If there
is no such node, it returns `null` and the current node is not changed.
## Syntax
```js-nolint
nextSibling()
```
### Parameters
None.
### Return value
A {{domxref("Node")}} object or `null`.
## Examples
```js
const treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
{
acceptNode(node) {
return NodeFilter.FILTER_ACCEPT;
},
},
false,
);
treeWalker.firstChild();
const node = treeWalker.nextSibling(); // returns null if the first child of the root element has no sibling
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("TreeWalker")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/treewalker | data/mdn-content/files/en-us/web/api/treewalker/lastchild/index.md | ---
title: "TreeWalker: lastChild() method"
short-title: lastChild()
slug: Web/API/TreeWalker/lastChild
page-type: web-api-instance-method
browser-compat: api.TreeWalker.lastChild
---
{{ APIRef("DOM") }}
The **`TreeWalker.lastChild()`** method moves the current
{{domxref("Node")}} to the last _visible_ child of the current node, and returns
the found child. If no such child exists, it returns `null` and the current node is not changed.
## Syntax
```js-nolint
lastChild()
```
### Parameters
None.
### Return value
A {{domxref("Node")}} object or `null`.
## Examples
```js
const treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
{
acceptNode(node) {
return NodeFilter.FILTER_ACCEPT;
},
},
);
const node = treeWalker.lastChild(); // returns the last visible child of the root element
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("TreeWalker")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/treewalker | data/mdn-content/files/en-us/web/api/treewalker/previoussibling/index.md | ---
title: "TreeWalker: previousSibling() method"
short-title: previousSibling()
slug: Web/API/TreeWalker/previousSibling
page-type: web-api-instance-method
browser-compat: api.TreeWalker.previousSibling
---
{{ APIRef("DOM") }}
The **`TreeWalker.previousSibling()`** method moves the current
{{domxref("Node")}} to its previous sibling, if any, and returns the found sibling. If
there is no such node, it returns `null` and the current node is not changed.
## Syntax
```js-nolint
previousSibling()
```
### Parameters
None.
### Return value
A {{domxref("Node")}} object or `null`.
## Examples
```js
const treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
{
acceptNode(node) {
return NodeFilter.FILTER_ACCEPT;
},
},
false,
);
const node = treeWalker.previousSibling(); // returns null as there is no previous sibling
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("TreeWalker")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/treewalker | data/mdn-content/files/en-us/web/api/treewalker/root/index.md | ---
title: "TreeWalker: root property"
short-title: root
slug: Web/API/TreeWalker/root
page-type: web-api-instance-property
browser-compat: api.TreeWalker.root
---
{{ APIRef("DOM") }}
The **`TreeWalker.root`** read-only property returns the node
that is the root of what the TreeWalker traverses.
## Value
A {{domxref("Node")}} object.
## Examples
```js
const treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
{
acceptNode(node) {
return NodeFilter.FILTER_ACCEPT;
},
},
false,
);
root = treeWalker.root; // document.body in this case
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("TreeWalker")}} interface.
| 0 |
data/mdn-content/files/en-us/web/api/treewalker | data/mdn-content/files/en-us/web/api/treewalker/parentnode/index.md | ---
title: "TreeWalker: parentNode() method"
short-title: parentNode()
slug: Web/API/TreeWalker/parentNode
page-type: web-api-instance-method
browser-compat: api.TreeWalker.parentNode
---
{{ APIRef("DOM") }}
The **`TreeWalker.parentNode()`** method moves the current
{{domxref("Node")}} to the first _visible_ ancestor node in the document order,
and returns the found node. If no such node exists, or if it is above the
`TreeWalker`'s _root node_, it returns `null` and the current
node is not changed.
## Syntax
```js-nolint
parentNode()
```
### Parameters
None.
### Return value
A {{domxref("Node")}} object or `null`.
## Examples
```js
const treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
{
acceptNode(node) {
return NodeFilter.FILTER_ACCEPT;
},
},
false,
);
const node = treeWalker.parentNode(); // returns null as there is no parent
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("TreeWalker")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/treewalker | data/mdn-content/files/en-us/web/api/treewalker/firstchild/index.md | ---
title: "TreeWalker: firstChild() method"
short-title: firstChild()
slug: Web/API/TreeWalker/firstChild
page-type: web-api-instance-method
browser-compat: api.TreeWalker.firstChild
---
{{ APIRef("DOM") }}
The **`TreeWalker.firstChild()`** method moves the current
{{domxref("Node")}} to the first _visible_ child of the current node, and returns
the found child. If no such child exists, it returns `null` and the current node is not changed.
## Syntax
```js-nolint
firstChild()
```
### Parameters
None.
### Return value
A {{domxref("Node")}} object or `null`.
## Examples
```js
const treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
{
acceptNode(node) {
return NodeFilter.FILTER_ACCEPT;
},
},
false,
);
const node = treeWalker.firstChild(); // returns the first child of the root element, or null if none
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("TreeWalker")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/treewalker | data/mdn-content/files/en-us/web/api/treewalker/currentnode/index.md | ---
title: "TreeWalker: currentNode property"
short-title: currentNode
slug: Web/API/TreeWalker/currentNode
page-type: web-api-instance-property
browser-compat: api.TreeWalker.currentNode
---
{{ APIRef("DOM") }}
The **`TreeWalker.currentNode`** property represents the
{{domxref("Node")}} which the {{domxref("TreeWalker")}} is currently pointing at.
## Value
A {{domxref("Node")}}.
## Examples
```js
const treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
{
acceptNode(node) {
return NodeFilter.FILTER_ACCEPT;
},
},
);
root = treeWalker.currentNode; // the root element as it is the first element!
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("TreeWalker")}} interface.
| 0 |
data/mdn-content/files/en-us/web/api/treewalker | data/mdn-content/files/en-us/web/api/treewalker/filter/index.md | ---
title: "TreeWalker: filter property"
short-title: filter
slug: Web/API/TreeWalker/filter
page-type: web-api-instance-property
browser-compat: api.TreeWalker.filter
---
{{ APIRef("DOM") }}
The **`TreeWalker.filter`** read-only property returns a
`NodeFilter` that is the filtering object associated with the
{{domxref("TreeWalker")}}.
When creating the `TreeWalker`, the filter object is passed in as the third
parameter, and its method `acceptNode()` is called on every
single node to determine whether or not to accept it.
## Value
A `NodeFilter` object.
## Examples
```js
const treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
{
acceptNode(node) {
return NodeFilter.FILTER_ACCEPT;
},
},
);
nodeFilter = treeWalker.filter; // document.body in this case
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("TreeWalker")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/navigationcurrententrychangeevent/index.md | ---
title: NavigationCurrentEntryChangeEvent
slug: Web/API/NavigationCurrentEntryChangeEvent
page-type: web-api-interface
status:
- experimental
browser-compat: api.NavigationCurrentEntryChangeEvent
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`NavigationCurrentEntryChangeEvent`** interface of the {{domxref("Navigation API", "Navigation API", "", "nocode")}} is the event object for the {{domxref("Navigation/currententrychange_event", "currententrychange")}} event, which fires when the {{domxref("Navigation.currentEntry")}} has changed.
This event will fire for same-document navigations (e.g. {{domxref("Navigation.back", "back()")}} or {{domxref("Navigation.traverseTo", "traverseTo()")}}), replacements (i.e. a {{domxref("Navigation.navigate", "navigate()")}} call with `history` set to `replace`), or other calls that change the entry's state (e.g. {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}}, or the {{domxref("History API", "History API", "", "nocode")}}'s {{domxref("History.replaceState()")}}).
This event fires after the navigation is committed, meaning that the visible URL has changed and the {{domxref("NavigationHistoryEntry")}} update has occurred. It is useful for migrating from usage of older API features like the {{domxref("Window/hashchange_event", "hashchange")}} or {{domxref("Window/popstate_event", "popstate")}} events.
{{InheritanceDiagram}}
## Constructor
- {{domxref("NavigationCurrentEntryChangeEvent.NavigationCurrentEntryChangeEvent", "NavigationCurrentEntryChangeEvent()")}} {{Experimental_Inline}}
- : Creates a new `NavigationCurrentEntryChangeEvent` object instance.
## Instance properties
_Inherits properties from its parent, {{DOMxRef("Event")}}._
- {{domxref("NavigationCurrentEntryChangeEvent.from", "from")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the {{domxref("NavigationHistoryEntry")}} that was navigated from.
- {{domxref("NavigationCurrentEntryChangeEvent.navigationType", "navigationType")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the type of the navigation that resulted in the change.
## Examples
Navigation data reporting:
```js
navigation.addEventListener("currententrychange", () => {
const data = navigation.currentEntry.getState();
submitAnalyticsData(data.analytics);
});
```
Setting up a per-entry event:
```js
navigation.addEventListener("currententrychange", () => {
navigation.currentEntry.addEventListener("dispose", genericDisposeHandler);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)
- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/)
| 0 |
data/mdn-content/files/en-us/web/api/navigationcurrententrychangeevent | data/mdn-content/files/en-us/web/api/navigationcurrententrychangeevent/from/index.md | ---
title: "NavigationCurrentEntryChangeEvent: from property"
short-title: from
slug: Web/API/NavigationCurrentEntryChangeEvent/from
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NavigationCurrentEntryChangeEvent.from
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`from`** read-only property of the {{domxref("NavigationCurrentEntryChangeEvent")}} interface returns the {{domxref("NavigationHistoryEntry")}} that was navigated from.
## Value
A {{domxref("NavigationHistoryEntry")}} object.
## Examples
```js
navigation.addEventListener("currententrychange", (event) => {
console.log(event.from);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)
- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/)
| 0 |
data/mdn-content/files/en-us/web/api/navigationcurrententrychangeevent | data/mdn-content/files/en-us/web/api/navigationcurrententrychangeevent/navigationtype/index.md | ---
title: "NavigationCurrentEntryChangeEvent: navigationType property"
short-title: navigationType
slug: Web/API/NavigationCurrentEntryChangeEvent/navigationType
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NavigationCurrentEntryChangeEvent.navigationType
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`navigationType`** read-only property of the {{domxref("NavigationCurrentEntryChangeEvent")}} interface returns the type of the navigation that resulted in the change. The property may be `null` if the change occurs due to {{domxref("Navigation.updateCurrentEntry()")}}.
## Value
An enumerated value representing the type of navigation.
The possible values are:
- `push`: A new location is navigated to, causing a new entry to be pushed onto the history list.
- `reload`: The {{domxref("Navigation.currentEntry")}} is reloaded.
- `replace`: The {{domxref("Navigation.currentEntry")}} is replaced with a new history entry. This new entry will reuse the same {{domxref("NavigationHistoryEntry.key", "key")}}, but be assigned a different {{domxref("NavigationHistoryEntry.id", "id")}}.
- `traverse`: The browser navigates from one existing history entry to another existing history entry.
## Examples
```js
navigation.addEventListener("currententrychange", (event) => {
console.log(event.navigationType);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)
- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/)
| 0 |
data/mdn-content/files/en-us/web/api/navigationcurrententrychangeevent | data/mdn-content/files/en-us/web/api/navigationcurrententrychangeevent/navigationcurrententrychangeevent/index.md | ---
title: "NavigationCurrentEntryChangeEvent: NavigationCurrentEntryChangeEvent() constructor"
short-title: NavigationCurrentEntryChangeEvent()
slug: Web/API/NavigationCurrentEntryChangeEvent/NavigationCurrentEntryChangeEvent
page-type: web-api-constructor
status:
- experimental
browser-compat: api.NavigationCurrentEntryChangeEvent.NavigationCurrentEntryChangeEvent
---
{{APIRef("Navigation API")}}{{SeeCompatTable}}
The **`NavigationCurrentEntryChangeEvent()`** constructor creates a new {{domxref("NavigationCurrentEntryChangeEvent")}} object.
## Syntax
```js-nolint
new NavigationCurrentEntryChangeEvent(type, init)
```
### Parameters
- `type`
- : A string representing the type of event. In the case of `NavigationCurrentEntryChangeEvent` this is always `event`.
- `init`
- : An object containing the following properties:
- `destination`
- : A {{domxref("NavigationHistoryEntry")}} object representing the location being navigated to.
- `navigationType` {{optional_inline}}
- : The type of the navigation that resulted in the change. Possible values are `push`, `reload`, `replace`, and `traverse`. Defaults to `null`.
## Examples
A developer would not use this constructor manually. A new `NavigationCurrentEntryChangeEvent` object is constructed when a handler is invoked as a result of the {{domxref("Navigation.currententrychange_event", "currententrychange")}} event firing.
```js
navigation.addEventListener("currententrychange", (event) => {
console.log(event.navigationType);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
- [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)
- Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/bluetoothremotegattserver/index.md | ---
title: BluetoothRemoteGATTServer
slug: Web/API/BluetoothRemoteGATTServer
page-type: web-api-interface
status:
- experimental
browser-compat: api.BluetoothRemoteGATTServer
---
{{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`BluetoothRemoteGATTServer`** interface of the [Web Bluetooth API](/en-US/docs/Web/API/Web_Bluetooth_API) represents a GATT
Server on a remote device.
## Instance properties
- {{DOMxRef("BluetoothRemoteGATTServer.connected")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A boolean value that returns true while this script execution environment is
connected to `this.device`. It can be false while the user agent is
physically connected.
- {{DOMxRef("BluetoothRemoteGATTServer.device")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A reference to the {{DOMxRef("BluetoothDevice")}} running the server.
## Instance methods
- {{DOMxRef("BluetoothRemoteGATTServer.connect()")}} {{Experimental_Inline}}
- : Causes the script execution environment to connect to `this.device`.
- {{DOMxRef("BluetoothRemoteGATTServer.disconnect()")}} {{Experimental_Inline}}
- : Causes the script execution environment to disconnect from `this.device`.
- {{DOMxRef("BluetoothRemoteGATTServer.getPrimaryService()")}} {{Experimental_Inline}}
- : Returns a promise to the primary {{DOMxRef("BluetoothRemoteGATTService")}} offered by the
Bluetooth device for a specified `BluetoothServiceUUID`.
- {{DOMxRef("BluetoothRemoteGATTServer.getPrimaryServices()")}} {{Experimental_Inline}}
- : Returns a promise to a list of primary {{DOMxRef("BluetoothRemoteGATTService")}} objects
offered by the Bluetooth device for a specified `BluetoothServiceUUID`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
{{APIRef("Web Bluetooth")}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothremotegattserver | data/mdn-content/files/en-us/web/api/bluetoothremotegattserver/connect/index.md | ---
title: "BluetoothRemoteGATTServer: connect() method"
short-title: connect()
slug: Web/API/BluetoothRemoteGATTServer/connect
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.BluetoothRemoteGATTServer.connect
---
{{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The
**`BluetoothRemoteGATTServer.connect()`** method causes the
script execution environment to connect to `this.device`.
## Syntax
```js-nolint
connect()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that resolves to a {{domxref("BluetoothRemoteGATTServer")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
{{APIRef("Web Bluetooth")}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothremotegattserver | data/mdn-content/files/en-us/web/api/bluetoothremotegattserver/getprimaryservice/index.md | ---
title: "BluetoothRemoteGATTServer: getPrimaryService() method"
short-title: getPrimaryService()
slug: Web/API/BluetoothRemoteGATTServer/getPrimaryService
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.BluetoothRemoteGATTServer.getPrimaryService
---
{{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`BluetoothRemoteGATTServer.getPrimaryService()`** method
returns a promise to the primary {{domxref("BluetoothRemoteGATTService")}} offered by the
Bluetooth device for a specified bluetooth service UUID.
## Syntax
```js-nolint
getPrimaryService(bluetoothServiceUUID)
```
### Parameters
- `bluetoothServiceUUID`
- : A Bluetooth service universally unique identifier for a specified device, that is either a 128-bit UUID, a 16-bit or 32-bit UUID alias, or a string from the list of [GATT assigned services](https://github.com/WebBluetoothCG/registries/blob/master/gatt_assigned_services.txt) keys.
### Return value
A {{jsxref("Promise")}} that resolves to a {{domxref("BluetoothRemoteGATTService")}} object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
{{APIRef("Web Bluetooth")}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothremotegattserver | data/mdn-content/files/en-us/web/api/bluetoothremotegattserver/device/index.md | ---
title: "BluetoothRemoteGATTServer: device property"
short-title: device
slug: Web/API/BluetoothRemoteGATTServer/device
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.BluetoothRemoteGATTServer.device
---
{{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`BluetoothRemoteGATTServer.device`** read-only property
returns a reference to the {{domxref("BluetoothDevice")}} running the server.
## Value
A reference to the {{domxref("BluetoothDevice")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
{{APIRef("Web Bluetooth")}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothremotegattserver | data/mdn-content/files/en-us/web/api/bluetoothremotegattserver/getprimaryservices/index.md | ---
title: "BluetoothRemoteGATTServer: getPrimaryServices() method"
short-title: getPrimaryServices()
slug: Web/API/BluetoothRemoteGATTServer/getPrimaryServices
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.BluetoothRemoteGATTServer.getPrimaryServices
---
{{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **BluetoothRemoteGATTServer.getPrimaryServices()** method returns a
promise to a list of primary {{domxref("BluetoothRemoteGATTService")}} objects offered by the
Bluetooth device for a specified `BluetoothServiceUUID`.
## Syntax
```js-nolint
getPrimaryServices(bluetoothServiceUUID)
```
### Parameters
- `bluetoothServiceUUID`
- : A Bluetooth service universally unique identifier for a specified device.
### Return value
A {{jsxref("Promise")}} that resolves to a list of {{domxref("BluetoothRemoteGATTService")}}
objects.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
{{APIRef("Web Bluetooth")}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothremotegattserver | data/mdn-content/files/en-us/web/api/bluetoothremotegattserver/disconnect/index.md | ---
title: "BluetoothRemoteGATTServer: disconnect() method"
short-title: disconnect()
slug: Web/API/BluetoothRemoteGATTServer/disconnect
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.BluetoothRemoteGATTServer.disconnect
---
{{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`BluetoothRemoteGATTServer.disconnect()`** method causes
the script execution environment to disconnect from `this.device`.
## Syntax
```js-nolint
disconnect()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
{{APIRef("Web Bluetooth")}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothremotegattserver | data/mdn-content/files/en-us/web/api/bluetoothremotegattserver/connected/index.md | ---
title: "BluetoothRemoteGATTServer: connected property"
short-title: connected
slug: Web/API/BluetoothRemoteGATTServer/connected
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.BluetoothRemoteGATTServer.connected
---
{{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`BluetoothRemoteGATTServer.connected`** read-only
property returns a boolean value that returns true while this script execution
environment is connected to `this.device`. It can be false while the user
agent is physically connected.
## Value
A `boolean`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
{{APIRef("Web Bluetooth")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/merchantvalidationevent/index.md | ---
title: MerchantValidationEvent
slug: Web/API/MerchantValidationEvent
page-type: web-api-interface
status:
- deprecated
browser-compat: api.MerchantValidationEvent
---
{{APIRef("Payment Request API")}}{{Deprecated_Header}}{{SecureContext_Header}}
The **`MerchantValidationEvent`** interface of the [Payment Request API](/en-US/docs/Web/API/Payment_Request_API) enables a merchant to verify themselves as allowed to use a particular payment handler.
Learn more about [merchant validation](/en-US/docs/Web/API/Payment_Request_API/Concepts#merchant_validation).
## Constructor
- {{domxref("MerchantValidationEvent.MerchantValidationEvent()","MerchantValidationEvent()")}} {{Deprecated_Inline}}
- : Creates a new `MerchantValidationEvent` object describing a {{domxref("PaymentRequest.merchantvalidation_event", "merchantvalidation")}} event that will be sent to the payment handler to request that it validate the merchant.
## Instance properties
- {{domxref("MerchantValidationEvent.methodName")}} {{Deprecated_Inline}}
- : A string providing a unique payment method identifier for the payment handler that's requiring validation. This may be either one of the standard payment method identifier strings or a URL that both identifies and handles requests for the payment handler, such as `https://apple.com/apple-pay`.
- {{domxref("MerchantValidationEvent.validationURL")}} {{Deprecated_Inline}}
- : A string specifying a URL from which the site or app can fetch payment handler specific validation information. Once this data is retrieved, the data (or a promise resolving to the validation data) should be passed into {{domxref("MerchantValidationEvent.complete", "complete()")}} to validate that the payment request is coming from an authorized merchant.
## Instance methods
- {{domxref("MerchantValidationEvent.complete()")}} {{Deprecated_Inline}}
- : Pass the data retrieved from the URL specified by {{domxref("MerchantValidationEvent.validationURL", "validationURL")}} into `complete()` to complete the validation process for the {{domxref("PaymentRequest")}}.
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/merchantvalidationevent | data/mdn-content/files/en-us/web/api/merchantvalidationevent/methodname/index.md | ---
title: "MerchantValidationEvent: methodName property"
short-title: methodName
slug: Web/API/MerchantValidationEvent/methodName
page-type: web-api-instance-property
status:
- deprecated
browser-compat: api.MerchantValidationEvent.methodName
---
{{APIRef("Payment Request API")}}{{Deprecated_Header}}{{SecureContext_Header}}
The {{domxref("MerchantValidationEvent")}} property
**`methodName`** is a read-only value which returns a string
indicating the payment method identifier which represents the payment handler that
requires merchant validation.
## Value
A read-only string which uniquely identifies the payment handler
which is requesting merchant validation. See
[Merchant validation](/en-US/docs/Web/API/Payment_Request_API/Concepts#merchant_validation) for more information on the process.
## Browser compatibility
{{Compat}}
## See also
- [Payment Request API](/en-US/docs/Web/API/Payment_Request_API)
- [Using the Payment Request API](/en-US/docs/Web/API/Payment_Request_API/Using_the_Payment_Request_API)
- [Payment processing concepts](/en-US/docs/Web/API/Payment_Request_API/Concepts)
| 0 |
data/mdn-content/files/en-us/web/api/merchantvalidationevent | data/mdn-content/files/en-us/web/api/merchantvalidationevent/validationurl/index.md | ---
title: "MerchantValidationEvent: validationURL property"
short-title: validationURL
slug: Web/API/MerchantValidationEvent/validationURL
page-type: web-api-instance-property
status:
- deprecated
browser-compat: api.MerchantValidationEvent.validationURL
---
{{APIRef("Payment Request API")}}{{Deprecated_Header}}{{SecureContext_Header}}
The {{domxref("MerchantValidationEvent")}} property
**`validationURL`** is a read-only string value providing the
URL from which to fetch the payment handler-specific data needed to validate the
merchant.
This data should be passed into the {{domxref("MerchantValidationEvent.complete",
"complete()")}} method to let the user agent complete the transaction.
## Value
A read-only string giving the URL from which to load payment handler
specific data needed to complete the merchant verification process. Once this has been
loaded, it should be passed into {{domxref("MerchantValidationEvent.complete",
"complete()")}}, either directly or using a promise.
See [Merchant validation](/en-US/docs/Web/API/Payment_Request_API/Concepts#merchant_validation) to learn more about the process.
## Browser compatibility
{{Compat}}
## See also
- [Payment Request API](/en-US/docs/Web/API/Payment_Request_API)
- [Using the Payment Request API](/en-US/docs/Web/API/Payment_Request_API/Using_the_Payment_Request_API)
- [Payment processing concepts](/en-US/docs/Web/API/Payment_Request_API/Concepts)
| 0 |
data/mdn-content/files/en-us/web/api/merchantvalidationevent | data/mdn-content/files/en-us/web/api/merchantvalidationevent/complete/index.md | ---
title: "MerchantValidationEvent: complete() method"
short-title: complete()
slug: Web/API/MerchantValidationEvent/complete
page-type: web-api-instance-method
status:
- deprecated
browser-compat: api.MerchantValidationEvent.complete
---
{{APIRef("Payment Request API")}}{{Deprecated_Header}}{{SecureContext_Header}}
The {{domxref("MerchantValidationEvent")}} method **`complete()`** takes merchant-specific information previously received from the {{domxref("MerchantValidationEvent.validationURL", "validationURL")}} and uses it to validate the merchant.
All you have to do is call `complete()` from your handler for the {{domxref("PaymentRequest.merchantvalidation_event", "merchantvalidation")}} event, passing in the data fetched from the `validationURL`.
## Syntax
```js-nolint
complete(validationData)
complete(merchantSessionPromise)
```
### Parameters
- `validationData` or `merchantSessionPromise`
- : An object containing the data needed to complete the merchant validation process, or a {{jsxref("Promise")}} which resolves to the validation data.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
This exception may be passed into the rejection handler for the promise:
- `InvalidStateError` {{domxref("DOMException")}}
- : Returned if the event did not come directly from the user agent, but was instead dispatched by other code. Another payment request is currently being processed, the current payment request is not currently being displayed to the user, or payment information is currently being updated.
## Examples
In this example, we see the client-side code needed to support merchant validation for a payment request called `payRequest`:
```js
payRequest.onmerchantvalidation = (event) => {
const validationDataPromise = getValidationData(event.validationURL);
event.complete(validationDataPromise);
};
function getValidationData(url) {
// Retrieve the validation data from the URL
// …
}
```
This code sets up a handler for the {{domxref("PaymentRequest.merchantvalidation_event", "merchantvalidation")}} event. The event handler calls a function, `getValidationData()`, which retrieves the data from the validation URL, then passes that data (or a promise to deliver the data) into `complete()`.
## Browser compatibility
{{Compat}}
## See also
- [Payment Request API](/en-US/docs/Web/API/Payment_Request_API)
- [Using the Payment Request API](/en-US/docs/Web/API/Payment_Request_API/Using_the_Payment_Request_API)
- [Payment processing concepts](/en-US/docs/Web/API/Payment_Request_API/Concepts)
| 0 |
data/mdn-content/files/en-us/web/api/merchantvalidationevent | data/mdn-content/files/en-us/web/api/merchantvalidationevent/merchantvalidationevent/index.md | ---
title: "MerchantValidationEvent: MerchantValidationEvent() constructor"
short-title: MerchantValidationEvent()
slug: Web/API/MerchantValidationEvent/MerchantValidationEvent
page-type: web-api-constructor
status:
- deprecated
browser-compat: api.MerchantValidationEvent.MerchantValidationEvent
---
{{deprecated_header}}{{securecontext_header}}{{APIRef}}
The **`MerchantValidationEvent()`** constructor creates a new {{domxref("MerchantValidationEvent")}} object. You should not have to create these events yourself; instead, just handle the {{domxref("PaymentRequest.merchantvalidation_event", "merchantvalidation")}} event.
## Syntax
```js-nolint
new MerchantValidationEvent(type)
new MerchantValidationEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers always set it to `merchantvalidation`.
- `options` {{optional_inline}}
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties:
- `methodName` {{optional_inline}}
- : A string containing the payment method identifier for the payment handler being used. This is an empty string by default.
- `validationURL` {{optional_inline}}
- : The URL from which to retrieve payment handler specific verification information used to validate the merchant. This is an empty string by default.
### Return value
A new {{domxref("MerchantValidationEvent")}} object providing the information
that needs to be delivered to the client-side code to present to the {{Glossary("user agent")}} by calling {{domxref("MerchantValidationEvent.complete", "complete()")}}.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the string specified as `validationURL` could not be parsed as a URL.
- {{jsxref("RangeError")}}
- : Thrown if the specified `methodName` does not correspond to a known and supported merchant or is not a well-formed standard payment method identifier.
## Specifications
_This feature is deprecated and is not part of any specification._
## Browser compatibility
{{Compat}}
## See also
- [Payment Request API](/en-US/docs/Web/API/Payment_Request_API)
- [Using the Payment Request API](/en-US/docs/Web/API/Payment_Request_API/Using_the_Payment_Request_API)
- [Payment processing concepts](/en-US/docs/Web/API/Payment_Request_API/Concepts)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/remote_playback_api/index.md | ---
title: Remote Playback API
slug: Web/API/Remote_Playback_API
page-type: web-api-overview
browser-compat: api.RemotePlayback
spec-urls: https://w3c.github.io/remote-playback/
---
{{DefaultAPISidebar("Remote Playback API")}}
The Remote Playback API extends the {{domxref("HTMLMediaElement")}} to enable the control of media played on a remote device.
## Concepts and Usage
Remote playback devices are connected devices such as TVs, projectors, or speakers. The API takes into account wired devices connected via HDMI or DVI, and wireless devices, for example Chromecast or AirPlay.
The API enables a page, which has an media element such as a video or audio file, to initiate and control playback of that media on a connected remote device. For example, playing a video on a connected TV.
> **Note:** Safari for iOS has some APIs which enable remote playback on AirPlay. Details of these can be found in [the Safari 9.0 release notes](https://developer.apple.com/library/archive/releasenotes/General/WhatsNewInSafari/Articles/Safari_9_0.html#//apple_ref/doc/uid/TP40014305-CH9-SW16).
>
> Android versions of Firefox and Chrome also contain some remote playback features. These devices will show a Cast button if there is a Cast device available in the local network.
## Interfaces
- {{domxref("RemotePlayback")}}
- : Allows the page to detect availability of remote playback devices, then connect to and control playing on these devices.
### Extensions to other interfaces
- {{domxref("HTMLMediaElement.disableRemotePlayback")}}
- : A boolean that sets or returns the remote playback state, indicating whether the media element is allowed to have a remote playback UI.
- {{domxref("HTMLMediaElement.remote")}} {{ReadOnlyInline}}
- : Return a {{domxref("RemotePlayback")}} object instance associated with the media element.
## Examples
The following example demonstrates a player with custom controls that supports remote playback. Initially the button used to select a device is hidden.
```html
<video id="videoElement" src="https://example.org/media.ext">
<button id="deviceBtn" style="display: none;">Pick device</button>
</video>
```
The {{domxref("RemotePlayback.watchAvailability()")}} method watches for available remote playback devices. If a device is available, use the callback to show the button.
```js
const deviceBtn = document.getElementById("deviceBtn");
const videoElem = document.getElementById("videoElement");
function availabilityCallback(available) {
// Show or hide the device picker button depending on device availability.
deviceBtn.style.display = available ? "inline" : "none";
}
videoElem.remote.watchAvailability(availabilityCallback).catch(() => {
/* If the device cannot continuously watch available,
show the button to allow the user to try to prompt for a connection.*/
deviceBtn.style.display = "inline";
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmltitleelement/index.md | ---
title: HTMLTitleElement
slug: Web/API/HTMLTitleElement
page-type: web-api-interface
browser-compat: api.HTMLTitleElement
---
{{ APIRef("HTML DOM") }}
The **`HTMLTitleElement`** interface is implemented by a document's {{ HTMLElement( "title" )}}. This element inherits all of the properties and methods of the {{domxref("HTMLElement")}} interface.
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its parent, {{domxref("HTMLElement")}}._
- {{domxref("HTMLTitleElement.text")}}
- : A string representing the text of the document's title.
## Instance methods
_No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}._
## Example
Do not confuse: `document.title` with `document.querySelector('title')`
The former is just a setter/getter method to set or get the inner text value of the document title, while the latter is the {{domxref("HTMLTitleElement")}} object. So you cannot write: `document.title.text = "Hello world!";`
Instead, you can simply write: `document.title = "Hello world!";` which is an equivalent to `document.querySelector('title').text = "Hello world!";`
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The HTML element implementing this interface: {{ HTMLElement("title") }}.
| 0 |
data/mdn-content/files/en-us/web/api/htmltitleelement | data/mdn-content/files/en-us/web/api/htmltitleelement/text/index.md | ---
title: "HTMLTitleElement: text property"
short-title: text
slug: Web/API/HTMLTitleElement/text
page-type: web-api-instance-property
browser-compat: api.HTMLTitleElement.text
---
{{APIRef("HTML DOM")}}
The **`text`** property of the {{domxref("HTMLTitleElement")}} interface represents the text of the document's title. Only the text part is included; tags within the element and their content are stripped and ignored.
## Value
A string.
## Examples
Consider the example below:
```html
<!doctype html>
<html lang="en-US">
<head>
<title>
Hello world! <span class="highlight">Isn't this wonderful</span> really?
</title>
</head>
<body></body>
</html>
```
```js
const title = document.querySelector("title");
console.log(title.text); // yield: "Hello world! really?"
```
As you can see, the tag `span` and its content were skipped.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/texttrack/index.md | ---
title: TextTrack
slug: Web/API/TextTrack
page-type: web-api-interface
browser-compat: api.TextTrack
---
{{APIRef("WebVTT")}}
The `TextTrack` interface—part of the API for handling WebVTT (text tracks on media presentations)—describes and controls the text track associated with a particular {{HTMLElement("track")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface also inherits properties from {{domxref("EventTarget")}}._
- {{domxref("TextTrack.activeCues")}} {{ReadOnlyInline}}
- : A {{domxref("TextTrackCueList")}} object listing the currently active set of text track cues. Track cues are active if the current playback position of the media is between the cues' start and end times. Thus, for displayed cues such as captions or subtitles, the active cues are currently being displayed.
- {{domxref("TextTrack.cues")}} {{ReadOnlyInline}}
- : A {{domxref("TextTrackCueList")}} which contains all of the track's cues.
- {{domxref("TextTrack.id")}} {{ReadOnlyInline}}
- : A string which identifies the track, if it has one. If it doesn't have an ID, then this value is an empty string (`""`). If the `TextTrack` is associated with a {{HTMLElement("track")}} element, then the track's ID matches the element's ID.
- {{domxref("TextTrack.inBandMetadataTrackDispatchType")}} {{ReadOnlyInline}}
- : Returns a string which indicates the track's in-band metadata track dispatch type.
- {{domxref("TextTrack.kind")}} {{ReadOnlyInline}}
- : Returns a string indicating what kind of text track the `TextTrack` describes. It must be one of the permitted values.
- {{domxref("TextTrack.label")}} {{ReadOnlyInline}}
- : A human-readable string which contains the text track's label, if one is present; otherwise, this is an empty string (`""`), in which case a custom label may need to be generated by your code using other attributes of the track, if the track's label needs to be exposed to the user.
- {{domxref("TextTrack.language")}} {{ReadOnlyInline}}
- : A string which specifies the text language in which the text track's contents is written. The value must adhere to the format specified in {{RFC(5646, "Tags for Identifying Languages (also known as BCP 47)")}}, just like the HTML [`lang`](/en-US/docs/Web/HTML/Global_attributes#lang) attribute. For example, this can be `"en-US"` for United States English or `"pt-BR"` for Brazilian Portuguese.
- {{domxref("TextTrack.mode")}}
- : A string specifying the track's current mode, which must be one of the permitted values. Changing this property's value changes the track's current mode to match. The default is `disabled`, unless the {{HTMLElement("track")}} element's [`default`](/en-US/docs/Web/HTML/Element/track#default) boolean attribute is set to `true` — in which case the default mode is `showing`.
## Instance methods
_This interface also inherits methods from {{domxref("EventTarget")}}._
> **Note:** The {{domxref("TextTrackCue")}} interface is an abstract class used as the parent for other cue interfaces such as {{domxref("VTTCue")}}. Therefore, when adding or removing a cue you will be passing in one of the cue types that inherit from `TextTrackCue`.
- {{domxref("TextTrack.addCue()")}}
- : Adds a cue (specified as a {{domxref("TextTrackCue")}} object) to the track's list of cues.
- {{domxref("TextTrack.removeCue()")}}
- : Removes a cue (specified as a {{domxref("TextTrackCue")}} object) from the track's list of cues.
## Events
- [`cuechange`](/en-US/docs/Web/API/TextTrack/cuechange_event)
- : Fired when cues are entered and exited. A given text cue appears when the cue is entered and disappears when the cue is exited.
Also available via the `oncuechange` property.
## Example
The following example adds a new `TextTrack` to a video, then sets it to display using {{domxref("TextTrack.mode")}}.
```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebVTT](/en-US/docs/Web/API/WebVTT_API)
- {{domxref("TextTrackCueList")}}
- {{domxref("VTTCue")}}
- {{HTMLElement("track")}}
- {{domxref("HTMLTrackElement")}}
| 0 |
data/mdn-content/files/en-us/web/api/texttrack | data/mdn-content/files/en-us/web/api/texttrack/mode/index.md | ---
title: "TextTrack: mode property"
short-title: mode
slug: Web/API/TextTrack/mode
page-type: web-api-instance-property
browser-compat: api.TextTrack.mode
---
{{APIRef("WebVTT")}}
The {{domxref("TextTrack")}} interface's
**`mode`** property is a string specifying and controlling the
text track's mode: `disabled`, `hidden`, or
`showing`. You can read this value to determine the current mode,
and you can change this value to switch modes.
Safari additionally requires the **`default`**
boolean attribute to be set to true when implementing your own video player controls in
order for the subtitles cues to be shown.
### Value
A string which indicates the track's current mode. One of:
- `disabled`
- : The text track is currently disabled. While the track's presence is exposed in the
DOM, the user agent is otherwise ignoring it. No cues are active, no events are being
fired, and the user agent won't attempt to obtain the track's cues. This is the
default value, unless the text track has the [`default`](/en-US/docs/Web/HTML/Element/track#default)
Boolean attribute is specified, in which case the default is `showing`.
- `hidden`
- : The text track is currently active but the cues aren't being displayed. If the user
agent hasn't tried to obtain the track's cues yet, it will do so soon (thereby
populating the track's {{domxref("TextTrack.cues")}} property). The user agent is
keeping a list of the active cues (in the track's {{domxref("TextTrack.activeCues",
"activeCues")}} property) and events are being fired at the corresponding times, even
though the text isn't being displayed.
- `showing`
- : The text track is currently enabled and is visible. If the track's cues list hasn't
been obtained yet, it will be soon. The {{domxref("TextTrack.activeCues",
"activeCues")}} list is being maintained and events are firing at the appropriate
times; the track's text is also being drawn appropriately based on the styling and the
track's {{domxref("TextTrack.kind", "kind")}}. This is the default value if the text
track's [`default`](/en-US/docs/Web/HTML/Element/track#default) Boolean attribute is specified.
## Usage notes
The default `mode` is `disabled`, unless the
[`default`](/en-US/docs/Web/HTML/Element/track#default) Boolean attribute is specified, in which case the
default `mode` is `showing`. When a text track is loaded in the
`disabled` state, the corresponding WebVTT file is not loaded until the state
changes to either `showing` or `hidden`. This way, the resource
fetch and memory usage are avoided unless the cues are actually needed.
However, that means that if you wish to perform any actions involving the track's cues
while handling, for example, the {{domxref("Window/load_event", "load")}} event—in order to process some aspect
of the cues upon page load—and the track mode was initially `disabled`,
you'll have to change the `mode` to either `hidden` or
`showing` in order to trigger loading of the cues.
When the mode is `showing`, text tracks are performed. The exact appearance
and manner of that performance varies depending on each text track's
{{domxref("TextTrack.kind", "kind")}}. In general:
- Tracks whose `kind` is `"subtitles"` or
`"captions"` are rendered with the cues overlaid over the top of the video.
- Tracks whose `kind` is `"descriptions"` are presented in a
non-visual form (for example, the text might be spoken to describe the action in the
video).
- Tracks whose `kind` is `"chapters"` are used by the user agent
or the website or web app to construct and present an interface for navigating the
named chapters, where each cue in the list represents a chapter in the media. The user
can then navigate to the desired chapter, which begins at the cue's start position and
ends at the cue's end position.
## Example
In this example, we configure the text track's cues so that every time a cue is
finished, the video automatically pauses playback. This is done by setting the
{{domxref("TextTrackCue.pauseonExit", "pauseOnExit")}} property on each cue to
`true`. However, to ensure that the track's cues are available, we first set
`mode` to `showing`.
```js
window.addEventListener("load", (event) => {
let trackElem = document.querySelector("track");
let track = trackElem.track;
track.mode = "showing";
for (const cue of track.cues) {
cue.pauseOnExit = true;
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebVTT](/en-US/docs/Web/API/WebVTT_API)
- {{domxref("TextTrack")}}
- {{domxref("TextTrackList")}}
- {{domxref("TextTrackCueList")}}
- {{domxref("VTTCue")}}
- {{HTMLElement("track")}}
- {{domxref("HTMLTrackElement")}}
| 0 |
data/mdn-content/files/en-us/web/api/texttrack | data/mdn-content/files/en-us/web/api/texttrack/addcue/index.md | ---
title: "TextTrack: addCue() method"
short-title: addCue()
slug: Web/API/TextTrack/addCue
page-type: web-api-instance-method
browser-compat: api.TextTrack.addCue
---
{{APIRef("WebVTT")}}
The **`addCue()`** method of the {{domxref("TextTrack")}} interface adds a new cue to the list of cues.
## Syntax
```js-nolint
addCue(cue)
```
### Parameters
- `cue`
- : A {{domxref("TextTrackCue")}}.
> **Note:** The {{domxref("TextTrackCue")}} interface is an abstract class used as the parent for other cue interfaces such as {{domxref("VTTCue")}}. Therefore, when adding a cue you will be using one of the cue types that inherit from `TextTrackCue`.
### Return value
Undefined.
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the rules for this {{domxref("TextTrackList")}} do not match those that are appropriate for the incoming {{domxref("TextTrackCue")}}.
## Examples
In the following example two cues are added to a video text track using `addCue()`.
```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
track.addCue(new VTTCue(0, 0.9, "Hildy!"));
track.addCue(new VTTCue(1, 1.4, "How are you?"));
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/texttrack | data/mdn-content/files/en-us/web/api/texttrack/inbandmetadatatrackdispatchtype/index.md | ---
title: "TextTrack: inBandMetadataTrackDispatchType property"
short-title: inBandMetadataTrackDispatchType
slug: Web/API/TextTrack/inBandMetadataTrackDispatchType
page-type: web-api-instance-property
browser-compat: api.TextTrack.label
---
{{APIRef("WebVTT")}}
The **`inBandMetadataTrackDispatchType`** read-only property of the {{domxref("TextTrack")}} interface returns the text track's in-band metadata dispatch type of the text track represented by the {{domxref("TextTrack")}} object.
An in-band metadata dispatch type is a string extracted from a media resource specifically for in-band metadata tracks. An example of a media resource that might have such tracks is a TV station streaming a broadcast on the web. Text Tracks may be used to include metadata for ad targeting, additional information such as recipe data during a cooking show, or trivia game data during a game show.
The value of this attribute could be used to attach these tracks to dedicated script modules as they are loaded.
## Value
A string containing the `inBandMetadataTrackDispatchType`, or an empty string.
## Examples
In the following example the value of `inBandMetadataTrackDispatchType` is printed to the console.
```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
console.log(track.inBandMetadataTrackDispatchType);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/texttrack | data/mdn-content/files/en-us/web/api/texttrack/language/index.md | ---
title: "TextTrack: language property"
short-title: language
slug: Web/API/TextTrack/language
page-type: web-api-instance-property
browser-compat: api.TextTrack.language
---
{{APIRef("WebVTT")}}
The **`language`** read-only property of the {{domxref("TextTrack")}} interface returns the language of the text track.
This uses the same values as the HTML [`lang`](/en-US/docs/Web/HTML/Global_attributes#lang) attribute. These values are documented in {{RFC(5646, "Tags for Identifying Languages (also known as BCP 47)")}}.
## Value
A string containing a language identifier. For example, `"en-US"` for United States English or `"pt-BR"` for Brazilian Portuguese.
## Examples
In the following example the value of `language` is printed to the console.
```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en-US");
track.mode = "showing";
console.log(track.language);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/texttrack | data/mdn-content/files/en-us/web/api/texttrack/cuechange_event/index.md | ---
title: "TextTrack: cuechange event"
short-title: cuechange
slug: Web/API/TextTrack/cuechange_event
page-type: web-api-event
browser-compat: api.TextTrack.cuechange_event
---
{{APIRef("WebVTT")}}
The **`cuechange`** event fires when a {{domxref("TextTrack")}} has changed the currently displaying cues. The event is fired on both the `TextTrack` and the {{domxref("HTMLTrackElement")}} in which it's being presented, if any.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("cuechange", (event) => {});
oncuechange = (event) => {};
```
## Event type
A generic {{DOMxRef("Event")}} with no added properties.
## Examples
You can set up a listener for the `cuechange` event on a `TextTrack` using the {{domxref("EventTarget.addEventListener", "addEventListener()")}} method:
```js
track.addEventListener("cuechange", () => {
const cues = track.activeCues; // array of current cues
// …
});
```
Or you can set the `oncuechange` event handler property:
```js
track.oncuechange = (event) => {
let cues = track.activeCues; // array of current cues
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{glossary("WebVTT")}}
- The same event on {{domxref("HTMLTrackElement")}}: {{domxref("HTMLTrackElement.cuechange_event", "cuechange")}}
| 0 |
data/mdn-content/files/en-us/web/api/texttrack | data/mdn-content/files/en-us/web/api/texttrack/cues/index.md | ---
title: "TextTrack: cues property"
short-title: cues
slug: Web/API/TextTrack/cues
page-type: web-api-instance-property
browser-compat: api.TextTrack.cues
---
{{APIRef("WebVTT")}}
The **`cues`** read-only property of the {{domxref("TextTrack")}} interface returns a {{domxref("TextTrackCueList")}} object containing all of the track's cues.
## Value
A {{domxref("TextTrackCueList")}} object.
## Examples
In the following example two cues are added to a video text track using `addCue()`. The value of `cues` is printed to the console. The returned {{domxref("TextTrackCueList")}} object contains the two cues.
```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
track.addCue(new VTTCue(0, 0.9, "Hildy!"));
track.addCue(new VTTCue(1, 1.4, "How are you?"));
console.log(track.cues);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/texttrack | data/mdn-content/files/en-us/web/api/texttrack/activecues/index.md | ---
title: "TextTrack: activeCues property"
short-title: activeCues
slug: Web/API/TextTrack/activeCues
page-type: web-api-instance-property
browser-compat: api.TextTrack.activeCues
---
{{APIRef("WebVTT")}}
The **`activeCues`** read-only property of the {{domxref("TextTrack")}} interface returns a {{domxref("TextTrackCueList")}} object listing the currently active cues.
## Value
A {{domxref("TextTrackCueList")}} object.
## Examples
The following example adds a new `TextTrack` to a video. The `activeCues` are printed to the console.
```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
console.log(track.activeCues);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/texttrack | data/mdn-content/files/en-us/web/api/texttrack/id/index.md | ---
title: "TextTrack: id property"
short-title: id
slug: Web/API/TextTrack/id
page-type: web-api-instance-property
browser-compat: api.TextTrack.id
---
{{APIRef("WebVTT")}}
The **`id`** read-only property of the {{domxref("TextTrack")}} interface returns the ID of the track if it has one.
## Value
A string containing the ID, or an empty string.
## Examples
In the following example the value of `id` is printed to the console.
```js
const video = document.querySelector("video");
const track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
console.log(track.id);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/texttrack | data/mdn-content/files/en-us/web/api/texttrack/label/index.md | ---
title: "TextTrack: label property"
short-title: label
slug: Web/API/TextTrack/label
page-type: web-api-instance-property
browser-compat: api.TextTrack.label
---
{{APIRef("WebVTT")}}
The **`label`** read-only property of the {{domxref("TextTrack")}} interface returns a human-readable label for the text track, if it is available.
## Value
A string containing the `label`, or an empty string.
## Examples
In the following example the value of `label` is printed to the console.
```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
console.log(track.label);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/texttrack | data/mdn-content/files/en-us/web/api/texttrack/kind/index.md | ---
title: "TextTrack: kind property"
short-title: kind
slug: Web/API/TextTrack/kind
page-type: web-api-instance-property
browser-compat: api.TextTrack.kind
---
{{APIRef("WebVTT")}}
The **`kind`** read-only property of the {{domxref("TextTrack")}} interface returns the kind of text track this object represents. This decides how the track will be handled by a user agent.
## Value
A string. One of:
- `"subtitles"`
- : The cues are overlaid on the video. Positioning of the cues is controlled using the properties of an object that inherits from {{domxref("TextTrackCue")}}, for example {{domxref("VTTCue")}}.
- `"captions"`
- : The cues are overlaid on the video. Positioning of the cues is controlled using the properties of an object that inherits from {{domxref("TextTrackCue")}}, for example {{domxref("VTTCue")}}.
- `"descriptions"`
- : The cues are made available in a non-visual fashion.
- `"chapters"`
- : The user agent will make available a mechanism to navigate by selecting a cue.
- `"metadata"`
- : Additional data related to the media data, which could be used for interactive views.
## Examples
In the following example the value of `kind` is printed to the console.
```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
console.log(track.kind);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/texttrack | data/mdn-content/files/en-us/web/api/texttrack/removecue/index.md | ---
title: "TextTrack: removeCue() method"
short-title: removeCue()
slug: Web/API/TextTrack/removeCue
page-type: web-api-instance-method
browser-compat: api.TextTrack.removeCue
---
{{APIRef("WebVTT")}}
The **`removeCue()`** method of the {{domxref("TextTrack")}} interface removes a cue from the list of cues.
## Syntax
```js-nolint
removeCue(cue)
```
### Parameters
- `cue`
- : A {{domxref("TextTrackCue")}}.
### Return value
Undefined.
### Exceptions
- `NotFoundError` {{domxref("DOMException")}}
- : Thrown if the given cue is not found in the list of cues.
> **Note:** The {{domxref("TextTrackCue")}} interface is an abstract class used as the parent for other cue interfaces such as {{domxref("VTTCue")}}. Therefore, when removing a cue you will be passing in one of the cue types that inherit from `TextTrackCue`.
## Examples
In the following example a cue is added to a video text track using `addCue()`, then removed using `removeCue`.
```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
let cue = new VTTCue(0, 0.9, "Hildy!");
track.addCue(cue);
track.removeCue(cue);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgpolylineelement/index.md | ---
title: SVGPolylineElement
slug: Web/API/SVGPolylineElement
page-type: web-api-interface
browser-compat: api.SVGPolylineElement
---
{{APIRef("SVG")}}
The **`SVGPolylineElement`** interface provides access to the properties of {{SVGElement("polyline")}} elements, as well as methods to manipulate them.
{{InheritanceDiagram}}
## Instance properties
_This interface also inherits properties from its parent, {{domxref("SVGGeometryElement")}}._
- {{domxref("SVGPolylineElement.animatedPoints")}} {{ReadOnlyInline}}
- : A {{DOMxRef("SVGPointList")}} representing the animated value of the element's {{SVGAttr("points")}} attribute. If the {{SVGAttr("points")}} attribute is not being animated, it contains the same value as the `points` property.
- {{domxref("SVGPolylineElement.points")}}
- : A {{DOMxRef("SVGPointList")}} representing the base (i.e., static) value of the element's {{SVGAttr("points")}} attribute. Modifications via the {{DOMxRef("SVGPointList")}} object are reflected in the {{SVGAttr("points")}} attribute, and vice versa.
## Instance methods
_This interface doesn't implement any specific methods, but inherits methods from its parent, {{domxref("SVGGeometryElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{SVGElement("polyline")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/toggleevent/index.md | ---
title: ToggleEvent
slug: Web/API/ToggleEvent
page-type: web-api-interface
browser-compat: api.ToggleEvent
---
{{APIRef("Popover API")}}
The **`ToggleEvent`** interface represents an event notifying the user when a [popover element](/en-US/docs/Web/API/Popover_API)'s state toggles between showing and hidden.
It is the event object for the `HTMLElement` {{domxref("HTMLElement.beforetoggle_event", "beforetoggle")}} and {{domxref("HTMLElement.toggle_event", "toggle")}} events, which fire on popovers when they transition between showing and hidden (before and after, respectively).
{{InheritanceDiagram}}
> **Note:** `ToggleEvent` is unrelated to the `HTMLDetailsElement` {{domxref("HTMLDetailsElement.toggle_event", "toggle")}} event, which fires on a {{htmlelement("details")}} element when its `open`/`closed` state is toggled. Its event object is a generic {{domxref("Event")}}.
## Constructor
- {{DOMxRef("ToggleEvent.ToggleEvent", "ToggleEvent()")}}
- : Creates an `ToggleEvent` object.
## Instance properties
_This interface inherits properties from its parent, {{DOMxRef("Event")}}._
- {{DOMxRef("ToggleEvent.newState")}} {{ReadOnlyInline}}
- : A string (either `"open"` or `"closed"`), representing the state the element is transitioning to.
- {{DOMxRef("ToggleEvent.oldState")}} {{ReadOnlyInline}}
- : A string (either `"open"` or `"closed"`), representing the state the element is transitioning from.
## Examples
### Basic example
```js
const popover = document.getElementById("mypopover");
// ...
popover.addEventListener("beforetoggle", (event) => {
if (event.newState === "open") {
console.log("Popover is being shown");
} else {
console.log("Popover is being hidden");
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Popover API](/en-US/docs/Web/API/Popover_API)
- [`beforetoggle` event](/en-US/docs/Web/API/HTMLElement/beforetoggle_event)
- [`toggle` event](/en-US/docs/Web/API/HTMLElement/toggle_event)
| 0 |
data/mdn-content/files/en-us/web/api/toggleevent | data/mdn-content/files/en-us/web/api/toggleevent/newstate/index.md | ---
title: "ToggleEvent: newState property"
short-title: newState
slug: Web/API/ToggleEvent/newState
page-type: web-api-instance-property
browser-compat: api.ToggleEvent.newState
---
{{APIRef("Popover API")}}
The **`newState`** read-only property of the {{domxref("ToggleEvent")}} interface is a string representing the state the element is transitioning to.
## Value
A string. Possible values are `"open"` (the popover is being shown) or `"closed"` (the popover is being hidden).
## Examples
```js
const popover = document.getElementById("mypopover");
// ...
popover.addEventListener("beforetoggle", (event) => {
if (event.newState === "open") {
console.log("Popover is being shown");
} else {
console.log("Popover is being hidden");
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Popover API](/en-US/docs/Web/API/Popover_API)
| 0 |
data/mdn-content/files/en-us/web/api/toggleevent | data/mdn-content/files/en-us/web/api/toggleevent/oldstate/index.md | ---
title: "ToggleEvent: oldState property"
short-title: oldState
slug: Web/API/ToggleEvent/oldState
page-type: web-api-instance-property
browser-compat: api.ToggleEvent.oldState
---
{{APIRef("Popover API")}}
The **`oldState`** read-only property of the {{domxref("ToggleEvent")}} interface is a string representing the state the element is transitioning from.
## Value
A string. Possible values are `"open"` (the popover is going from showing to hidden) or `"closed"` (the popover going from hidden to shown).
## Examples
```js
const popover = document.getElementById("mypopover");
// ...
popover.addEventListener("beforetoggle", (event) => {
if (event.oldState === "open") {
console.log("Popover is being hidden");
} else {
console.log("Popover is being shown");
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Popover API](/en-US/docs/Web/API/Popover_API)
| 0 |
data/mdn-content/files/en-us/web/api/toggleevent | data/mdn-content/files/en-us/web/api/toggleevent/toggleevent/index.md | ---
title: "ToggleEvent: ToggleEvent() constructor"
short-title: ToggleEvent()
slug: Web/API/ToggleEvent/ToggleEvent
page-type: web-api-constructor
browser-compat: api.ToggleEvent.ToggleEvent
---
{{APIRef("Popover API")}}
The **`ToggleEvent()`** constructor creates a new {{domxref("ToggleEvent")}} object.
## Syntax
```js-nolint
new ToggleEvent(type, init)
```
### Parameters
- `type`
- : A string representing the type of event. In the case of `ToggleEvent` this is always `toggleevent`.
- `init`
- : An object containing the following properties:
- `newState`
- : A string representing the state the element is transitioning to. Possible values are `"open"` and `"closed"`.
- `oldState`
- : A string representing the state the element is transitioning from. Possible values are `"open"` and `"closed"`.
## Examples
A developer would not use this constructor manually. A new `ToggleEvent` object is constructed when a handler is invoked as a result of a relevant event firing.
For example:
```js
const popover = document.getElementById("mypopover");
// ...
popover.addEventListener("beforetoggle", (event) => {
if (event.newState === "open") {
console.log("Popover is being shown");
} else {
console.log("Popover is being hidden");
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Popover API](/en-US/docs/Web/API/Popover_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/cookiechangeevent/index.md | ---
title: CookieChangeEvent
slug: Web/API/CookieChangeEvent
page-type: web-api-interface
browser-compat: api.CookieChangeEvent
---
{{securecontext_header}}{{APIRef("Cookie Store API")}}
The **`CookieChangeEvent`** interface of the {{domxref("Cookie Store API", "", "", "nocode")}} is the event type of the {{domxref("CookieStore/change_event", "change")}} event fired at a {{domxref("CookieStore")}} when any cookie changes occur. A cookie change consists of a cookie and a type (either "changed" or "deleted").
Cookie changes that will cause the `CookieChangeEvent` to be dispatched are:
- A cookie is newly created and not immediately removed. In this case `type` is "changed".
- A cookie is newly created and immediately removed. In this case `type` is "deleted".
- A cookie is removed. In this case `type` is "deleted".
> **Note:** A cookie that is replaced due to the insertion of another cookie with the same name, domain, and path, is ignored and does not trigger a change event.
{{InheritanceDiagram}}
## Constructor
- {{domxref("CookieChangeEvent.CookieChangeEvent", "CookieChangeEvent()")}}
- : Creates a new `CookieChangeEvent`.
## Instance properties
_This interface also inherits properties from {{domxref("Event")}}._
- {{domxref("CookieChangeEvent.changed")}} {{ReadOnlyInline}}
- : Returns an array containing one or more changed cookies.
- {{domxref("CookieChangeEvent.deleted")}} {{ReadOnlyInline}}
- : Returns an array containing one or more deleted cookies.
## Instance methods
_This interface also inherits methods from {{domxref("Event")}}._
## Examples
In this example when the cookie is set, the event listener logs the event to the console. This is a `CookieChangeEvent` object with the {{domxref("CookieChangeEvent.changed","changed")}} property containing an object representing the cookie that has just been set.
```js
cookieStore.addEventListener("change", (event) => {
console.log(event);
});
const one_day = 24 * 60 * 60 * 1000;
cookieStore.set({
name: "cookie1",
value: "cookie1-value",
expires: Date.now() + one_day,
domain: "example.com",
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cookiechangeevent | data/mdn-content/files/en-us/web/api/cookiechangeevent/changed/index.md | ---
title: "CookieChangeEvent: changed property"
short-title: changed
slug: Web/API/CookieChangeEvent/changed
page-type: web-api-instance-property
browser-compat: api.CookieChangeEvent.changed
---
{{securecontext_header}}{{APIRef("Cookie Store API")}}
The **`changed`** read-only property of the {{domxref("CookieChangeEvent")}} interface returns an array of the cookies that have been changed.
## Value
An array of objects containing the changed cookie(s). Each object contains the following properties:
- `name`
- : A string containing the name of the cookie.
- `value`
- : A string containing the value of the cookie.
- `domain`
- : A string containing the domain of the cookie.
- `path`
- : A string containing the path of the cookie.
- `expires`
- : A timestamp, given as {{glossary("Unix time")}} in milliseconds, containing the expiration date of the cookie.
- `secure`
- : A {{jsxref("boolean")}} indicating whether the cookie is from a site with a secure context (HTTPS rather than HTTP).
- `sameSite`
- : One of the following [`SameSite`](/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value) values:
- `"strict"`
- : Cookies will only be sent in a first-party context and not be sent with requests initiated by third party websites.
- `"lax"`
- : Cookies are not sent on normal cross-site subrequests (for example to load images or frames into a third party site), but are sent when a user is navigating within the origin site (i.e. when following a link).
- `"none"`
- : Cookies will be sent in all contexts.
- `partitioned`
- : A boolean indicating whether the cookie is a partitioned cookie (`true`) or not (`false`). See [Cookies Having Independent Partitioned State (CHIPS)](/en-US/docs/Web/Privacy/Partitioned_cookies) for more information.
## Examples
In this example, when the cookie is set, the event listener logs the `changed` property to the console. The first item in that array contains an object representing the cookie that has just been set.
```js
cookieStore.addEventListener("change", (event) => {
console.log(event.changed[0]);
});
const one_day = 24 * 60 * 60 * 1000;
cookieStore.set({
name: "cookie1",
value: "cookie1-value",
expires: Date.now() + one_day,
domain: "example.com",
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cookiechangeevent | data/mdn-content/files/en-us/web/api/cookiechangeevent/deleted/index.md | ---
title: "CookieChangeEvent: deleted property"
short-title: deleted
slug: Web/API/CookieChangeEvent/deleted
page-type: web-api-instance-property
browser-compat: api.CookieChangeEvent.deleted
---
{{securecontext_header}}{{APIRef("Cookie Store API")}}
The **`deleted`** read-only property of the {{domxref("CookieChangeEvent")}} interface returns an array of the cookies that have been deleted by the given `CookieChangeEvent` instance.
## Value
An array of objects containing the deleted cookie(s). Each object contains the following properties:
- `name`
- : A string containing the name of the cookie.
- `value`
- : A string containing the value of the cookie.
- `domain`
- : A string containing the domain of the cookie.
- `path`
- : A string containing the path of the cookie.
- `expires`
- : A timestamp, given as {{glossary("Unix time")}} in milliseconds, containing the expiration date of the cookie.
- `secure`
- : A {{jsxref("boolean")}} indicating whether the cookie is from a site with a secure context (HTTPS rather than HTTP).
- `sameSite`
- : One of the following [`SameSite`](/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value) values:
- `"strict"`
- : Cookies will only be sent in a first-party context and not be sent with requests initiated by third party websites.
- `"lax"`
- : Cookies are not sent on normal cross-site subrequests (for example to load images or frames into a third party site), but are sent when a user is navigating within the origin site (i.e. when following a link).
- `"none"`
- : Cookies will be sent in all contexts.
- `partitioned`
- : A boolean indicating whether the cookie is a partitioned cookie (`true`) or not (`false`). See [Cookies Having Independent Partitioned State (CHIPS)](/en-US/docs/Web/Privacy/Partitioned_cookies) for more information.
## Examples
In this example, when the cookie is deleted, the event listener logs the first item in the `CookieChangeEvent.deleted` property to the console. It contains an object representing the cookie that has just been deleted.
```js
cookieStore.addEventListener("change", (event) => {
console.log(event.deleted[0]);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cookiechangeevent | data/mdn-content/files/en-us/web/api/cookiechangeevent/cookiechangeevent/index.md | ---
title: "CookieChangeEvent: CookieChangeEvent() constructor"
short-title: CookieChangeEvent()
slug: Web/API/CookieChangeEvent/CookieChangeEvent
page-type: web-api-constructor
browser-compat: api.CookieChangeEvent.CookieChangeEvent
---
{{securecontext_header}}{{APIRef("Cookie Store API")}}
The **`CookieChangeEvent()`** constructor creates a new {{domxref("CookieChangeEvent")}} object
which is the event type of the {{domxref("CookieStore/change_event", "change")}} event fired at a {{domxref("CookieStore")}} when any cookie changes occur.
This constructor is called by the browser when a change event occurs.
> **Note:** This event constructor is generally not needed for production websites. It's primary use is for tests that require an instance of this event.
## Syntax
```js-nolint
new CookieChangeEvent(type)
new CookieChangeEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event. It is case-sensitive and browsers always set it to `change`.
- `options` {{Optional_Inline}}
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties:
- `changed`{{Optional_Inline}}
- : An array containing the changed cookies.
- `deleted`{{Optional_Inline}}
- : An array containing the deleted cookies.
### Return value
A new {{domxref("CookieChangeEvent")}} object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web | data/mdn-content/files/en-us/web/performance/index.md | ---
title: Web performance
slug: Web/Performance
page-type: landing-page
---
{{QuickLinksWithSubPages}}
Web performance is the objective measurements and the perceived user experience of load time and runtime. Web performance is how long a site takes to load, become interactive and responsive, and how smooth the content is during user interactions - is the scrolling smooth? are buttons clickable? Are pop-ups quick to load and display, and do they animate smoothly as they do so? Web performance includes both objective measurements like time to load, frames per second, and time to become interactive, and subjective experiences of how long it felt like it took the content to load.
The longer it takes for a site to respond, the more users will abandon the site. It is important to minimize the loading and response times and add additional features to conceal latency by making the experience as available and interactive as possible, as soon as possible, while asynchronously loading in the longer tail parts of the experience.
There are tools, APIs, and best practices that help us measure and improve web performance. We cover them in this section:
## Key performance guides
{{LandingPageListSubpages}}
## Beginner's tutorials
The MDN [Web Performance Learning Area](/en-US/docs/Learn/Performance) contains modern, up-to-date tutorials covering Performance essentials. Start here if you are a newcomer to performance:
- [Web performance: brief overview](/en-US/docs/Learn/Performance/What_is_web_performance)
- : Overview of the web performance learning path. Start your journey here.
- [What is web performance?](/en-US/docs/Learn/Performance/What_is_web_performance)
- : This article starts the module off with a good look at what performance actually is — this includes the tools, metrics, APIs, networks, and groups of people we need to consider when thinking about performance, and how we can make performance part of our web development workflow.
- [How do users perceive performance?](/en-US/docs/Learn/Performance/Perceived_performance)
- : More important than how fast your website is in milliseconds, is how fast your users perceive your site to be. These perceptions are impacted by actual page load time, idling, responsiveness to user interaction, and the smoothness of scrolling and other animations. In this article, we discuss the various loading metrics, animation, and responsiveness metrics, along with best practices to improve user perception, if not the actual timings.
- [Web performance basics](/en-US/docs/Learn/Performance/Web_Performance_Basics)
- : In addition to the front end components of HTML, CSS, JavaScript, and media files, there are features that can make applications slower and features that can make applications subjectively and objectively faster. There are many APIs, developer tools, best practices, and bad practices relating to web performance. Here we'll introduce many of these features ad the basic level and provide links to deeper dives to improve performance for each topic.
- [HTML performance features](/en-US/docs/Learn/Performance/HTML)
- : Some attributes and the source order of your markup can impact the performance or your website. By minimizing the number of DOM nodes, making sure the best order and attributes are used for including content such as styles, scripts, media, and third-party scripts, you can drastically improve the user experience. This article looks in detail at how HTML can be used to ensure maximum performance.
- [Multimedia: images and video](/en-US/docs/Learn/Performance/Multimedia)
- : The lowest hanging fruit of web performance is often media optimization. Serving different media files based on each user agent's capability, size, and pixel density is possible. Additional tips like removing audio tracks from background videos can improve performance even further. In this article we discuss the impact video, audio, and image content has on performance, and the methods to ensure that impact is as minimal as possible.
- [CSS performance features](/en-US/docs/Learn/Performance/CSS)
- : CSS may be a less important optimization focus for improved performance, but there are some CSS features that impact performance more than others. In this article we look at some CSS properties that impact performance and suggested ways of handling styles to ensure performance is not negatively impacted.
- [JavaScript performance best practices](/en-US/docs/Learn/Performance/JavaScript)
- : JavaScript, when used properly, can allow for interactive and immersive web experiences — or it can significantly harm download time, render time, in-app performance, battery life, and user experience. This article outlines some JavaScript best practices that should be considered to ensure even complex content is as performant as possible.
## Using Performance APIs
- [Resource Timing API](/en-US/docs/Web/API/Performance_API/Resource_timing)
- : [Resource loading and timing](/en-US/docs/Web/API/Performance_API/Resource_timing) the loading of those resources, including managing the resource buffer and coping with CORS
- [User Timing API](/en-US/docs/Web/API/Performance_API/User_timing)
- : Create application specific timestamps using the [user timing API](/en-US/docs/Web/API/Performance_API/User_timing)'s "mark" and "measure" entry types - that are part of the browser's performance timeline.
- [Beacon API](/en-US/docs/Web/API/Beacon_API)
- : The [Beacon](/en-US/docs/Web/API/Beacon_API) interface schedules an asynchronous and non-blocking request to a web server.
- [Intersection Observer API](/en-US/docs/Web/API/Intersection_Observer_API/Timing_element_visibility)
- : Learn to time element visibility with the [Intersection Observer API](/en-US/docs/Web/API/Intersection_Observer_API) and be asynchronously notified when elements of interest becomes visible.
## Other documentation
- [Firefox Profiler Performance Features](https://profiler.firefox.com/docs/#/)
- : This website provides information on how to use and understand the performance features in your developer tools, including [Call Tree](https://profiler.firefox.com/docs/#/./guide-ui-tour-panels?id=the-call-tree), [Flame Graph](https://profiler.firefox.com/docs/#/./guide-ui-tour-panels?id=the-flame-graph), [Stack Chart](https://profiler.firefox.com/docs/#/./guide-ui-tour-panels?id=the-stack-chart), [Marker Chart](https://profiler.firefox.com/docs/#/./guide-ui-tour-panels?id=the-marker-chart) and [Network Chart](https://profiler.firefox.com/docs/#/./guide-ui-tour-panels?id=the-network-chart).
- [Profiling with the built-in profiler](https://profiler.firefox.com/docs/#/./guide-getting-started)
- : Learn how to profile app performance with Firefox's built-in profiler.
## Glossary Terms
- {{glossary('Beacon')}}
- {{glossary('Brotli compression')}}
- [Client hints](/en-US/docs/Web/HTTP/Client_hints)
- {{glossary('Code splitting')}}
- {{glossary('CSSOM')}}
- {{glossary('Domain sharding')}}
- {{glossary('Effective connection type')}}
- {{glossary('First contentful paint')}}
- {{glossary('First CPU idle')}}
- {{glossary('First input delay')}}
- {{glossary('First meaningful paint')}}
- {{glossary('First paint')}}
- {{glossary('HTTP')}}
- {{glossary('HTTP_2', 'HTTP/2')}}
- {{glossary('Jank')}}
- {{glossary('Latency')}}
- {{glossary('Lazy load')}}
- {{glossary('Long task')}}
- {{glossary('Lossless compression')}}
- {{glossary('Lossy compression')}}
- {{glossary('Main thread')}}
- {{glossary('Minification')}}
- {{glossary('Network throttling')}}
- {{glossary('Packet')}}
- {{glossary('Page load time')}}
- {{glossary('Page prediction')}}
- {{glossary('Parse')}}
- {{glossary('Perceived performance')}}
- {{glossary('Prefetch')}}
- {{glossary('Prerender')}}
- {{glossary('QUIC')}}
- {{glossary('RAIL')}}
- {{glossary('Real User Monitoring')}}
- {{glossary('Resource Timing')}}
- {{glossary('Round Trip Time', 'Round Trip Time (RTT)')}}
- {{glossary('Server Timing')}}
- {{glossary('Speculative parsing')}}
- {{glossary('Speed index')}}
- {{glossary('SSL')}}
- {{glossary('Synthetic monitoring')}}
- {{glossary('TCP handshake')}}
- {{glossary('TCP slow start')}}
- {{glossary('Time to first byte')}}
- {{glossary('Time to interactive')}}
- {{glossary('TLS')}}
- {{glossary('TCP', 'Transmission Control Protocol (TCP)')}}
- {{glossary('Tree shaking')}}
- {{glossary('Web performance')}}
## See also
HTML
- [The `<picture>` Element](/en-US/docs/Web/HTML/Element/picture)
- [The `<video>` Element](/en-US/docs/Web/HTML/Element/video)
- [The `<source>` Element](/en-US/docs/Web/HTML/Element/source)
- [The `<img> srcset` attribute](/en-US/docs/Web/HTML/Element/img#attributes)
- [Responsive images](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images)
- [Preloading content with `rel="preload"`](/en-US/docs/Web/HTML/Attributes/rel/preload)
- <https://w3c.github.io/preload/>
CSS
- [will-change](/en-US/docs/Web/CSS/will-change)
- GPU v CPU
- Measuring layout
- Font-loading best practices
JavaScript
- [DOMContentLoaded](/en-US/docs/Web/API/Document/DOMContentLoaded_event)
- [Garbage collection](/en-US/docs/Glossary/Garbage_collection)
- [requestAnimationFrame](/en-US/docs/Web/API/window/requestAnimationFrame)
APIs
- [Performance API](/en-US/docs/Web/API/Performance_API)
- [Navigation Timing API](/en-US/docs/Web/API/Performance_API/Navigation_timing)
- [Media Capabilities API](/en-US/docs/Web/API/Media_Capabilities_API/Using_the_Media_Capabilities_API)
- [Network Information API](/en-US/docs/Web/API/Network_Information_API)
- [PerformanceNavigationTiming](/en-US/docs/Web/API/PerformanceNavigationTiming)
- [Battery Status API](/en-US/docs/Web/API/Battery_Status_API)
- [Navigator.deviceMemory](/en-US/docs/Web/API/Navigator/deviceMemory)
- [Intersection Observer](/en-US/docs/Web/API/Intersection_Observer_API)
- [Using the User Timing API](/en-US/docs/Web/API/Performance_API/User_timing)
- [High Resolution Timing API](/en-US/docs/Web/API/DOMHighResTimeStamp) ([https://w3c.github.io/hr-time/)](https://w3c.github.io/hr-time/)
- [Resource Timing API](/en-US/docs/Web/API/Performance_API/Resource_timing)
- [Page Visibility](/en-US/docs/Web/API/Page_Visibility_API)
- [Cooperative Scheduling of Background Tasks API](/en-US/docs/Web/API/Background_Tasks_API)
- [requestIdleCallback()](/en-US/docs/Web/API/Window/requestIdleCallback)
- [Beacon API](/en-US/docs/Web/API/Beacon_API)
- Resource Hints - [dns-prefetch](/en-US/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control), preconnect, [prefetch](/en-US/docs/Glossary/Prefetch), and prerender
- [FetchEvent.preloadResponse](/en-US/docs/Web/API/FetchEvent/preloadResponse)
- [Performance Server Timing API](/en-US/docs/Web/API/PerformanceServerTiming)
Headers
- [Content-encoding](/en-US/docs/Web/HTTP/Headers/Content-Encoding)
- HTTP/2
- [gZip](/en-US/docs/Glossary/GZip_compression)
- Client Hints
Tools
- [Performance in Firefox Developer Tools](https://profiler.firefox.com/docs/#/)
Additional Metrics
- Speed Index and Perceptual Speed Index
Best Practices
- [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers)
- [Using Web Workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
- [Web Workers API](/en-US/docs/Web/API/Web_Workers_API)
- [Offline and background operation](/en-US/docs/Web/Progressive_web_apps/Guides/Offline_and_background_operation)
- [Caching](/en-US/docs/Web/HTTP/Caching)
- Content Delivery Networks (CDN)
| 0 |
data/mdn-content/files/en-us/web/performance | data/mdn-content/files/en-us/web/performance/animation_performance_and_frame_rate/index.md | ---
title: Animation performance and frame rate
slug: Web/Performance/Animation_performance_and_frame_rate
page-type: guide
---
{{QuickLinksWithSubPages("Web/Performance")}}
Animation on the web can be done via {{domxref('SVGAnimationElement', 'SVG')}}, {{domxref('window.requestAnimationFrame','JavaScript')}}, including {{htmlelement('canvas')}} and {{domxref('WebGL_API', 'WebGL')}}, CSS {{cssxref('animation')}}, {{htmlelement('video')}}, animated gifs and even animated PNGs and other image types. The performance cost of animating a CSS property can vary from one property to another, and animating expensive CSS properties can result in {{glossary('jank')}} as the browser struggles to hit a smooth {{glossary("FPS", "frame rate")}}.
For animated media, such as video and animated gifs, the main performance concern is file size - downloading the file fast enough to not negatively impact performance is the greatest issue. Code based animations, be it CSS, SVG, \<canvas>, webGL or other JavaScript animations, can cause performance issues even if the bandwidth footprint is small. These animations can consume CPU and/or cause jank.
Users expect all interface interactions to be smooth and all user interfaces to be responsive. Animation can help make a site feel faster and responsive, but animations can also make a site feel slower and janky if not done correctly. Responsive user interfaces have a frame rate of 60 frames per second (fps). While it is not always possible to maintain 60fps, it is important to maintain a high and steady frame rate for all animations.
With [CSS animations](/en-US/docs/Web/CSS/CSS_animations/Using_CSS_animations) you specify a number of [keyframes](/en-US/docs/Web/CSS/@keyframes), each of which uses CSS to define the appearance of the element at a particular stage of the animation. The browser creates the animation as a transition from each keyframe to the next.
Compared with animating elements using JavaScript, CSS animations can be easier to create. They can also give better performance, as they give the browser more control over when to render frames, and to drop frames if necessary.
However, the performance cost of modifying a CSS property can vary from one property to another. It's commonly accepted that 60 frames per second is the rate at which animations will appear smooth. For a rate of 60 frames per second, the browser has 16.7 milliseconds to execute scripts, recalculate styles and layout if needed, and repaint the area being updated. Slow scripts and animating expensive CSS properties can result in [jank](/en-US/docs/Glossary/Jank) as the browser struggles to hit a smooth frame rate.
## The rendering waterfall
The process a browser uses to paint changes to a page when an element is animating CSS properties can be described as a waterfall consisting of the following steps:

1. **Recalculate Style**: when a property for an element changes, the browser must recalculate computed styles.
2. **Layout**: next, the browser uses the computed styles to figure out the position and geometry for the elements. This operation is labeled "layout" but is also sometimes called "reflow".
3. **Paint**: finally, the browser needs to repaint the elements to the screen. One last step is not shown in this sequence: the page may be split into layers, which are painted independently and then combined in a process called "Composition".
This sequence needs to fit into a single frame, since the screen isn't updated until it is complete.
## CSS property cost
In the context of the rendering waterfall, some properties are more expensive than others:
- Properties that affect an element's **geometry** or **position** trigger a:
- style recalculation
- layout
- repaint
For example: {{cssxref("left")}}, {{cssxref("max-width")}}, {{cssxref("border-width")}}, {{cssxref("margin-left")}}, {{cssxref("font-size")}}
- Properties that do _not_ affect geometry or position and are _not rendered_ in their own layer, do _not_ trigger a layout. They do trigger a:
- style recalculation
- repaint
For example: {{cssxref("color")}}
- Properties that _are rendered_ in their **own layer** don't even trigger a repaint, because the update is handled in **composition**. These do trigger:
- style recalculation
For example: {{cssxref("transform")}}, {{cssxref("opacity")}}
## Developer tools
Most web browsers include tools to provide insight into the work the browser is doing when it animates elements of a page. Using these tools you can measure an application's animation frame rate, and diagnose performance bottlenecks if any are found.
- [Chrome performance tools](https://developer.chrome.com/docs/devtools/#performance)
- [Firefox performance tools](https://firefox-source-docs.mozilla.org/devtools-user/performance/)
| 0 |
data/mdn-content/files/en-us/web/performance | data/mdn-content/files/en-us/web/performance/how_long_is_too_long/index.md | ---
title: "Recommended Web Performance Timings: How long is too long?"
slug: Web/Performance/How_long_is_too_long
page-type: guide
---
{{QuickLinksWithSubPages("Web/Performance")}}
There are no clear set rules as to what constitutes a slow pace when loading pages, but there are specific guidelines for indicating content will load (1 second), idling (50ms), animating (16.7ms) and responding to user input (50 to 200ms).
## Load goal
The 'Under a second' is often touted as optimal for load, but what does that mean? A second should be considered a rule in the maximum amount of time to indicate to a user that the request for new content was made and will load, such as the browser displaying the page title and the background color of the page displaying.
The first asset retrieved from a request is usually an HTML document, which then makes calls for additional assets. As noted in the description of the [critical rendering path](/en-US/docs/Web/Performance/Critical_rendering_path), when received, browsers immediately start processing the HTML, rendering the content as it is received rather than waiting for additional assets to load.
Yes, one second for loading is a goal, but it's something few sites achieve. Expectations differ. A 'hello world' on the corporate network would be expected to load in milliseconds, but a user downloading a cat video on a five-year-old device over an edge network in northern Siberia would likely find a 20-second download speedy. If you wait three or four seconds without communicating to the user that a load is happening and showing some progress, the typical site will lose potential visitors, and those visitors will take a long time to come back if they ever do.
In optimizing for performance, do set an ambitious first load goal, such as 5 seconds over the mobile 3G network and 1.5 seconds on an office T1 line, with even more ambitious page load goals for subsequent page loads, leveraging service workers and caching. There are different suggested times for initially loading the page versus loading additional assets, responding to user interaction, and ensuring smooth animations:
## Idling goal
Browsers are single threaded (though background threads are supported for web workers). This means that user interaction, painting, and script execution are all on the same thread. If the thread is busy doing complex JavaScript execution, the main thread will not be available to react to user input, such as pressing a button. For this reason, script execution should be limited in scope, divided into chunks of code that can be executed in 50ms or less. This makes the thread available for user interactions.
## Animation goal
For scrolling and other animations to look smooth and feel responsive, the content repaints should occur at 60 frames per second (60fps), which is once every 16.7ms. The 16.7 milliseconds includes scripting, reflow, and repaint. Realize a document takes about 6ms to render a frame, leaving about 10ms for the rest. Anything less than 60fps, especially an un-even or changing frame rate, will appear janky.
## Responsiveness goal
When the user interacts with content, it is important to provide feedback and acknowledge the user's response or interaction and to do so within 100ms, preferably within 50ms. 50ms seconds feels immediate. The acknowledgment of user interaction should often feel immediate, such as a hover or button press, but that doesn't mean the completed response should be instantaneous. While a slower than 100ms reaction may create a disconnect between the user interaction and the response, a 100 to 200ms transition for a response may help the user notice the response their interaction initiated, such as a menu opening. If a response takes longer than 100ms to complete, provide some form of feedback to inform the user the interaction has occurred.
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.