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/mediastreamtrack | data/mdn-content/files/en-us/web/api/mediastreamtrack/getsettings/index.md | ---
title: "MediaStreamTrack: getSettings() method"
short-title: getSettings()
slug: Web/API/MediaStreamTrack/getSettings
page-type: web-api-instance-method
browser-compat: api.MediaStreamTrack.getSettings
---
{{APIRef("Media Capture and Streams")}}
The **`getSettings()`** method of the
{{domxref("MediaStreamTrack")}} interface returns a {{domxref("MediaTrackSettings")}}
object containing the current values of each of the constrainable properties for the
current `MediaStreamTrack`.
See [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints) for details on how to work with constrainable properties.
## Syntax
```js-nolint
getSettings()
```
### Parameters
None.
### Return value
A {{domxref("MediaTrackSettings")}} object describing the current configuration of the
track's constrainable properties.
> **Note:** The returned object identifies the current values of every
> constrainable property, including those which are platform defaults rather than having
> been expressly set by the site's code. To instead fetch the most-recently established
> constraints for the track's properties, as specified by the site's code, use
> {{domxref("MediaStreamTrack.getConstraints", "getConstraints()")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrack | data/mdn-content/files/en-us/web/api/mediastreamtrack/kind/index.md | ---
title: "MediaStreamTrack: kind property"
short-title: kind
slug: Web/API/MediaStreamTrack/kind
page-type: web-api-instance-property
browser-compat: api.MediaStreamTrack.kind
---
{{APIRef("Media Capture and Streams")}}
The **`kind`** read-only property of the {{domxref("MediaStreamTrack")}} interface returns a string set to `"audio"` if the track is an audio track and to `"video"` if it is a video track.
It doesn't change if the track is disassociated from its source.
## Value
The possible values are a string with one of the following values:
- `"audio"`: the track is an audio track.
- `"video"`: the track is a video track.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrack | data/mdn-content/files/en-us/web/api/mediastreamtrack/contenthint/index.md | ---
title: "MediaStreamTrack: contentHint property"
short-title: contentHint
slug: Web/API/MediaStreamTrack/contentHint
page-type: web-api-instance-property
browser-compat: api.MediaStreamTrack.contentHint
---
{{APIRef("Media Capture and Streams")}}
The **`contentHint`** property of the {{domxref("MediaStreamTrack")}} interface is a string that hints at the type of content the track contains. Allowable values depend on the value of the {{domxref("MediaStreamTrack.kind")}} property.
## Value
A string with one of the following values:
- `""`
- : No `contentHint` has been set.
- `"speech"`
- : The track should be treated as if it contains speech data. When setting this value, the value of {{domxref("MediaStreamTrack.kind")}} must be `"audio"`.
- `"speech-recognition"`
- : The track should be treated as if it contains data for the purpose of speech recognition by a machine. When setting this value, the value of {{domxref("MediaStreamTrack.kind")}} must be `"audio"`.
- `"music"`
- : The track should be treated as if it contains music. When setting this value, the value of {{domxref("MediaStreamTrack.kind")}} must be `"audio"`.
- `"motion"`
- : The track should be treated as if it contains video where motion is important. For example, webcam video, movies or video games. When setting this value, the value of {{domxref("MediaStreamTrack.kind")}} must be `"video"`.
- `"detail"`
- : The track should be treated as if video details are extra important. For example, presentations or web pages with text content, painting or line art. When setting this value, the value of {{domxref("MediaStreamTrack.kind")}} must be `"video"`.
- `"text"`
- : The track should be treated as if video details are extra important, and that significant sharp edges and areas of consistent color can occur frequently. For example, presentations or web pages with text content. When setting this value, the value of {{domxref("MediaStreamTrack.kind")}} must be `"video"`.
## Examples
### A function that sets the contentHint
This function takes a stream and a `contentHint` value, and applies the hint to each track. [See the full example here](https://webrtc.github.io/samples/src/content/capture/video-contenthint/), showing how different `contentHint` values change how the tracks display.
```js
function setVideoTrackContentHints(stream, hint) {
const tracks = stream.getVideoTracks();
tracks.forEach((track) => {
if ("contentHint" in track) {
track.contentHint = hint;
if (track.contentHint !== hint) {
console.error(`Invalid video track contentHint: "${hint}"`);
}
} else {
console.error("MediaStreamTrack contentHint attribute not supported");
}
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/notificationevent/index.md | ---
title: NotificationEvent
slug: Web/API/NotificationEvent
page-type: web-api-interface
browser-compat: api.NotificationEvent
---
{{APIRef("Web Notifications")}}
The **`NotificationEvent`** interface of the {{domxref("Notifications API", "", "", "nocode")}} represents a notification event dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}.
This interface inherits from the {{domxref("ExtendableEvent")}} interface.
> **Note:** Only persistent notification events, fired at the {{domxref("ServiceWorkerGlobalScope")}} object, implement the `NotificationEvent` interface. Non-persistent notification events, fired at the {{domxref("Notification")}} object, implement the `Event` interface.
{{InheritanceDiagram}}
## Constructor
- {{domxref("NotificationEvent.NotificationEvent","NotificationEvent()")}}
- : Creates a new `NotificationEvent` object.
## Instance properties
_Also inherits properties from its parent interface, {{domxref("ExtendableEvent")}}_.
- {{domxref("NotificationEvent.notification")}} {{ReadOnlyInline}}
- : Returns a {{domxref("Notification")}} object representing the notification that was clicked to fire the event.
- {{domxref("NotificationEvent.action")}} {{ReadOnlyInline}}
- : Returns the string ID of the notification button the user clicked. This value returns an empty string if the user clicked the notification somewhere other than an action button, or the notification does not have a button.
## Instance methods
_Also inherits methods from its parent interface, {{domxref("ExtendableEvent")}}_.
## Example
```js
self.addEventListener("notificationclick", (event) => {
console.log(`On notification click: ${event.notification.tag}`);
event.notification.close();
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(
clients
.matchAll({
type: "window",
})
.then((clientList) => {
for (const client of clientList) {
if (client.url === "/" && "focus" in client) return client.focus();
}
if (clients.openWindow) return clients.openWindow("/");
}),
);
});
```
## Specifications
{{Specifications}}
> **Note:** This interface is specified in the [Notifications API](/en-US/docs/Web/API/Notifications_API), but accessed through {{domxref("ServiceWorkerGlobalScope")}}.
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/notificationevent | data/mdn-content/files/en-us/web/api/notificationevent/action/index.md | ---
title: "NotificationEvent: action property"
short-title: action
slug: Web/API/NotificationEvent/action
page-type: web-api-instance-property
browser-compat: api.NotificationEvent.action
---
{{APIRef("Web Notifications")}}
The **`action`** read-only property of the {{domxref("NotificationEvent")}} interface returns the string ID of the notification button the user clicked. This value returns an empty string if the user clicked the notification somewhere other than an action button, or the notification does not have a button. The notification id is set during the creation of the Notification via the actions array attribute and can't be modified unless the notification is replaced.
## Value
A string.
## Examples
```js
self.registration.showNotification("New articles available", {
actions: [{ action: "get", title: "Get now." }],
});
self.addEventListener(
"notificationclick",
(event) => {
event.notification.close();
if (event.action === "get") {
synchronizeReader();
} else {
clients.openWindow("/reader");
}
},
false,
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/notificationevent | data/mdn-content/files/en-us/web/api/notificationevent/notificationevent/index.md | ---
title: "NotificationEvent: NotificationEvent() constructor"
short-title: NotificationEvent()
slug: Web/API/NotificationEvent/NotificationEvent
page-type: web-api-constructor
browser-compat: api.NotificationEvent.NotificationEvent
---
{{APIRef("Web Notifications")}}
The **`NotificationEvent()`** constructor creates a new {{domxref("NotificationEvent")}} object.
## Syntax
```js-nolint
new NotificationEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers set it to `notificationclick` or `notificationclose`.
- `options`
- : An object that, _in addition of the properties defined in {{domxref("ExtendableEvent/ExtendableEvent", "ExtendableEvent()")}}_, can have the following properties:
- `notification`
- : A {{domxref("Notification")}} object to be used as the notification the event is dispatched on.
- `action` {{optional_inline}}
- : An action associated with the notification. It defaults to `""`.
### Return value
A new {{domxref("NotificationEvent()")}} object.
## Examples
```js
const n = new Notification("Hello");
const myNotificationEvent = new NotificationEvent(type, { notification: n });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/notificationevent | data/mdn-content/files/en-us/web/api/notificationevent/notification/index.md | ---
title: "NotificationEvent: notification property"
short-title: notification
slug: Web/API/NotificationEvent/notification
page-type: web-api-instance-property
browser-compat: api.NotificationEvent.notification
---
{{APIRef("Web Notifications")}}
The **`notification`** read-only property of the {{domxref("NotificationEvent")}} interface returns the instance of the {{domxref("Notification")}} that was clicked to fire the event. The {{domxref("Notification")}} provides read-only access to many properties that were set at the instantiation time of the Notification such as `tag` and `data` attributes that allow you to store information for deferred use in the `notificationclick` event.
## Value
A {{domxref("Notification")}} object.
## Examples
```js
self.addEventListener("notificationclick", (event) => {
console.log("On notification click");
// Data can be attached to the notification so that you
// can process it in the notificationclick handler.
console.log(`Notification Tag: ${event.notification.tag}`);
console.log(`Notification Data: ${event.notification.data}`);
event.notification.close();
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(
clients
.matchAll({
type: "window",
})
.then((clientList) => {
for (const client of clientList) {
if (client.url === "/" && "focus" in client) return client.focus();
}
if (clients.openWindow) return clients.openWindow("/");
}),
);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/midiconnectionevent/index.md | ---
title: MIDIConnectionEvent
slug: Web/API/MIDIConnectionEvent
page-type: web-api-interface
browser-compat: api.MIDIConnectionEvent
---
{{securecontext_header}}{{APIRef("Web MIDI API")}}
The **`MIDIConnectionEvent`** interface of the [Web MIDI API](/en-US/docs/Web/API/Web_MIDI_API) is the event passed to the {{domxref("MIDIAccess.statechange_event","statechange")}} event of the {{domxref("MIDIAccess")}} interface and the {{domxref("MIDIPort.statechange_event","statechange")}} event of the {{domxref("MIDIPort")}} interface. This occurs any time a new port becomes available, or when a previously available port becomes unavailable. For example, this event is fired whenever a MIDI device is either plugged in to or unplugged from a computer.
{{InheritanceDiagram}}
## Constructor
- {{domxref("MIDIConnectionEvent.MIDIConnectionEvent", "MIDIConnectionEvent()")}}
- : Creates a new `MIDIConnectionEvent` object.
## Instance properties
- {{domxref("MIDIConnectionEvent.port")}} {{ReadOnlyInline}}
- : Returns a reference to a {{domxref("MIDIPort")}} instance for a port that has been connected or disconnected.
## Examples
The {{domxref("Navigator.requestMIDIAccess()")}} method returns a promise that resolves with a {{domxref("MIDIAccess")}} object. When a port changes state, a `MIDIConnectionEvent` is passed to {{domxref("MIDIAccess.statechange_event", "statechange")}} event. Information about the port can then be printed to the console.
```js
navigator.requestMIDIAccess().then((access) => {
access.onstatechange = (event) => {
console.log(event.port.name, event.port.manufacturer, event.port.state);
};
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/midiconnectionevent | data/mdn-content/files/en-us/web/api/midiconnectionevent/port/index.md | ---
title: "MIDIConnectionEvent: port property"
short-title: port
slug: Web/API/MIDIConnectionEvent/port
page-type: web-api-instance-property
browser-compat: api.MIDIConnectionEvent.port
---
{{securecontext_header}}{{APIRef("Web MIDI API")}}
The **`port`** read-only property of the {{domxref("MIDIConnectionEvent")}} interface returns the port that has been disconnected or connected.
## Value
A {{domxref("MIDIPort")}} object.
## Examples
The {{domxref("Navigator.requestMIDIAccess()")}} method returns a promise that resolves with a {{domxref("MIDIAccess")}} object. When a port changes state, a `MIDIConnectionEvent` is passed to the {{domxref("MIDIAccess.statechange_event","statechange")}} event. Information about the port can then be printed to the console.
```js
navigator.requestMIDIAccess().then((access) => {
access.onstatechange = (event) => {
console.log(event.port.name, event.port.manufacturer, event.port.state);
};
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/midiconnectionevent | data/mdn-content/files/en-us/web/api/midiconnectionevent/midiconnectionevent/index.md | ---
title: "MIDIConnectionEvent: MIDIConnectionEvent() constructor"
short-title: MIDIConnectionEvent()
slug: Web/API/MIDIConnectionEvent/MIDIConnectionEvent
page-type: web-api-constructor
browser-compat: api.MIDIConnectionEvent.MIDIConnectionEvent
---
{{securecontext_header}}{{APIRef("Web MIDI API")}}
The **`MIDIConnectionEvent()`** constructor creates a new {{domxref("MIDIConnectionEvent")}} object. Typically this constructor is not used as events are created when a new port becomes available, and the object is passed to the {{domxref("MIDIAccess.statechange_event", "statechange")}} event.
## Syntax
```js-nolint
new MIDIConnectionEvent(type)
new MIDIConnectionEvent(type, midiConnectionEventInit)
```
### Parameters
- `type`
- : A string with one of `"connect"` or `"disconnect"`.
- `midiConnectionEventInit` {{optional_inline}}
- : A dictionary including the following fields:
- `port`
- : The {{domxref("MIDIPort")}} instance representing the port that has connected or disconnected.
- `bubbles` {{optional_inline}}
- : A boolean value indicating whether the event bubbles. The default is
`false`.
- `cancelable` {{optional_inline}}
- : A boolean value indicating whether the event can be cancelled. The
default is `false`.
- `composed` {{optional_inline}}
- : A boolean value indicating whether the event will trigger listeners
outside of a shadow root (see {{domxref("Event.composed")}} for more details). The
default is `false`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgpatternelement/index.md | ---
title: SVGPatternElement
slug: Web/API/SVGPatternElement
page-type: web-api-interface
browser-compat: api.SVGPatternElement
---
{{APIRef("SVG")}}
The **`SVGPatternElement`** interface corresponds to the {{SVGElement("pattern")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface also inherits properties from its parent, {{domxref("SVGElement")}}._
- {{domxref("SVGPatternElement.href")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("href")}} or {{SVGAttr("xlink:href")}} {{deprecated_inline}} attribute of the given {{SVGElement("pattern")}} element.
- {{domxref("SVGPatternElement.patternUnits")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("patternUnits")}} attribute of the given {{SVGElement("pattern")}} element. Takes one of the constants defined in {{domxref("SVGUnitTypes")}}.
- {{domxref("SVGPatternElement.patternContentUnits")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("patternContentUnits")}} attribute of the given {{SVGElement("pattern")}} element. Takes one of the constants defined in {{domxref("SVGUnitTypes")}}.
- {{domxref("SVGPatternElement.patternTransform")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedTransformList")}} corresponding to the {{SVGAttr("patternTransform")}} attribute of the given {{SVGElement("pattern")}} element.
- {{domxref("SVGPatternElement.x")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("x")}} attribute of the given {{SVGElement("pattern")}} element.
- {{domxref("SVGPatternElement.y")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("y")}} attribute of the given {{SVGElement("pattern")}} element.
- {{domxref("SVGPatternElement.width")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("width")}} attribute of the given {{SVGElement("pattern")}} element.
- {{domxref("SVGPatternElement.height")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("height")}} attribute of the given {{SVGElement("pattern")}} element.
## Instance methods
_This interface doesn't implement any specific methods, but inherits methods from its parent interface, {{domxref("SVGElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/taskprioritychangeevent/index.md | ---
title: TaskPriorityChangeEvent
slug: Web/API/TaskPriorityChangeEvent
page-type: web-api-interface
browser-compat: api.TaskPriorityChangeEvent
---
{{APIRef("Prioritized Task Scheduling API")}}
The **`TaskPriorityChangeEvent`** is the interface for the [`prioritychange`](/en-US/docs/Web/API/TaskSignal/prioritychange_event) event.
{{InheritanceDiagram}}
## Constructor
- {{domxref("TaskPriorityChangeEvent.TaskPriorityChangeEvent", "TaskPriorityChangeEvent()")}}
- : Creates a new `TaskPriorityChangeEvent` object, setting an event name and previous priority.
## Instance properties
_This interface also inherits the properties of its parent, {{domxref("Event")}}._
- {{domxref("TaskPriorityChangeEvent.previousPriority")}} {{ReadOnlyInline}}
- : Returns the [priority](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#task_priorities) of the corresponding {{domxref("TaskSignal")}} _before_ this [`prioritychange`](/en-US/docs/Web/API/TaskSignal/prioritychange_event) event.
## Instance methods
_This interface has no methods of its own, but inherits the methods of its parent, {{domxref("Event")}}._
## Examples
An object of this type is returned in the handler for a `prioritychange` event.
The code below shows a handler in which the `newPriority` and `previousPriority` are logged.
```js
// Listen for 'prioritychange' events on the controller's signal.
controller.signal.addEventListener("prioritychange", (event) => {
const previousPriority = event.previousPriority;
const newPriority = event.target.priority;
console.log(`Priority changed from ${previousPriority} to ${newPriority}.`);
});
```
A more complete live example can be found in [`prioritychange` event > Examples](/en-US/docs/Web/API/TaskSignal/prioritychange_event).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`prioritychange`](/en-US/docs/Web/API/TaskSignal/prioritychange_event) event
| 0 |
data/mdn-content/files/en-us/web/api/taskprioritychangeevent | data/mdn-content/files/en-us/web/api/taskprioritychangeevent/previouspriority/index.md | ---
title: "TaskPriorityChangeEvent: previousPriority property"
short-title: previousPriority
slug: Web/API/TaskPriorityChangeEvent/previousPriority
page-type: web-api-instance-property
browser-compat: api.TaskPriorityChangeEvent.previousPriority
---
{{APIRef("Prioritized Task Scheduling API")}}
The readonly **`previousPriority`** property of the {{domxref("TaskPriorityChangeEvent")}} interface returns the priority of the corresponding {{domxref("TaskSignal")}} before it was changed and this [`prioritychange`](/en-US/docs/Web/API/TaskSignal/prioritychange_event) event was emitted.
This is the value that was set in the [`TaskPriorityChangeEvent` constructor](/en-US/docs/Web/API/TaskPriorityChangeEvent/TaskPriorityChangeEvent) argument `options.previous`. <!-- link? -->
The new priority of the task can be read from `event.target.priority`.
## Value
A string, indicating the associated task's priority before it was changed.
This will be one of: [`"user-blocking"`](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#user-blocking), [`"user-visible"`](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#user-visible), [`"background"`](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#background).
## Examples
The code below shows the `previousPriority` being obtained in a handler for a `prioritychange` event.
```js
// Listen for 'prioritychange' events on the controller's signal.
controller.signal.addEventListener("prioritychange", (event) => {
const previousPriority = event.previousPriority;
const newPriority = event.target.priority;
console.log(
`The priority changed from ${previousPriority} to ${newPriority}.`,
);
});
```
A more complete live example can be found in [`prioritychange` event > Examples](/en-US/docs/Web/API/TaskSignal/prioritychange_event).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/taskprioritychangeevent | data/mdn-content/files/en-us/web/api/taskprioritychangeevent/taskprioritychangeevent/index.md | ---
title: "TaskPriorityChangeEvent: TaskPriorityChangeEvent() constructor"
short-title: TaskPriorityChangeEvent()
slug: Web/API/TaskPriorityChangeEvent/TaskPriorityChangeEvent
page-type: web-api-constructor
browser-compat: api.TaskPriorityChangeEvent.TaskPriorityChangeEvent
---
{{APIRef("Prioritized Task Scheduling API")}}
The **`TaskPriorityChangeEvent()`** constructor creates a new {{domxref("TaskPriorityChangeEvent")}} object.
This object is created with a value indicating the [previous priority](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#task_priorities) of the task: the priority before it changed and this event was fired.
## Syntax
```js-nolint
new TaskPriorityChangeEvent(type, options)
```
### Parameters
- `type`
- : A string with the case-sensitive name of the associated event.
User agents set it to `"prioritychange"`.
- `options`
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties:
- `previousPriority`
- : A string indicating the _previous_ [priority](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#task_priorities) of the task.
One of: [`"user-blocking"`](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#user-blocking), [`"user-visible"`](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#user-visible), [`"background"`](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#background).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/csslayerstatementrule/index.md | ---
title: CSSLayerStatementRule
slug: Web/API/CSSLayerStatementRule
page-type: web-api-interface
browser-compat: api.CSSLayerStatementRule
---
{{APIRef("CSSOM")}}
The **`CSSLayerStatementRule`** represents a {{cssxref("@layer")}} statement rule. Unlike {{domxref("CSSLayerBlockRule")}}, it doesn't contain other rules and merely defines one or several layers by providing their names.
This rule allows to explicitly declare the ordering layer that is in an apparent way at the beginning of a CSS file: the layer order is defined by the order of first occurrence of each layer name. Declaring them with a statement allows the reader to understand the layer order. It also allows inline and imported layers to be interleaved, which is not possible when using the `CSSLayerBlockRule` syntax.
{{InheritanceDiagram}}
## Instance properties
_Also inherits properties from its parent interface, {{DOMxRef("CSSRule")}}._
- {{DOMxRef("CSSLayerStatementRule.nameList")}} {{ReadOnlyInline}}
- An array of strings, that represent the name of each cascade layer by the rule
## Examples
### HTML
```html
<p></p>
```
### CSS
```css
@layer layerName, layerName2;
```
### JavaScript
```js
const item = document.getElementsByTagName("p")[0];
const rules = document.styleSheets[1].cssRules;
// Note that stylesheet #1 is the stylesheet associated with this embedded example,
// while stylesheet #0 is the stylesheet associated with the whole MDN page
const layer = rules[0]; // A CSSLayerStatementRule
item.textContent = `The CSS @layer statement declares the following layers: ${layer.nameList.join(
", ",
)}.`;
```
### Result
{{EmbedLiveSample("Examples")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{cssxref("@layer")}}
- [The `@layer` statement at-rule for named layers](/en-US/docs/Learn/CSS/Building_blocks/Cascade_layers#the_layer_statement_at-rule_for_named_layers)
- {{DOMxRef("CSSLayerBlockRule")}}
| 0 |
data/mdn-content/files/en-us/web/api/csslayerstatementrule | data/mdn-content/files/en-us/web/api/csslayerstatementrule/namelist/index.md | ---
title: "CSSLayerStatementRule: nameList property"
short-title: nameList
slug: Web/API/CSSLayerStatementRule/nameList
page-type: web-api-instance-property
browser-compat: api.CSSLayerStatementRule.nameList
---
{{APIRef("CSSOM")}}
The read-only **`nameList`** property of the {{DOMxRef("CSSLayerStatementRule")}} interface return the list of associated cascade layer names. The names can't be modified.
## Value
A {{jsxref("Array")}} of strings, each representing a cascade layer represented by the {{cssxref("@layer")}} statement rule.
## Examples
### HTML
```html
<div></div>
```
### CSS
```css
@layer layerName, layerName2;
@layer layerName3 {
div {
font-family: serif;
}
}
```
### JavaScript
```js
const item = document.getElementsByTagName("div")[0];
const rules = document.styleSheets[1].cssRules;
// Note that stylesheet #1 is the stylesheet associated with this embedded example,
// while stylesheet #0 is the stylesheet associated with the whole MDN page
const layerStatementRule = rules[0]; // A CSSLayerStatementRule
const layerBlockRule = rules[1]; // A CSSLayerBlockRule; no nameList property.
item.textContent = `@layer declares the following layers: ${layer.nameList.join(
", ",
)}.`;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{DOMXRef("CSSLayerBlockRule.name")}}
- {{CSSXref("@layer")}}
- [The `@layer` statement at-rule for named layers](/en-US/docs/Learn/CSS/Building_blocks/Cascade_layers#the_layer_statement_at-rule_for_named_layers)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/progressevent/index.md | ---
title: ProgressEvent
slug: Web/API/ProgressEvent
page-type: web-api-interface
browser-compat: api.ProgressEvent
---
{{APIRef("XMLHttpRequest API")}}
The **`ProgressEvent`** interface represents events measuring progress of an underlying process, like an HTTP request (for an `XMLHttpRequest`, or the loading of the underlying resource of an {{HTMLElement("img")}}, {{HTMLElement("audio")}}, {{HTMLElement("video")}}, {{HTMLElement("style")}} or {{HTMLElement("link")}}).
{{InheritanceDiagram}}
## Constructor
- {{domxref("ProgressEvent.ProgressEvent", "ProgressEvent()")}}
- : Creates a `ProgressEvent` event with the given parameters.
## Instance properties
_Also inherits properties from its parent {{domxref("Event")}}_.
- {{domxref("ProgressEvent.lengthComputable")}} {{ReadOnlyInline}}
- : A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not.
- {{domxref("ProgressEvent.loaded")}} {{ReadOnlyInline}}
- : A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead.
- {{domxref("ProgressEvent.total")}} {{ReadOnlyInline}}
- : A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead.
## Instance methods
_Inherits methods from its parent, {{domxref("Event")}}._
## Examples
The following example adds a `ProgressEvent` to a new {{domxref("XMLHTTPRequest")}} and uses it to display the status of the request.
```js
const progressBar = document.getElementById("p"),
client = new XMLHttpRequest();
client.open("GET", "magical-unicorns");
client.onprogress = (pe) => {
if (pe.lengthComputable) {
progressBar.max = pe.total;
progressBar.value = pe.loaded;
}
};
client.onloadend = (pe) => {
progressBar.value = pe.loaded;
};
client.send();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("Event")}} base interface.
| 0 |
data/mdn-content/files/en-us/web/api/progressevent | data/mdn-content/files/en-us/web/api/progressevent/lengthcomputable/index.md | ---
title: "ProgressEvent: lengthComputable property"
short-title: lengthComputable
slug: Web/API/ProgressEvent/lengthComputable
page-type: web-api-instance-property
browser-compat: api.ProgressEvent.lengthComputable
---
{{APIRef("XMLHttpRequest API")}}
The
**`ProgressEvent.lengthComputable`** read-only property is a
boolean flag indicating if the resource concerned by the
{{domxref("ProgressEvent")}} has a length that can be calculated. If not, the
{{domxref("ProgressEvent.total")}} property has no significant value.
## Value
A boolean.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("ProgressEvent")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/progressevent | data/mdn-content/files/en-us/web/api/progressevent/progressevent/index.md | ---
title: "ProgressEvent: ProgressEvent() constructor"
short-title: ProgressEvent()
slug: Web/API/ProgressEvent/ProgressEvent
page-type: web-api-constructor
browser-compat: api.ProgressEvent.ProgressEvent
---
{{APIRef("XMLHttpRequest API")}}
The **`ProgressEvent()`** constructor returns a new {{domxref("ProgressEvent")}} object, representing the current completion of a long process.
## Syntax
```js-nolint
new ProgressEvent(type)
new ProgressEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers set it to `loadstart`, `progress`, `abort`, `error`, `load`, `timeout`, or `loadend`.
- `options` {{optional_inline}}
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties:
- `lengthComputable` {{optional_inline}}
- : A boolean value indicating if the total work to be done, and the
amount of work already done, by the underlying process is calculable. In other words,
it tells if the progress is measurable or not. It defaults to `false`.
- `loaded` {{optional_inline}}
- : A number representing the amount of work already
performed by the underlying process. The ratio of work done can be calculated with the
property and `ProgressEvent.total`. When downloading a resource using HTTP,
this only represent the part of the content itself, not headers and other overhead. It
defaults to `0`.
- `total` {{optional_inline}}
- : A number representing the total amount of work that the
underlying process is in the progress of performing. When downloading a resource using
HTTP, this only represent the content itself, not headers and other overhead. It
defaults to `0`.
### Return value
A new {{domxref("ProgressEvent")}} object.
## Example
The example demonstrates how a `ProgressEvent` is built using a constructor. This is particularly useful for tracking the progress of processes like file uploads, downloads, or any long-running tasks.
```js
function updateProgress(loaded, total) {
const progressEvent = new ProgressEvent("progress", {
lengthComputable: true,
loaded: loaded,
total: total,
});
document.dispatchEvent(progressEvent);
}
document.addEventListener("progress", (event) => {
console.log(`Progress: ${event.loaded}/${event.total}`);
});
updateProgress(50, 100);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("ProgressEvent")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/progressevent | data/mdn-content/files/en-us/web/api/progressevent/loaded/index.md | ---
title: "ProgressEvent: loaded property"
short-title: loaded
slug: Web/API/ProgressEvent/loaded
page-type: web-api-instance-property
browser-compat: api.ProgressEvent.loaded
---
{{APIRef("XMLHttpRequest API")}}
The **`ProgressEvent.loaded`** read-only property is an integer
representing the amount of work already performed by the underlying process. The ratio
of work done can be calculated with the property and `ProgressEvent.total`.
When downloading a resource using HTTP, this value is specified in bytes (not bits), and only represents the part of the content
itself, not headers and other overhead.
## Value
A number.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("ProgressEvent")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/progressevent | data/mdn-content/files/en-us/web/api/progressevent/total/index.md | ---
title: "ProgressEvent: total property"
short-title: total
slug: Web/API/ProgressEvent/total
page-type: web-api-instance-property
browser-compat: api.ProgressEvent.total
---
{{APIRef("XMLHttpRequest API")}}
The **`ProgressEvent.total`** read-only property is an unsigned
64-bit integer value indicating the total size of the data being processed or
transmitted. In the case of an HTTP transmission, this is the size of the body of the
message (the `Content-Length`), and does not include headers and other
overhead.
If the event's {{domxref("ProgressEvent.lengthComputable", "lengthComputable")}}
property is `false`, this value is meaningless and should be ignored.
## Value
An integer.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("ProgressEvent")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgevent/index.md | ---
title: SVGEvent
slug: Web/API/SVGEvent
page-type: web-api-interface
---
{{deprecated_header}}{{APIRef("SVG")}}
The {{domxref("SVGEvent")}} interface represents the event object for most SVG-related events.
## Instance properties
| Property | Type | Description |
| ------------------------------- | -------------------------- | ------------------------------------------------------ |
| `target` {{ReadOnlyInline}} | {{domxref("EventTarget")}} | The event target (the topmost target in the DOM tree). |
| `type` {{ReadOnlyInline}} | string | The type of event. |
| `bubbles` {{ReadOnlyInline}} | A boolean value | Whether the event normally bubbles or not. |
| `cancelable` {{ReadOnlyInline}} | A boolean value | Whether the event is cancellable or not. |
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/webglshader/index.md | ---
title: WebGLShader
slug: Web/API/WebGLShader
page-type: web-api-interface
browser-compat: api.WebGLShader
---
{{APIRef("WebGL")}}
The **WebGLShader** is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and can either be a vertex or a fragment shader. A {{domxref("WebGLProgram")}} requires both types of shaders.
{{InheritanceDiagram}}
## Description
To create a **WebGLShader** use {{domxref("WebGLRenderingContext.createShader")}}, then hook up the GLSL source code using {{domxref("WebGLRenderingContext.shaderSource()")}}, and finally invoke {{domxref("WebGLRenderingContext.compileShader()")}} to finish and compile the shader. At this point the **WebGLShader** is still not in a usable form and must still be attached to a {{domxref("WebGLProgram")}}.
```js
function createShader(gl, sourceCode, type) {
// Compiles either a shader of type gl.VERTEX_SHADER or gl.FRAGMENT_SHADER
const shader = gl.createShader(type);
gl.shaderSource(shader, sourceCode);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
const info = gl.getShaderInfoLog(shader);
throw `Could not compile WebGL program. \n\n${info}`;
}
return shader;
}
```
See {{domxref("WebGLProgram")}} for information on attaching the shaders.
## Examples
### Creating a vertex shader
Note that there are many other strategies for writing and accessing shader source code strings. These example are for illustration purposes only.
```js
const vertexShaderSource =
"attribute vec4 position;\n" +
"void main() {\n" +
" gl_Position = position;\n" +
"}\n";
//Use the createShader function from the example above
const vertexShader = createShader(gl, vertexShaderSource, gl.VERTEX_SHADER);
```
### Creating a fragment shader
```js
const fragmentShaderSource =
"void main() {\n" + " gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n" + "}\n";
//Use the createShader function from the example above
const fragmentShader = createShader(
gl,
fragmentShaderSource,
gl.FRAGMENT_SHADER,
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("WebGLProgram")}}
- {{domxref("WebGLRenderingContext.attachShader()")}}
- {{domxref("WebGLRenderingContext.bindAttribLocation()")}}
- {{domxref("WebGLRenderingContext.compileShader()")}}
- {{domxref("WebGLRenderingContext.createProgram()")}}
- {{domxref("WebGLRenderingContext.createShader()")}}
- {{domxref("WebGLRenderingContext.deleteProgram()")}}
- {{domxref("WebGLRenderingContext.deleteShader()")}}
- {{domxref("WebGLRenderingContext.detachShader()")}}
- {{domxref("WebGLRenderingContext.getAttachedShaders()")}}
- {{domxref("WebGLRenderingContext.getProgramParameter()")}}
- {{domxref("WebGLRenderingContext.getProgramInfoLog()")}}
- {{domxref("WebGLRenderingContext.getShaderParameter()")}}
- {{domxref("WebGLRenderingContext.getShaderPrecisionFormat()")}}
- {{domxref("WebGLRenderingContext.getShaderInfoLog()")}}
- {{domxref("WebGLRenderingContext.getShaderSource()")}}
- {{domxref("WebGLRenderingContext.isProgram()")}}
- {{domxref("WebGLRenderingContext.isShader()")}}
- {{domxref("WebGLRenderingContext.linkProgram()")}}
- {{domxref("WebGLRenderingContext.shaderSource()")}}
- {{domxref("WebGLRenderingContext.useProgram()")}}
- {{domxref("WebGLRenderingContext.validateProgram()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/formdataevent/index.md | ---
title: FormDataEvent
slug: Web/API/FormDataEvent
page-type: web-api-interface
browser-compat: api.FormDataEvent
---
{{APIRef("DOM")}}
The **`FormDataEvent`** interface represents a [`formdata` event](/en-US/docs/Web/API/HTMLFormElement/formdata_event) — such an event is fired on an {{domxref("HTMLFormElement")}} object after the entry list representing the form's data is constructed. This happens when the form is submitted, but can also be triggered by the invocation of a {{domxref("FormData.FormData", "FormData()")}} constructor.
This allows a {{domxref("FormData")}} object to be quickly obtained in response to a `formdata` event firing, rather than needing to put it together yourself when you wish to submit form data via a method like {{domxref("fetch()")}} (see [Using FormData objects](/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects)).
{{InheritanceDiagram}}
## Constructor
- {{domxref("FormDataEvent.FormDataEvent","FormDataEvent()")}}
- : Creates a new `FormDataEvent` object instance.
## Instance properties
_Inherits properties from its parent interface, {{domxref("Event")}}._
- {{domxref("FormDataEvent.formData")}}
- : Contains the {{domxref("FormData")}} object representing the data contained in the form when the event was fired.
## Instance methods
_Inherits methods from its parent interface, {{domxref("Event")}}._
## Examples
```js
// grab reference to form
const formElem = document.querySelector("form");
// submit handler
formElem.addEventListener("submit", (e) => {
// on form submission, prevent default
e.preventDefault();
console.log(form.querySelector('input[name="field1"]')); // FOO
console.log(form.querySelector('input[name="field2"]')); // BAR
// construct a FormData object, which fires the formdata event
const formData = new FormData(formElem);
// formdata gets modified by the formdata event
console.log(formData.get("field1")); // foo
console.log(formData.get("field2")); // bar
});
// formdata handler to retrieve data
formElem.addEventListener("formdata", (e) => {
console.log("formdata fired");
// modifies the form data
const formData = e.formData;
formData.set("field1", formData.get("field1").toLowerCase());
formData.set("field2", formData.get("field2").toLowerCase());
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("fetch()")}}
- {{domxref("FormData")}}
- [Using FormData objects](/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects)
- {{HTMLElement("Form")}}
| 0 |
data/mdn-content/files/en-us/web/api/formdataevent | data/mdn-content/files/en-us/web/api/formdataevent/formdataevent/index.md | ---
title: "FormDataEvent: FormDataEvent() constructor"
short-title: FormDataEvent()
slug: Web/API/FormDataEvent/FormDataEvent
page-type: web-api-constructor
browser-compat: api.FormDataEvent.FormDataEvent
---
{{APIRef("DOM")}}
The **`FormDataEvent()`** constructor creates a new {{domxref("FormDataEvent")}} object.
## Syntax
```js-nolint
new FormDataEvent(type, formEventInit)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers always set it to `formdata`.
- `options`
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties:
- `formData`
- : A {{domxref("FormData")}} object to pre-populate the {{domxref("FormDataEvent")}} with.
This would then be accessed through the {{domxref("FormDataEvent.formData")}} property.
### Return value
A new {{domxref("FormDataEvent")}} object.
## Examples
```js
const fd = new FormData();
fd.append("test", "test");
const fdEv = new FormDataEvent("formdata", { formData: fd });
for (const value of fdEv.formData.values()) {
console.log(value);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("FormDataEvent")}}
| 0 |
data/mdn-content/files/en-us/web/api/formdataevent | data/mdn-content/files/en-us/web/api/formdataevent/formdata/index.md | ---
title: "FormDataEvent: formData property"
short-title: formData
slug: Web/API/FormDataEvent/formData
page-type: web-api-instance-property
browser-compat: api.FormDataEvent.formData
---
{{APIRef("DOM")}}
The `formData` read-only property of the {{domxref("FormDataEvent")}}
interface contains the {{domxref("FormData")}} object representing the data contained in
the form when the event was fired.
## Value
A {{domxref("FormData")}} object.
## Examples
```js
// grab reference to form
const formElem = document.querySelector("form");
// submit handler
formElem.addEventListener("submit", (e) => {
// on form submission, prevent default
e.preventDefault();
// construct a FormData object, which fires the formdata event
new FormData(formElem);
});
// formdata handler to retrieve data
formElem.addEventListener("formdata", (e) => {
console.log("formdata fired");
// Get the form data from the event object
let data = e.formData;
for (const value of data.values()) {
console.log(value);
}
// submit the data via XHR
const request = new XMLHttpRequest();
request.open("POST", "/formHandler");
request.send(data);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XMLHTTPRequest")}}
- [Using XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest)
- [Using FormData objects](/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects)
- {{HTMLElement("Form")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/gpubuffer/index.md | ---
title: GPUBuffer
slug: Web/API/GPUBuffer
page-type: web-api-interface
status:
- experimental
browser-compat: api.GPUBuffer
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`GPUBuffer`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} represents a block of memory that can be used to store raw data to use in GPU operations.
A `GPUBuffer` object instance is created using the {{domxref("GPUDevice.createBuffer()")}} method.
{{InheritanceDiagram}}
## Instance properties
- {{domxref("GPUBuffer.label", "label")}} {{Experimental_Inline}}
- : A string providing a label that can be used to identify the object, for example in
{{domxref("GPUError")}} messages or console warnings.
- {{domxref("GPUBuffer.mapState", "mapState")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : An enumerated value representing the mapped state of the `GPUBuffer`.
- {{domxref("GPUBuffer.size", "size")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : A number representing the length of the `GPUBuffer`'s memory allocation, in bytes.
- {{domxref("GPUBuffer.usage", "usage")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : The {{glossary("bitwise flags")}} representing the allowed usages of the `GPUBuffer`.
## Instance methods
- {{domxref("GPUBuffer.destroy", "destroy()")}} {{Experimental_Inline}}
- : Destroys the `GPUBuffer`.
- {{domxref("GPUBuffer.getMappedRange", "getMappedRange()")}} {{Experimental_Inline}}
- : Returns an {{jsxref("ArrayBuffer")}} containing the mapped contents of the `GPUBuffer` in the specified range.
- {{domxref("GPUBuffer.mapAsync", "mapAsync()")}} {{Experimental_Inline}}
- : Maps the specified range of the `GPUBuffer`. Returns a {{jsxref("Promise")}} that resolves when the `GPUBuffer`'s content is ready to be accessed with {{domxref("GPUBuffer.getMappedRange()")}}.
- {{domxref("GPUBuffer.unmap", "unmap()")}} {{Experimental_Inline}}
- : Unmaps the mapped range of the `GPUBuffer`, making its contents available for use by the GPU again.
## Examples
In our [basic compute demo](https://mdn.github.io/dom-examples/webgpu-compute-demo/), we create an output buffer to read GPU calculations to, and a staging buffer to be mapped for JavaScript access.
```js
const output = device.createBuffer({
size: BUFFER_SIZE,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
});
const stagingBuffer = device.createBuffer({
size: BUFFER_SIZE,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
});
```
Later on, once the `stagingBuffer` contains the results of the GPU computation, a combination of `GPUBuffer` methods are used to read the data back to JavaScript so that it can then be logged to the console:
- {{domxref("GPUBuffer.mapAsync()")}} is used to map the `GPUBuffer` for reading.
- {{domxref("GPUBuffer.getMappedRange()")}} is used to return an {{jsxref("ArrayBuffer")}} containing the `GPUBuffer`'s contents.
- {{domxref("GPUBuffer.unmap()")}} is used to unmap the `GPUBuffer` again, once we have read the content into JavaScript as needed.
```js
// map staging buffer to read results back to JS
await stagingBuffer.mapAsync(
GPUMapMode.READ,
0, // Offset
BUFFER_SIZE, // Length
);
const copyArrayBuffer = stagingBuffer.getMappedRange(0, BUFFER_SIZE);
const data = copyArrayBuffer.slice(0);
stagingBuffer.unmap();
console.log(new Float32Array(data));
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
| 0 |
data/mdn-content/files/en-us/web/api/gpubuffer | data/mdn-content/files/en-us/web/api/gpubuffer/usage/index.md | ---
title: "GPUBuffer: usage property"
short-title: usage
slug: Web/API/GPUBuffer/usage
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GPUBuffer.usage
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`usage`** read-only property of the
{{domxref("GPUBuffer")}} interface contains the {{glossary("bitwise flags")}} representing the allowed usages of the `GPUBuffer`.
`usage` is set via the `usage` property in the descriptor object passed into the originating {{domxref("GPUDevice.createBuffer()")}} call.
## Value
The bitwise flags representing the original usages set when the `GPUBuffer` was first created. The returned number is the sum of decimal values representing the different flags, as seen in the table below.
| Bitwise flag | Usage description | Hex equiv. | Decimal equiv. |
| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | -------------- |
| `GPUBufferUsage.COPY_SRC` | The buffer can be used as the source of a copy operation, for example the source argument of a {{domxref("GPUCommandEncoder.copyBufferToBuffer","copyBufferToBuffer()")}} call. | 0x0004 | 4 |
| `GPUBufferUsage.COPY_DST` | The buffer can be used as the destination of a copy/write operation, for example the destination argument of a {{domxref("GPUCommandEncoder.copyTextureToBuffer", "copyTextureToBuffer()")}} call. | 0x0008 | 8 |
| `GPUBufferUsage.INDEX` | The buffer can be used as an index buffer, for example as the `buffer` argument passed to {{domxref("GPURenderPassEncoder.setIndexBuffer", "setIndexBuffer()")}}. | 0x0010 | 16 |
| `GPUBufferUsage.INDIRECT` | The buffer can be used to store indirect command arguments, for example as the `indirectBuffer` argument of a {{domxref("GPURenderPassEncoder.drawIndirect", "drawIndirect()")}} or {{domxref("GPUComputePassEncoder.dispatchWorkgroupsIndirect", "dispatchWorkgroupsIndirect()")}} call. | 0x0100 | 256 |
| `GPUBufferUsage.MAP_READ` | The buffer can be mapped for reading, for example when calling {{domxref("GPUBuffer.mapAsync", "mapAsync()")}} with a `mode` of `GPUMapMode.READ`. This flag may only be combined with `GPUBufferUsage.COPY_DST`. | 0x0001 | 1 |
| `GPUBufferUsage.MAP_WRITE` | The buffer can be mapped for writing, for example when calling {{domxref("GPUBuffer.mapAsync", "mapAsync()")}} with a `mode` of `GPUMapMode.WRITE`. This flag may only be combined with `GPUBufferUsage.COPY_SRC`. | 0x0002 | 2 |
| `GPUBufferUsage.QUERY_RESOLVE` | The buffer can be used to capture query results, for example as the destination argument of a {{domxref("GPUCommandEncoder.resolveQuerySet", "resolveQuerySet()")}} call. | 0x0200 | 512 |
| `GPUBufferUsage.STORAGE` | The buffer can be used as a storage buffer, for example as a resource in a bind group entry when creating a {{domxref("GPUBindGroup")}} (via {{domxref("GPUDevice.createBindGroup", "createBindGroup()")}}), which adheres to a {{domxref("GPUBindGroupLayout")}} entry with a buffer binding layout `type` of `"storage"` or `"read-only-storage"`. | 0x0080 | 128 |
| `GPUBufferUsage.UNIFORM` | The buffer can be used as a uniform buffer, for example as a resource in a bind group entry when creating a {{domxref("GPUBindGroup")}} (via {{domxref("GPUDevice.createBindGroup", "createBindGroup()")}}), which adheres to a {{domxref("GPUBindGroupLayout")}} entry with a buffer binding layout `type` of `"uniform"`. | 0x0040 | 64 |
| `GPUBufferUsage.VERTEX` | The buffer can be used as a vertex buffer, for example as the `buffer` argument passed to {{domxref("GPURenderPassEncoder.setVertexBuffer", "setVertexBuffer()")}}. | 0x0020 | 32 |
## Examples
```js
const output = device.createBuffer({
size: BUFFER_SIZE,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
});
console.log(output.usage); // 132
const stagingBuffer = device.createBuffer({
size: BUFFER_SIZE,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
});
console.log(stagingBuffer.usage); // 9
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
| 0 |
data/mdn-content/files/en-us/web/api/gpubuffer | data/mdn-content/files/en-us/web/api/gpubuffer/getmappedrange/index.md | ---
title: "GPUBuffer: getMappedRange() method"
short-title: getMappedRange()
slug: Web/API/GPUBuffer/getMappedRange
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPUBuffer.getMappedRange
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`getMappedRange()`** method of the
{{domxref("GPUBuffer")}} interface returns an {{jsxref("ArrayBuffer")}} containing the mapped contents of the `GPUBuffer` in the specified range.
This can only happen once the `GPUBuffer` has been successfully mapped with {{domxref("GPUBuffer.mapAsync()")}} (this can be checked via {{domxref("GPUBuffer.mapState")}}). While the `GPUBuffer` is mapped it cannot be used in any GPU commands.
When you have finished working with the `GPUBuffer` values, call {{domxref("GPUBuffer.unmap()")}} to unmap it, making it accessible to the GPU again.
## Syntax
```js-nolint
getMappedRange()
getMappedRange(offset)
getMappedRange(offset, size)
```
### Parameters
- `offset` {{optional_inline}}
- : A number representing the offset, in bytes, from the start of the `GPUBuffer`'s mapped range to the start of the range to be returned in the {{jsxref("ArrayBuffer")}}. If `offset` is omitted, it defaults to 0.
- `size` {{optional_inline}}
- : A number representing the size, in bytes, of the {{jsxref("ArrayBuffer")}} to return. If `size` is omitted, the range extends to the end of the `GPUBuffer`'s mapped range.
### Return value
An {{jsxref("ArrayBuffer")}}.
### Validation
The following criteria must be met when calling **`getMappedRange()`**, otherwise an `OperationError` {{domxref("DOMException")}} is thrown:
- `offset` is a multiple of 8.
- The total range to be mapped (`size` if specified, or mapped range length - `offset` if not) is a multiple of 4.
- The total range is inside the bounds of the mapped range and does not overlap with the {{jsxref("ArrayBuffer")}} ranges specified by any other active `getMappedRange()` calls.
### Exceptions
- `TypeError` {{domxref("DOMException")}}
- : Thrown if an attempt is made to detach the {{jsxref("ArrayBuffer")}} in any way other than via {{domxref("GPUBuffer.unmap()")}}.
## Examples
See the [main `GPUBuffer` page](/en-US/docs/Web/API/GPUBuffer#examples) for an example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
| 0 |
data/mdn-content/files/en-us/web/api/gpubuffer | data/mdn-content/files/en-us/web/api/gpubuffer/mapstate/index.md | ---
title: "GPUBuffer: mapState property"
short-title: mapState
slug: Web/API/GPUBuffer/mapState
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GPUBuffer.mapState
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`mapState`** read-only property of the
{{domxref("GPUBuffer")}} interface represents the mapped state of the `GPUBuffer`.
## Value
An enumerated value. Possible values are:
- `unmapped`
- : The buffer is not mapped. {{domxref("GPUBuffer.getMappedRange()")}} cannot be used to access the contents of the `GPUBuffer` in JavaScript. This could be because:
- {{domxref("GPUBuffer.mapAsync()")}} has not yet been called.
- The `GPUBuffer` was previously mapped, and then unmapped again with {{domxref("GPUBuffer.unmap()")}}.
- `pending`
- : The buffer is not yet mapped. {{domxref("GPUBuffer.mapAsync()")}} has been called, but its {{jsxref("Promise")}} is currently pending. {{domxref("GPUBuffer.getMappedRange()")}} cannot currently be used to access the contents of the `GPUBuffer` in JavaScript.
- `mapped`
- : The buffer is mapped. The {{domxref("GPUBuffer.mapAsync()")}} {{jsxref("Promise")}} has fulfilled, and {{domxref("GPUBuffer.getMappedRange()")}} can now be used to access the contents of the `GPUBuffer` in JavaScript.
## Examples
```js
const stagingBuffer = device.createBuffer({
size: BUFFER_SIZE,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
});
console.log(stagingBuffer.mapState); // "unmapped"
// ...
await stagingBuffer.mapAsync(
GPUMapMode.READ,
0, // Offset
BUFFER_SIZE, // Length
);
console.log(stagingBuffer.mapState); // "mapped"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
| 0 |
data/mdn-content/files/en-us/web/api/gpubuffer | data/mdn-content/files/en-us/web/api/gpubuffer/size/index.md | ---
title: "GPUBuffer: size property"
short-title: size
slug: Web/API/GPUBuffer/size
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GPUBuffer.size
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`size`** read-only property of the
{{domxref("GPUBuffer")}} interface represents the length of the `GPUBuffer`'s memory allocation, in bytes.
`size` is set via the `size` property in the descriptor object passed into the originating {{domxref("GPUDevice.createBuffer()")}} call.
## Value
A number.
## Examples
```js
// Define global buffer size
const BUFFER_SIZE = 1000;
// ...
const output = device.createBuffer({
size: BUFFER_SIZE,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
});
console.log(output.size); // 1000
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
| 0 |
data/mdn-content/files/en-us/web/api/gpubuffer | data/mdn-content/files/en-us/web/api/gpubuffer/destroy/index.md | ---
title: "GPUBuffer: destroy() method"
short-title: destroy()
slug: Web/API/GPUBuffer/destroy
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPUBuffer.destroy
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`destroy()`** method of the
{{domxref("GPUBuffer")}} interface destroys the `GPUBuffer`.
## Syntax
```js-nolint
destroy()
```
### Parameters
None.
### Return value
None ({{jsxref("Undefined")}}).
## Examples
```js
const output = device.createBuffer({
size: 1000,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
});
// some time later
output.destroy();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
| 0 |
data/mdn-content/files/en-us/web/api/gpubuffer | data/mdn-content/files/en-us/web/api/gpubuffer/label/index.md | ---
title: "GPUBuffer: label property"
short-title: label
slug: Web/API/GPUBuffer/label
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GPUBuffer.label
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`label`** property of the
{{domxref("GPUBuffer")}} interface provides a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings.
This can be set by providing a `label` property in the descriptor object passed into the originating {{domxref("GPUDevice.createBuffer()")}} call, or you can get and set it directly on the `GPUBuffer` object.
## Value
A string. If this has not been previously set as described above, it will be an empty string.
## Examples
Setting and getting a label via `GPUBuffer.label`:
```js
const output = device.createBuffer({
size: BUFFER_SIZE,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
});
output.label = "mybuffer";
console.log(output.label); // "mybuffer"
```
Setting a label via the originating {{domxref("GPUDevice.createBuffer()")}} call, and then getting it via `GPUBuffer.label`:
```js
const output = device.createBuffer({
size: BUFFER_SIZE,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
label: "mybuffer",
});
console.log(output.label); // "mybuffer"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
| 0 |
data/mdn-content/files/en-us/web/api/gpubuffer | data/mdn-content/files/en-us/web/api/gpubuffer/unmap/index.md | ---
title: "GPUBuffer: unmap() method"
short-title: unmap()
slug: Web/API/GPUBuffer/unmap
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPUBuffer.unmap
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`unmap()`** method of the
{{domxref("GPUBuffer")}} interface unmaps the mapped range of the `GPUBuffer`, making its contents available for use by the GPU again after it has previously been mapped with {{domxref("GPUBuffer.mapAsync()")}} (the GPU cannot access a mapped `GPUBuffer`).
When `unmap()` is called, any {{jsxref("ArrayBuffer")}}s created via {{domxref("GPUBuffer.getMappedRange()")}} are detached.
## Syntax
```js-nolint
unmap()
```
### Parameters
None.
### Return value
None ({{jsxref("Undefined")}}).
## Examples
See the [main `GPUBuffer` page](/en-US/docs/Web/API/GPUBuffer#examples) for an example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
| 0 |
data/mdn-content/files/en-us/web/api/gpubuffer | data/mdn-content/files/en-us/web/api/gpubuffer/mapasync/index.md | ---
title: "GPUBuffer: mapAsync() method"
short-title: mapAsync()
slug: Web/API/GPUBuffer/mapAsync
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPUBuffer.mapAsync
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`mapAsync()`** method of the
{{domxref("GPUBuffer")}} interface maps the specified range of the `GPUBuffer`. It returns a {{jsxref("Promise")}} that resolves when the `GPUBuffer`'s content is ready to be accessed. While the `GPUBuffer` is mapped it cannot be used in any GPU commands.
Once the buffer is successfully mapped (which can be checked via {{domxref("GPUBuffer.mapState")}}), calls to {{domxref("GPUBuffer.getMappedRange()")}} will return an {{jsxref("ArrayBuffer")}} containing the `GPUBuffer`'s current values, to be read and updated by JavaScript as required.
When you have finished working with the `GPUBuffer` values, call {{domxref("GPUBuffer.unmap()")}} to unmap it, making it accessible to the GPU again.
## Syntax
```js-nolint
mapAsync(mode)
mapAsync(mode, offset, size)
```
### Parameters
- `mode`
- : A {{glossary("bitwise flags", "bitwise flag")}} that specifies whether the `GPUBuffer` is mapped for reading or writing. Possible values are:
- `GPUMapMode.READ`
- : The `GPUBuffer` is mapped for reading. Values can be read, but any changes made to the {{jsxref("ArrayBuffer")}} returned by {{domxref("GPUBuffer.getMappedRange()")}} will be discarded once {{domxref("GPUBuffer.unmap()")}} is called.
Read-mode mapping can only be used on `GPUBuffer`s that have a usage of `GPUBufferUsage.MAP_READ` set on them (i.e. when created with {{domxref("GPUDevice.createBuffer()")}}).
- `GPUMapMode.WRITE`
- : The `GPUBuffer` is mapped for writing. Values can be read and updated — any changes made to the {{jsxref("ArrayBuffer")}} returned by {{domxref("GPUBuffer.getMappedRange()")}} will be saved to the `GPUBuffer` once {{domxref("GPUBuffer.unmap()")}} is called.
Write-mode mapping can only be used on `GPUBuffer`s that have a usage of `GPUBufferUsage.MAP_WRITE` set on them (i.e. when created with {{domxref("GPUDevice.createBuffer()")}}).
- `offset` {{optional_inline}}
- : A number representing the offset, in bytes, from the start of the buffer to the start of the range to be mapped. If `offset` is omitted, it defaults to 0.
- `size` {{optional_inline}}
- : A number representing the size, in bytes, of the range to be mapped. If `size` is omitted, the range mapped extends to the end of the `GPUBuffer`.
### Return value
A {{jsxref("Promise")}} that resolves to {{jsxref("Undefined")}} when the `GPUBuffer`'s content is ready to be accessed.
### Validation
The following criteria must be met when calling **`mapSync()`**, otherwise an `OperationError` {{domxref("DOMException")}} is thrown, the promise is rejected, and a {{domxref("GPUValidationError")}} is generated:
- `offset` is a multiple of 8.
- The total range to be mapped (`size` if specified, or {{domxref("GPUBuffer.size")}} - `offset` if not) is a multiple of 4.
- The total range to be mapped is inside the bounds of the `GPUBuffer`.
- If mode is `GPUMapMode.READ`, the `GPUBuffer` has a usage of `GPUBufferUsage.MAP_READ`.
- If mode is `GPUMapMode.WRITE`, the `GPUBuffer` has a usage of `GPUBufferUsage.MAP_WRITE`.
## Examples
See the [main `GPUBuffer` page](/en-US/docs/Web/API/GPUBuffer#examples) for an example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/broadcast_channel_api/index.md | ---
title: Broadcast Channel API
slug: Web/API/Broadcast_Channel_API
page-type: web-api-overview
browser-compat: api.BroadcastChannel
---
{{DefaultAPISidebar("Broadcast Channel API")}}
The **Broadcast Channel API** allows basic communication between {{glossary("browsing context", "browsing contexts")}} (that is, _windows_, _tabs_, _frames_, or _iframes_) and workers on the same {{glossary("origin")}}.
{{AvailableInWorkers}}
By creating a {{domxref("BroadcastChannel")}} object, you can receive any messages that are posted to it. You don't have to maintain a reference to the frames or workers you wish to communicate with: they can "subscribe" to a particular channel by constructing their own {{domxref("BroadcastChannel")}} with the same name, and have bi-directional communication between all of them.

## Broadcast Channel interface
### Creating or joining a channel
A client joins a broadcast channel by creating a {{domxref("BroadcastChannel")}} object. Its [constructor](/en-US/docs/Web/API/BroadcastChannel/BroadcastChannel) takes one single parameter: the _name_ of the channel. If it is the first to connect to that broadcast channel name, the underlying channel is created.
```js
// Connection to a broadcast channel
const bc = new BroadcastChannel("test_channel");
```
### Sending a message
It is enough to call the {{domxref("BroadcastChannel.postMessage", "postMessage()")}} method on the created `BroadcastChannel` object, which takes any object as an argument. An example string message:
```js
// Example of sending of a very simple message
bc.postMessage("This is a test message.");
```
Data sent to the channel is serialized using the [structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). That means you can send a broad variety of data objects safely without having to serialize them yourself.
The API doesn't associate any semantics to messages, so it is up to the code to know what kind of messages to expect and what to do with them.
### Receiving a message
When a message is posted, a [`message`](/en-US/docs/Web/API/BroadcastChannel/message_event) event is dispatched to each {{domxref("BroadcastChannel")}} object connected to this channel. A function can be run for this event using the {{domxref("BroadcastChannel/message_event", "onmessage")}} event handler:
```js
// A handler that only logs the event to the console:
bc.onmessage = (event) => {
console.log(event);
};
```
### Disconnecting a channel
To leave a channel, call the {{domxref("BroadcastChannel.close", "close()")}} method on the object. This disconnects the object from the underlying channel, allowing garbage collection.
```js
// Disconnect the channel
bc.close();
```
## Conclusion
The Broadcast Channel API's self-contained interface allows cross-context communication. It can be used to detect user actions in other tabs within a same origin, like when the user logs in or out.
The messaging protocol is not defined and the different browsing contexts need to implement it themselves; there is no negotiation nor requirement from the specification.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("BroadcastChannel")}}, the interface implementing it.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/inkpresenter/index.md | ---
title: InkPresenter
slug: Web/API/InkPresenter
page-type: web-api-interface
status:
- experimental
browser-compat: api.InkPresenter
---
{{APIRef("Ink API")}}{{SeeCompatTable}}
The **`InkPresenter`** interface of the [Ink API](/en-US/docs/Web/API/Ink_API) provides the ability to instruct the OS-level compositor to render ink strokes between pointer event dispatches.
{{InheritanceDiagram}}
## Instance properties
- {{domxref("InkPresenter.expectedImprovement", "expectedImprovement")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : Returns a value, in milliseconds, indicating the latency improvement that can be expected using this presenter.
- {{domxref("InkPresenter.presentationArea", "presentationArea")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : Returns the {{domxref("Element")}} inside which rendering of ink strokes is confined.
## Instance methods
- {{domxref("InkPresenter.updateInkTrailStartPoint", "updateInkTrailStartPoint()")}} {{Experimental_Inline}}
- : Passes the {{domxref("PointerEvent")}} that was used as the last rendering point for the current frame, allowing the OS-level compositor to render a delegated ink trail ahead of the next pointer event being dispatched.
## Example
In this example, we draw a trail onto a 2D canvas. Near the start of the code, we call {{domxref("Ink.requestPresenter()")}}, passing it the canvas as the presentation area for it to take care of and storing the promise it returns in the `presenter` variable.
Later on, in the `pointermove` event listener, the new position of the trailhead is drawn onto the canvas each time the event fires. In addition, the {{domxref("InkPresenter")}} object returned when the `presenter` promise fulfills has its {{domxref("InkPresenter.updateInkTrailStartPoint", "updateInkTrailStartPoint()")}} method invoked; this is passed:
- The last trusted pointer event representing the rendering point for the current frame.
- A `style` object containing color and diameter settings.
The result is that a delegated ink trail is drawn ahead of the default browser rendering on the app's behalf, in the specified style, until the next time it receives a `pointermove` event.
```js
const ctx = canvas.getContext("2d");
let presenter = navigator.ink.requestPresenter({ presentationArea: canvas });
let move_cnt = 0;
let style = { color: "rgb(0 0 255 / 100%)", diameter: 10 };
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
canvas.addEventListener("pointermove", (evt) => {
const pointSize = 10;
ctx.fillStyle = "#000000";
ctx.fillRect(evt.pageX, evt.pageY, pointSize, pointSize);
if (move_cnt == 50) {
let r = getRandomInt(0, 255);
let g = getRandomInt(0, 255);
let b = getRandomInt(0, 255);
style = {
color: "rgb(" + r + " " + g + " " + b + " / 100%)",
diameter: 10,
};
move_cnt = 0;
document.getElementById("div").style.backgroundColor =
"rgb(" + r + " " + g + " " + b + " / 100%)";
}
move_cnt += 1;
presenter.then(function (v) {
v.updateInkTrailStartPoint(evt, style);
});
});
window.addEventListener("pointerdown", (evt) => {
evt.pointerId;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
});
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
```
> **Note:** See this example running live — [Delegated ink trail](https://mabian-ms.github.io/delegated-ink-trail.html).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Enhancing Inking on the Web](https://blogs.windows.com/msedgedev/2021/08/18/enhancing-inking-on-the-web/)
| 0 |
data/mdn-content/files/en-us/web/api/inkpresenter | data/mdn-content/files/en-us/web/api/inkpresenter/expectedimprovement/index.md | ---
title: "InkPresenter: expectedImprovement property"
short-title: expectedImprovement
slug: Web/API/InkPresenter/expectedImprovement
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.InkPresenter.expectedImprovement
---
{{APIRef("Ink API")}}{{SeeCompatTable}}
The **`expectedImprovement`** read-only property of the {{domxref("InkPresenter")}} interface returns a value, in milliseconds, indicating the latency improvement that can be expected using this presenter.
### Value
A number.
## Example
```js
async function inkInit() {
const ink = navigator.ink;
let presenter = await ink.requestPresenter({ presentationArea: canvas });
console.log(presenter.expectedImprovement);
//...
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Enhancing Inking on the Web](https://blogs.windows.com/msedgedev/2021/08/18/enhancing-inking-on-the-web/)
| 0 |
data/mdn-content/files/en-us/web/api/inkpresenter | data/mdn-content/files/en-us/web/api/inkpresenter/presentationarea/index.md | ---
title: "InkPresenter: presentationArea property"
short-title: presentationArea
slug: Web/API/InkPresenter/presentationArea
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.InkPresenter.presentationArea
---
{{APIRef("Ink API")}}{{SeeCompatTable}}
The **`presentationArea`** read-only property of the {{domxref("InkPresenter")}} interface returns the {{domxref("Element")}} inside which rendering of ink strokes is confined.
If the preceding {{domxref("Ink.requestPresenter", "Ink.requestPresenter()")}} method call included a specific `presentationArea` element definition, then that will be the element returned. Otherwise, the default is returned, which is the containing viewport.
This area is always the client coordinates for the element's border box, so moving the element or scrolling the element requires no recalculation on the developer's part.
### Value
An {{domxref("Element")}}.
## Example
```js
async function inkInit() {
const ink = navigator.ink;
let presenter = await ink.requestPresenter({ presentationArea: canvas });
console.log(presenter.presentationArea);
//...
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Enhancing Inking on the Web](https://blogs.windows.com/msedgedev/2021/08/18/enhancing-inking-on-the-web/)
| 0 |
data/mdn-content/files/en-us/web/api/inkpresenter | data/mdn-content/files/en-us/web/api/inkpresenter/updateinktrailstartpoint/index.md | ---
title: "InkPresenter: updateInkTrailStartPoint() method"
short-title: updateInkTrailStartPoint()
slug: Web/API/InkPresenter/updateInkTrailStartPoint
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.InkPresenter.updateInkTrailStartPoint
---
{{APIRef("Ink API")}}{{SeeCompatTable}}
The **`updateInkTrailStartPoint()`** method of the {{domxref("InkPresenter")}} interface indicates which {{domxref("PointerEvent")}} was used as the last rendering point for the current frame, allowing the OS-level compositor to render a delegated ink trail ahead of the next pointer event being dispatched.
## Syntax
```js-nolint
requestPresenter(event, style)
```
### Parameters
- `event` {{optional_inline}}
- : A {{domxref("PointerEvent")}}.
- `style`
- : An object defining the trail style, which contains the following properties:
- `color`
- : A {{jsxref("String")}} containing a valid CSS color code, indicating the color the presenter will use when rendering the ink trail.
- `diameter`
- : A number representing the diameter the presenter will use when rendering the ink trail.
### Return value
`undefined`.
### Exceptions
- `Error` {{domxref("DOMException")}}
- : An error is thrown and the operation is aborted if the:
- `color` property does not contain a valid CSS color code.
- `diameter` property is not a number or less than 1.
- {{domxref("InkPresenter.presentationArea", "presentationArea")}} element is removed from the document before or during rendering.
## Examples
### Drawing an ink trail
In this example, we draw a trail onto a 2D canvas. Near the start of the code, we call {{domxref("Ink.requestPresenter()")}}, passing it the canvas as the presentation area for it to take care of and storing the promise it returns in the `presenter` variable.
Later on, in the `pointermove` event listener, the new position of the trailhead is drawn onto the canvas each time the event fires. In addition, the {{domxref("InkPresenter")}} object returned when the `presenter` promise fulfills has its {{domxref("InkPresenter.updateInkTrailStartPoint", "updateInkTrailStartPoint()")}} method invoked; this is passed:
- The last trusted pointer event representing the rendering point for the current frame.
- A `style` object containing color and diameter settings.
The result is that a delegated ink trail is drawn ahead of the default browser rendering on the app's behalf, in the specified style, until the next time it receives a `pointermove` event.
#### HTML
```html
<canvas id="canvas"></canvas>
<div id="div">Delegated ink trail should match the color of this div.</div>
```
#### CSS
```css
div {
background-color: rgb(0 255 0 / 100%);
position: fixed;
top: 1rem;
left: 1rem;
}
```
#### JavaScript
```js
const ctx = canvas.getContext("2d");
const presenter = navigator.ink.requestPresenter({ presentationArea: canvas });
let move_cnt = 0;
let style = { color: "rgb(0 255 0 / 100%)", diameter: 10 };
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
canvas.addEventListener("pointermove", async (evt) => {
const pointSize = 10;
ctx.fillStyle = style.color;
ctx.fillRect(evt.pageX, evt.pageY, pointSize, pointSize);
if (move_cnt == 20) {
const r = getRandomInt(0, 255);
const g = getRandomInt(0, 255);
const b = getRandomInt(0, 255);
style = { color: `rgb(${r} ${g} ${b} / 100%)`, diameter: 10 };
move_cnt = 0;
document.getElementById("div").style.backgroundColor =
`rgb(${r} ${g} ${b} / 60%)`;
}
move_cnt += 1;
await presenter.updateInkTrailStartPoint(evt, style);
});
window.addEventListener("pointerdown", () => {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
});
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
```
#### Result
{{EmbedLiveSample("Drawing an ink trail")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Enhancing Inking on the Web](https://blogs.windows.com/msedgedev/2021/08/18/enhancing-inking-on-the-web/)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/webtransportsendstream/index.md | ---
title: WebTransportSendStream
slug: Web/API/WebTransportSendStream
page-type: web-api-interface
status:
- experimental
browser-compat: api.WebTransportSendStream
---
{{APIRef("WebTransport API")}}{{SeeCompatTable}}{{securecontext_header}}
The `WebTransportSendStream` interface of the {{domxref("WebTransport API", "WebTransport API", "", "nocode")}} is a specialized {{domxref("WritableStream")}} that is used to send outbound data in both unidirectional or bidirectional {{domxref("WebTransport")}} streams.
The send stream is a [writable stream](/en-US/docs/Web/API/Streams_API/Using_writable_streams) of [`Uint8Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), that can be written to in order to send data to a server.
It additionally provides streaming features such as setting the send order, and getting stream statistics.
Objects of this type are not constructed directly.
When creating a unidirectional stream the {{domxref("WebTransport.createUnidirectionalStream()")}} returns an object of this type for sending data.
When creating a bidirectional stream using {{domxref("WebTransport.createBidirectionalStream()")}}, the method returns a {{domxref("WebTransportBidirectionalStream")}}, and the send stream object can be obtained from its {{domxref("WebTransportBidirectionalStream.writable", "writable")}} property.
When a bidirectional stream is initiated by the remote end, an object of this type can similarly be obtained using {{domxref("WebTransport.incomingBidirectionalStreams")}}.
`WebTransportSendStream` is a [transferable object](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects).
{{InheritanceDiagram}}
{{AvailableInWorkers}}
## Instance properties
_Also inherits properties from its parent interface, {{domxref("WritableStream")}}._
- {{domxref("WebTransportSendStream.getStats()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves with statistics related to this stream.
## Instance methods
_Also inherits methods from its parent interface, {{domxref("WritableStream")}}._
<!-- WebTransportSendStream.sendGroup not implemented in any browser -->
- {{domxref("WebTransportSendStream.sendOrder")}} {{Experimental_Inline}}
- : Indicates the send priority of this stream relative to other streams for which the value has been set.
## Examples
See [`WebTransport.incomingUnidirectionalStreams`](/en-US/docs/Web/API/WebTransport/incomingUnidirectionalStreams) for an example of how to get a {{domxref("ReadableStream")}} of `WebTransportSendStream` objects.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api/webtransportsendstream | data/mdn-content/files/en-us/web/api/webtransportsendstream/getstats/index.md | ---
title: "WebTransportSendStream: getStats() method"
short-title: getStats()
slug: Web/API/WebTransportSendStream/getStats
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.WebTransportSendStream.getStats
---
{{APIRef("WebTransport API")}}{{SeeCompatTable}}{{securecontext_header}}
The **`getStats()`** method of the {{domxref("WebTransportSendStream")}} interface asynchronously returns an object containing statistics for the current stream.
The statistics include the total number of bytes written to the stream, the number that have been sent (ignoring packet overhead), and the number of bytes that have been set at least once, and the number that have been acknowledged (up until the first sequentially-ordered non-acknowledged byte).
It therefore provides a measure of how quickly the application is sending bytes to the server on this particular stream.
{{AvailableInWorkers}}
## Syntax
```js-nolint
getStats()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that resolves to a object containing statistics about the current stream.
The returned object has the following properties:
- `bytesAcknowledged`
- : A positive integer indicating the number of bytes written to this stream that have been sent and acknowledged as received by the server, using QUIC's ACK mechanism.
Only sequential bytes up to, but not including, the first non-acknowledged byte, are counted.
This number can only increase and is always less than or equal to `bytesSent`.
When the connection is over HTTP/2, the value will match `bytesSent`.
- `bytesSent`
- : A positive integer indicating the number of bytes written to this stream that have been sent at least once (but not necessarily acknowledged).
This number can only increase, and is always less than or equal to `bytesWritten`.
Note that this count does not include bytes sent as network overhead (such as packet headers).
- `bytesWritten`
- : A positive integer indicating the number of bytes successfully written to this stream.
This number can only increase.
## Examples
The code snippet below uses `await` to wait on the {{jsxref("Promise")}} returned by `getStats()`.
When the promise fulfills, the result for the number of bytes that have been sent but not acknowledged is logged to the console.
```js
const stats = await stream.getStats();
const bytesNotReceived = stats.bytesWritten - stats.bytesAcknowledged;
console.log(`Bytes still successfully sent: ${bytesNotReceived}`);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/webtransportsendstream | data/mdn-content/files/en-us/web/api/webtransportsendstream/sendorder/index.md | ---
title: "WebTransportSendStream: sendOrder property"
short-title: sendOrder
slug: Web/API/WebTransportSendStream/sendOrder
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.WebTransportSendStream.sendOrder
---
{{APIRef("WebTransport API")}}{{SeeCompatTable}}{{securecontext_header}}
The **`sendOrder`** property of the {{domxref("WebTransportSendStream")}} interface indicates the send priority of this stream relative to other streams for which the value has been set.
Queued bytes are sent first for streams that have a higher value.
If not set, the send order depends on the implementation.
{{AvailableInWorkers}}
## Value
A number indicating the relative priority of this stream when sending bytes.
## Examples
The example below shows how you can set the initial `sendOrder` when calling {{domxref("WebTransport.createUnidirectionalStream()")}} to create the send stream, read the value from the stream, and then change the order.
After changing the order the priority of this stream would increase, becoming higher than any stream with a priority of less than "596996858".
```js
async function writeData() {
const stream = await transport.createUnidirectionalStream({
sendOrder: "400", // Set initial stream order
});
console.log(`Stream order: ${stream.sendOrder}`); // Stream order: 400
// write data ...
// Change the stream order
stream.sendOrder = 596996858;
console.log(`Stream order: ${stream.sendOrder}`); // Stream order: 596996858
// write more data ...
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/usbinterface/index.md | ---
title: USBInterface
slug: Web/API/USBInterface
page-type: web-api-interface
status:
- experimental
browser-compat: api.USBInterface
---
{{securecontext_header}}{{APIRef("WebUSB API")}}{{SeeCompatTable}}
The `USBInterface` interface of the [WebUSB API](/en-US/docs/Web/API/WebUSB_API) provides information about an interface provided by the USB device. An interface represents a feature of the device which implements a particular protocol and may contain endpoints for bidirectional communication.
## Constructor
- {{domxref("USBInterface.USBInterface", "USBInterface()")}} {{Experimental_Inline}}
- : Creates a new `USBInterface` object which will be populated with information about the interface on the provided `USBConfiguration` with the given interface number.
## Instance properties
- {{domxref("USBInterface.interfaceNumber")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the interface number of this interface. This is equal to the `bInterfaceNumber` field of the interface descriptor defining this interface.
- {{domxref("USBInterface.alternate")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the currently selected alternative configuration of this interface. By default this is the `USBAlternateInterface` from `alternates` with `alternateSetting` equal to `0`. It can be changed by calling `USBDevice.selectAlternateInterface()` with any other value found in `alternates`.
- {{domxref("USBInterface.alternates")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns an array containing instances of the `USBAlternateInterface` interface describing each of the alternative configurations possible for this interface.
- {{domxref("USBInterface.claimed")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns whether or not this interface has been claimed by the current page by calling `USBDevice.claimInterface()`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/cssskew/index.md | ---
title: CSSSkew
slug: Web/API/CSSSkew
page-type: web-api-interface
browser-compat: api.CSSSkew
---
{{APIRef("CSS Typed OM")}}
The **`CSSSkew`** interface of the {{domxref('CSS_Object_Model#css_typed_object_model','','',' ')}} is part of the {{domxref('CSSTransformValue')}} interface. It represents the [`skew()`](/en-US/docs/Web/CSS/transform-function/skew) value of the individual {{CSSXRef('transform')}} property in CSS.
{{InheritanceDiagram}}
## Constructor
- {{domxref("CSSSkew.CSSSkew", "CSSSkew()")}}
- : Creates a new `CSSSkew` object.
## Instance properties
- {{domxref('CSSSkew.ax','ax')}}
- : Returns or sets the x-axis value.
- {{domxref('CSSSkew.ay','ay')}}
- : Returns or sets the y-axis value.
## Examples
To Do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssskew | data/mdn-content/files/en-us/web/api/cssskew/ay/index.md | ---
title: "CSSSkew: ay property"
short-title: ay
slug: Web/API/CSSSkew/ay
page-type: web-api-instance-property
browser-compat: api.CSSSkew.ay
---
{{APIRef("CSS Typed OM")}}
The **`ay`** property of the
{{domxref("CSSSkew")}} interface gets and sets the angle used to distort the element
along the y-axis (or ordinate).
## Value
A {{domxref("CSSNumericValue")}}.
## Examples
To do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssskew | data/mdn-content/files/en-us/web/api/cssskew/cssskew/index.md | ---
title: "CSSSkew: CSSSkew() constructor"
short-title: CSSSkew()
slug: Web/API/CSSSkew/CSSSkew
page-type: web-api-constructor
browser-compat: api.CSSSkew.CSSSkew
---
{{APIRef("CSS Typed OM")}}
The **`CSSSkew()`** constructor creates a new
{{domxref("CSSSkew")}} object which represents the
[`skew()`](/en-US/docs/Web/CSS/transform-function/skew) value
of the individual {{CSSXRef('transform')}} property in CSS.
## Syntax
```js-nolint
new CSSSkew(ax, ay)
```
### Parameters
- {{domxref('CSSSkew.ax','ax')}}
- : A value for the `ax` (x-axis) angle of the {{domxref('CSSSkew')}} object to be constructed. This must be a {{domxref('CSSNumericValue')}}.
- {{domxref('CSSSkew.ay','ay')}}
- : A value for the `ay` (y-axis) angle of the {{domxref('CSSSkew')}} object to be constructed. This must be a {{domxref('CSSNumericValue')}}.
## Examples
To do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssskew | data/mdn-content/files/en-us/web/api/cssskew/ax/index.md | ---
title: "CSSSkew: ax property"
short-title: ax
slug: Web/API/CSSSkew/ax
page-type: web-api-instance-property
browser-compat: api.CSSSkew.ax
---
{{APIRef("CSS Typed OM")}}
The **`ax`** property of the
{{domxref("CSSSkew")}} interface gets and sets the angle used to distort the element
along the x-axis (or abscissa).
## Value
A {{domxref("CSSNumericValue")}}.
## Examples
To do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/idbrequest/index.md | ---
title: IDBRequest
slug: Web/API/IDBRequest
page-type: web-api-interface
browser-compat: api.IDBRequest
---
{{APIRef("IndexedDB")}}
The **`IDBRequest`** interface of the IndexedDB API provides access to results of asynchronous requests to databases and database objects using event handler attributes. Each reading and writing operation on a database is done using a request.
The request object does not initially contain any information about the result of the operation, but once information becomes available, an event is fired on the request, and the information becomes available through the properties of the `IDBRequest` instance.
All asynchronous operations immediately return an {{domxref("IDBRequest")}} instance. Each request has a `readyState` that is set to the `'pending'` state; this changes to `'done'` when the request is completed or fails. When the state is set to `done`, every request returns a `result` and an `error`, and an event is fired on the request. When the state is still `pending`, any attempt to access the `result` or `error` raises an `InvalidStateError` exception.
In plain words, all asynchronous methods return a request object. If the request has been completed successfully, the result is made available through the `result` property and an event indicating success is fired at the request ({{domxref("IDBRequest.success_event", "success")}}). If an error occurs while performing the operation, the exception is made available through the `error` property and an error event is fired ({{domxref("IDBRequest.error_event", "error")}}).
The interface {{domxref("IDBOpenDBRequest")}} is derived from `IDBRequest`.
{{AvailableInWorkers}}
{{InheritanceDiagram}}
## Instance properties
_Also inherits properties from {{domxref("EventTarget")}}._
- {{domxref("IDBRequest.error")}} {{ReadOnlyInline}}
- : Returns a {{domxref("DOMException")}} in the event of an unsuccessful request, indicating what went wrong.
- {{domxref("IDBRequest.result")}} {{ReadOnlyInline}}
- : Returns the result of the request. If the request is not completed, the result is not available and an `InvalidStateError` exception is thrown.
- {{domxref("IDBRequest.source")}} {{ReadOnlyInline}}
- : The source of the request, such as an {{domxref("IDBIndex")}} or an {{domxref("IDBObjectStore")}}. If no source exists (such as when calling {{domxref("IDBFactory.open")}}), it returns null.
- {{domxref("IDBRequest.readyState")}} {{ReadOnlyInline}}
- : The state of the request. Every request starts in the `pending` state. The state changes to `done` when the request completes successfully or when an error occurs.
- {{domxref("IDBRequest.transaction")}} {{ReadOnlyInline}}
- : The transaction for the request. This property can be null for certain requests, for example those returned from {{domxref("IDBFactory.open")}} unless an upgrade is needed. (You're just connecting to a database, so there is no transaction to return).
## Instance methods
_No methods, but inherits methods from {{domxref("EventTarget")}}._
## Events
Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.
- [`error`](/en-US/docs/Web/API/IDBRequest/error_event)
- : Fired when an error caused a request to fail.
- [`success`](/en-US/docs/Web/API/IDBRequest/success_event)
- : Fired when an `IDBRequest` succeeds.
## Example
In the following code snippet, we open a database asynchronously and make a request; `onerror` and `onsuccess` functions are included to handle the success and error cases. For a full working example, see our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app ([view example live](https://mdn.github.io/dom-examples/to-do-notifications/).)
```js
let db;
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
// these two event handlers act on the database being
// opened successfully, or not
DBOpenRequest.onerror = (event) => {
note.innerHTML += "<li>Error loading database.</li>";
};
DBOpenRequest.onsuccess = (event) => {
note.innerHTML += "<li>Database initialized.</li>";
// store the result of opening the database.
db = DBOpenRequest.result;
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
- Starting transactions: {{domxref("IDBDatabase")}}
- Using transactions: {{domxref("IDBTransaction")}}
- Setting a range of keys: {{domxref("IDBKeyRange")}}
- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
- Using cursors: {{domxref("IDBCursor")}}
- Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
| 0 |
data/mdn-content/files/en-us/web/api/idbrequest | data/mdn-content/files/en-us/web/api/idbrequest/source/index.md | ---
title: "IDBRequest: source property"
short-title: source
slug: Web/API/IDBRequest/source
page-type: web-api-instance-property
browser-compat: api.IDBRequest.source
---
{{ APIRef("IndexedDB") }}
The **`source`** read-only property of the
{{domxref("IDBRequest")}} interface returns the source of the request, such as an
Index or an object store. If no source exists (such as when calling
{{domxref("IDBFactory.open")}}), it returns null.
{{AvailableInWorkers}}
## Value
An object representing the source of the request, such as an {{domxref("IDBIndex")}},
{{domxref("IDBObjectStore")}} or {{domxref("IDBCursor")}}.
## Examples
The following example requests a given record title, `onsuccess` gets the
associated record from the {{domxref("IDBObjectStore")}} (made available
as `objectStoreTitleRequest.result`), updates
one property of the record, and then puts the updated record back into the object
store in another request. The source of the 2nd request is logged to the developer
console. For a full working example, see our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
```js
const title = "Walk dog";
// Open up a transaction as usual
const objectStore = db
.transaction(["toDoList"], "readwrite")
.objectStore("toDoList");
// Get the to-do list object that has this title as its title
const objectStoreTitleRequest = objectStore.get(title);
objectStoreTitleRequest.onsuccess = () => {
// Grab the data object returned as the result
const data = objectStoreTitleRequest.result;
// Update the notified value in the object to "yes"
data.notified = "yes";
// Create another request that inserts the item
// back into the database
const updateTitleRequest = objectStore.put(data);
// Log the source of this request
console.log(`The source of this request is ${updateTitleRequest.source}`);
// When this new request succeeds, run the displayData()
// function again to update the display
updateTitleRequest.onsuccess = () => {
displayData();
};
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
- Starting transactions: {{domxref("IDBDatabase")}}
- Using transactions: {{domxref("IDBTransaction")}}
- Setting a range of keys: {{domxref("IDBKeyRange")}}
- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
- Using cursors: {{domxref("IDBCursor")}}
- Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
| 0 |
data/mdn-content/files/en-us/web/api/idbrequest | data/mdn-content/files/en-us/web/api/idbrequest/transaction/index.md | ---
title: "IDBRequest: transaction property"
short-title: transaction
slug: Web/API/IDBRequest/transaction
page-type: web-api-instance-property
browser-compat: api.IDBRequest.transaction
---
{{ APIRef("IndexedDB") }}
The **`transaction`** read-only property of the IDBRequest
interface returns the transaction for the request, that is, the transaction the
request is being made inside.
This property can be `null` for requests not made within transactions,
such as for requests returned from {{domxref("IDBFactory.open")}} — in this case
you're just connecting to a database, so there is no transaction to return. If a
version upgrade is needed when opening a database then during the
{{domxref("IDBOpenDBRequest.upgradeneeded_event", "upgradeneeded")}} event handler the
**`transaction`** property will be an
{{domxref("IDBTransaction")}} with {{domxref("IDBTransaction.mode", "mode")}} equal
to `"versionchange"`, and can be used to access existing object stores and
indexes, or abort the upgrade. Following the upgrade, the
**`transaction`** property will again be `null`.
{{AvailableInWorkers}}
## Value
An {{domxref("IDBTransaction")}}.
## Examples
The following example requests a given record title, `onsuccess` gets the
associated record from the {{domxref("IDBObjectStore")}} (made available
as `objectStoreTitleRequest.result`), updates
one property of the record, and then puts the updated record back into the object
store in another request. The source of the requests is logged to the developer
console — both originate from the same transaction. For a full working example, see
our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app
([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
```js
const title = "Walk dog";
// Open up a transaction as usual
const objectStore = db
.transaction(["toDoList"], "readwrite")
.objectStore("toDoList");
// Get the to-do list object that has this title as it's title
const objectStoreTitleRequest = objectStore.get(title);
objectStoreTitleRequest.onsuccess = () => {
// Grab the data object returned as the result
const data = objectStoreTitleRequest.result;
// Update the notified value in the object to "yes"
data.notified = "yes";
// Create another request that inserts the item back
// into the database
const updateTitleRequest = objectStore.put(data);
// Log the transaction that originated this request
console.log(
`The transaction that originated this request is ${updateTitleRequest.transaction}`,
);
// When this new request succeeds, run the displayData()
// function again to update the display
updateTitleRequest.onsuccess = () => {
displayData();
};
};
```
This example shows how a the **`transaction`** property can be
used during a version upgrade to access existing object stores:
```js
const openRequest = indexedDB.open("db", 2);
console.log(openRequest.transaction); // Will log "null".
openRequest.onupgradeneeded = (event) => {
console.log(openRequest.transaction.mode); // Will log "versionchange".
const db = openRequest.result;
if (event.oldVersion < 1) {
// New database, create "books" object store.
db.createObjectStore("books");
}
if (event.oldVersion < 2) {
// Upgrading from v1 database: add index on "title" to "books" store.
const bookStore = openRequest.transaction.objectStore("books");
bookStore.createIndex("by_title", "title");
}
};
openRequest.onsuccess = () => {
console.log(openRequest.transaction); // Will log "null".
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
- Starting transactions: {{domxref("IDBDatabase")}}
- Using transactions: {{domxref("IDBTransaction")}}
- Setting a range of keys: {{domxref("IDBKeyRange")}}
- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
- Using cursors: {{domxref("IDBCursor")}}
- Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
| 0 |
data/mdn-content/files/en-us/web/api/idbrequest | data/mdn-content/files/en-us/web/api/idbrequest/success_event/index.md | ---
title: "IDBRequest: success event"
short-title: success
slug: Web/API/IDBRequest/success_event
page-type: web-api-event
browser-compat: api.IDBRequest.success_event
---
{{ APIRef("IndexedDB") }}
The `success` event is fired when an `IDBRequest` succeeds.
This event is not cancelable and does not bubble.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("success", (event) => {});
onsuccess = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
This example tries to open a database and listens for the `success` event using `addEventListener()`:
```js
// Open the database
const openRequest = window.indexedDB.open("toDoList", 4);
openRequest.onupgradeneeded = (event) => {
const db = event.target.result;
db.onerror = () => {
console.log("Error creating database");
};
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
};
openRequest.addEventListener("success", (event) => {
console.log("Database opened successfully!");
});
```
The same example, but using the `onsuccess` event handler property:
```js
// Open the database
const openRequest = window.indexedDB.open("toDoList", 4);
openRequest.onupgradeneeded = (event) => {
const db = event.target.result;
db.onerror = () => {
console.log("Error creating database");
};
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
};
openRequest.onsuccess = (event) => {
console.log("Database opened successfully!");
};
```
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
| 0 |
data/mdn-content/files/en-us/web/api/idbrequest | data/mdn-content/files/en-us/web/api/idbrequest/error/index.md | ---
title: "IDBRequest: error property"
short-title: error
slug: Web/API/IDBRequest/error
page-type: web-api-instance-property
browser-compat: api.IDBRequest.error
---
{{ APIRef("IndexedDB") }}
The **`error`** read-only property of the
{{domxref("IDBRequest")}} interface returns the error in the event of an unsuccessful
request.
{{AvailableInWorkers}}
## Value
A {{domxref("DOMException")}} or `null` if there is no error. The following error names are returned
in the exception object:
- `AbortError`
- : If you abort the transaction, then all requests still in progress receive this error.
- `ConstraintError`
- : If you insert data that doesn't conform to a constraint.
It's an exception type for creating stores and indexes.
You get this error, for example, if you try to add a new key that already exists in the record.
- `QuotaExceededError`
- : If you run out of disk quota and the user declined to grant you more space.
- `UnknownError`
- : If the operation failed for reasons unrelated to the database itself.
A failure due to disk IO errors is such an example.
- `VersionError`
- : If you try to open a database with a version lower than the one it already has.
In addition to the error codes sent to the {{ domxref("IDBRequest") }} object,
asynchronous operations can also raise exceptions. The list describes problems that
could occur when the request is being executed, but you might also encounter other
problems when the request is being made. For example, if the result is accessed
while the request is not completed, the `InvalidStateError` exception is thrown.
## Examples
The following example requests a given record title, `onsuccess` gets the
associated record from the {{domxref("IDBObjectStore")}} (made available as
`objectStoreTitleRequest.result`), updates one property of the record, and then puts the
updated record back into the object store. Also included at the bottom is an
`onerror` function that reports what the error was if the request fails.
For a full working example, see our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
```js
const title = "Walk dog";
// Open up a transaction as usual
const objectStore = db
.transaction(["toDoList"], "readwrite")
.objectStore("toDoList");
// Get the to-do list with the specified title
const objectStoreTitleRequest = objectStore.get(title);
objectStoreTitleRequest.onsuccess = () => {
// Grab the data object returned as the result
const data = objectStoreTitleRequest.result;
// Update the notified value in the object to "yes"
data.notified = "yes";
// Create another request that inserts the item
// back into the database
const updateTitleRequest = objectStore.put(data);
// When this new request succeeds, run the displayData()
// function again to update the display
updateTitleRequest.onsuccess = () => {
displayData();
};
};
objectStoreTitleRequest.onerror = () => {
// If an error occurs with the request, log what it is
console.log(
`There has been an error with retrieving your data: ${objectStoreTitleRequest.error}`,
);
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
- Starting transactions: {{domxref("IDBDatabase")}}
- Using transactions: {{domxref("IDBTransaction")}}
- Setting a range of keys: {{domxref("IDBKeyRange")}}
- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
- Using cursors: {{domxref("IDBCursor")}}
- Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
| 0 |
data/mdn-content/files/en-us/web/api/idbrequest | data/mdn-content/files/en-us/web/api/idbrequest/readystate/index.md | ---
title: "IDBRequest: readyState property"
short-title: readyState
slug: Web/API/IDBRequest/readyState
page-type: web-api-instance-property
browser-compat: api.IDBRequest.readyState
---
{{ APIRef("IndexedDB") }}
The **`readyState`** read-only property of the
{{domxref("IDBRequest")}} interface returns the state of the request.
Every request starts in the `pending` state. The state changes to
`done` when the request completes successfully or when an error
occurs.
{{AvailableInWorkers}}
## Value
One of the following strings:
- `pending`
- : Returned if the request is still ongoing.
- `done`
- : Returned if the request has already completed.
## Examples
The following example requests a given record title, `onsuccess` gets the
associated record from the {{domxref("IDBObjectStore")}} (made available
as `objectStoreTitleRequest.result`), updates
one property of the record, and then puts the updated record back into the object
store in another request. The `readyState` of the 2nd request is logged to
the developer console. For a full working example, see our
[To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app
([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
```js
const title = "Walk dog";
// Open up a transaction as usual
const objectStore = db
.transaction(["toDoList"], "readwrite")
.objectStore("toDoList");
// Get the to-do list object that has this title as it's title
const objectStoreTitleRequest = objectStore.get(title);
objectStoreTitleRequest.onsuccess = () => {
// Grab the data object returned as the result
const data = objectStoreTitleRequest.result;
// Update the notified value in the object to "yes"
data.notified = "yes";
// Create another request that inserts the item
// back into the database
const updateTitleRequest = objectStore.put(data);
// Log the readyState of this request
console.log(
`The readyState of this request is ${updateTitleRequest.readyState}`,
);
// When this new request succeeds, run the displayData()
// function again to update the display
updateTitleRequest.onsuccess = () => {
displayData();
};
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
- Starting transactions: {{domxref("IDBDatabase")}}
- Using transactions: {{domxref("IDBTransaction")}}
- Setting a range of keys: {{domxref("IDBKeyRange")}}
- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
- Using cursors: {{domxref("IDBCursor")}}
- Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
| 0 |
data/mdn-content/files/en-us/web/api/idbrequest | data/mdn-content/files/en-us/web/api/idbrequest/result/index.md | ---
title: "IDBRequest: result property"
short-title: result
slug: Web/API/IDBRequest/result
page-type: web-api-instance-property
browser-compat: api.IDBRequest.result
---
{{ APIRef("IndexedDB") }}
The **`result`** read-only property of the
{{domxref("IDBRequest")}} interface returns the result of the request. If the request
is not completed, the result is not available and an `InvalidStateError` exception is
thrown.
{{AvailableInWorkers}}
## Value
any
## Examples
The following example requests a given record title, `onsuccess` gets the
associated record from the {{domxref("IDBObjectStore")}} (made available
as `objectStoreTitleRequest.result`), updates
one property of the record, and then puts the updated record back into the object
store. For a full working example, see our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
```js
const title = "Walk dog";
// Open up a transaction as usual
const objectStore = db
.transaction(["toDoList"], "readwrite")
.objectStore("toDoList");
// Get the to-do list object that has this title as it's title
const objectStoreTitleRequest = objectStore.get(title);
objectStoreTitleRequest.onsuccess = () => {
// Grab the data object returned as the result
const data = objectStoreTitleRequest.result;
// Update the notified value in the object to "yes"
data.notified = "yes";
// Create another request that inserts the item
// back into the database
const updateTitleRequest = objectStore.put(data);
// When this new request succeeds, run the displayData()
// function again to update the display
updateTitleRequest.onsuccess = () => {
displayData();
};
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
- Starting transactions: {{domxref("IDBDatabase")}}
- Using transactions: {{domxref("IDBTransaction")}}
- Setting a range of keys: {{domxref("IDBKeyRange")}}
- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
- Using cursors: {{domxref("IDBCursor")}}
- Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
| 0 |
data/mdn-content/files/en-us/web/api/idbrequest | data/mdn-content/files/en-us/web/api/idbrequest/error_event/index.md | ---
title: "IDBRequest: error event"
short-title: error
slug: Web/API/IDBRequest/error_event
page-type: web-api-event
browser-compat: api.IDBRequest.error_event
---
{{APIRef("IndexedDB")}}
The `error` handler is executed when an error caused a request to fail.
This event is not cancelable and does not bubble.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("error", (event) => {});
onerror = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
This example opens a database and tries to add a record, listening for the `error` event for the `add()` operation (this will occur if, for example, a record with the given `taskTitle` already exists):
```js
// Open the database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.addEventListener("upgradeneeded", (event) => {
const db = event.target.result;
db.onerror = () => {
console.log("Error creating database");
};
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
});
DBOpenRequest.addEventListener("success", (event) => {
const db = DBOpenRequest.result;
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
const objectStore = transaction.objectStore("toDoList");
const newItem = {
taskTitle: "my task",
hours: 10,
minutes: 10,
day: 10,
month: "January",
year: 2020,
};
const objectStoreRequest = objectStore.add(newItem);
objectStoreRequest.addEventListener("error", () => {
console.log(`Error adding new item: ${newItem.taskTitle}`);
});
});
```
The same example, using the `onerror` property instead of `addEventListener()`:
```js
// Open the database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
db.onerror = () => {
console.log("Error creating database");
};
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
};
DBOpenRequest.onsuccess = (event) => {
const db = DBOpenRequest.result;
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
const objectStore = transaction.objectStore("toDoList");
const newItem = {
taskTitle: "my task",
hours: 10,
minutes: 10,
day: 10,
month: "January",
year: 2020,
};
const objectStoreRequest = objectStore.add(newItem);
objectStoreRequest.onerror = () => {
console.log(`Error adding new item: ${newItem.taskTitle}`);
};
};
```
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/payment_handler_api/index.md | ---
title: Payment Handler API
slug: Web/API/Payment_Handler_API
page-type: web-api-overview
status:
- experimental
browser-compat: api.PaymentRequestEvent
---
{{DefaultAPISidebar("Payment Handler API")}}{{securecontext_header}}{{SeeCompatTable}}
The Payment Handler API provides a standardized set of functionality for web applications to directly handle payments, rather than having to be redirected to a separate site for payment handling.
When a merchant website initiates payment via the {{domxref("Payment Request API", "Payment Request API", "", "nocode")}}, the Payment Handler API handles discovery of applicable payment apps, presenting them as choices to the user, opening a payment handler window once a choice has been made to allow the user to enter their payment details, and handling the payment transaction with the payment app.
Communication with payment apps (authorization, passing of payment credentials) is handled via Service Workers.
## Concepts and usage
On a merchant website, a payment request is initiated by the construction of a new {{domxref("PaymentRequest")}} object:
```js
const request = new PaymentRequest(
[
{
supportedMethods: "https://bobbucks.dev/pay",
},
],
{
total: {
label: "total",
amount: { value: "10", currency: "USD" },
},
},
);
```
The `supportedMethods` property specifies a URL representing the payment method supported by the merchant. To use more than one payment method, you would specify them in an array of objects, like this:
```js
const request = new PaymentRequest(
[
{
supportedMethods: "https://alicebucks.dev/pay",
},
{
supportedMethods: "https://bobbucks.dev/pay",
},
],
{
total: {
label: "total",
amount: { value: "10", currency: "USD" },
},
},
);
```
### Making payment apps available
In supporting browsers, the process starts by requesting a payment method manifest file from each URL. A payment method manifest is typically called something like `payment-manifest.json` (the exact name can be whatever you like), and should be structured like this:
```json
{
"default_applications": ["https://bobbucks.dev/manifest.json"],
"supported_origins": ["https://alicepay.friendsofalice.example"]
}
```
Given a payment method identifier like `https://bobbucks.dev/pay`, the browser:
1. Starts loading `https://bobbucks.dev/pay` and checks its HTTP headers.
1. If a {{httpheader("Link")}} header is found with `rel="payment-method-manifest"`, then it downloads the payment method manifest at that location instead (see [Optionally route the browser to find the payment method manifest in another location](https://web.dev/articles/setting-up-a-payment-method#optionally_route_the_browser_to_find_the_payment_method_manifest_in_another_location) for details).
2. Otherwise, parse the response body of `https://bobbucks.dev/pay` as the payment method manifest.
2. Parses the downloaded content as JSON with `default_applications` and `supported_origins` members.
These members have the following purposes:
- `default_applications` tells the browser where to find the default payment app that can use the BobBucks payment method if it doesn't already have one installed.
- `supported_origins` tells the browser what other payment apps are permitted to handle the BobBucks payment if needed. If they are already installed on the device, they will be presented to the user as alternative payment options alongside the default application.
From the payment method manifest, the browser gets the URL of the default payment apps' [web app manifest](/en-US/docs/Web/Manifest) files, which can be called whatever you like, and look something like this:
```json
{
"name": "Pay with BobBucks",
"short_name": "BobBucks",
"description": "This is an example of the Payment Handler API.",
"icons": [
{
"src": "images/manifest/icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "images/manifest/icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"serviceworker": {
"src": "service-worker.js",
"scope": "/",
"use_cache": false
},
"start_url": "/",
"display": "standalone",
"theme_color": "#3f51b5",
"background_color": "#3f51b5",
"related_applications": [
{
"platform": "play",
"id": "com.example.android.samplepay",
"min_version": "1",
"fingerprints": [
{
"type": "sha256_cert",
"value": "4C:FC:14:C6:97:DE:66:4E:66:97:50:C0:24:CE:5F:27:00:92:EE:F3:7F:18:B3:DA:77:66:84:CD:9D:E9:D2:CB"
}
]
}
]
}
```
When the {{domxref("PaymentRequest.show()")}} method is invoked by the merchant app in response to a user gesture, the browser uses the [`name`](/en-US/docs/Web/Manifest/name) and [`icons`](/en-US/docs/Web/Manifest/icons) information found in each manifest to present the payment apps to the user in the browser-provided Payment Request UI.
- If there are multiple payment app options, a list of options is presented to the user for them to choose from. Selecting a payment app will start the payment flow, which causes the browser to Just-In-Time (JIT) install the web app if necessary, registering the service worker specified in the [`serviceworker`](/en-US/docs/Web/Manifest/serviceworker) member so it can handle the payment.
- If there is only one payment app option, the {{domxref("PaymentRequest.show()")}} method will start the payment flow with this payment app, JIT-installing it if necessary, as described above. This is an optimization to avoid presenting the user with a list that contains only one payment app choice.
> **Note:** If [`prefer_related_applications`](/en-US/docs/Web/Manifest/prefer_related_applications) is set to `true` in the payment app manifest, the browser will launch the platform-specific payment app specified in [`related_applications`](/en-US/docs/Web/Manifest/related_applications) to handle the payment (if it is available) instead of the web payment app.
See [Serve a web app manifest](https://web.dev/articles/setting-up-a-payment-method#step_3_serve_a_web_app_manifest) for more details.
### Checking whether the payment app is ready to pay with
The Payment Request API's {{domxref("PaymentRequest.canMakePayment()")}} method returns `true` if a payment app is available on the customer's device, meaning that a payment app that supports the payment method is discovered, and that the platform-specific payment app is installed, or the web-based payment app is ready to be registered.
```js
async function checkCanMakePayment() {
// ...
const canMakePayment = await request.canMakePayment();
if (!canMakePayment) {
// Fallback to other means of payment or hide the button.
}
}
```
The Payment Handler API adds an additional mechanism to prepare for handling a payment. The {{domxref("ServiceWorkerGlobalScope.canmakepayment_event", "canmakepayment")}} event is fired on a payment app's service worker to check whether it is ready to handle a payment. Specifically, it is fired when the merchant website calls {{domxref("PaymentRequest.PaymentRequest", "new PaymentRequest()")}}. The service worker can then use the {{domxref("CanMakePaymentEvent.respondWith()")}} method to respond appropriately:
```js
self.addEventListener("canmakepayment", (e) => {
e.respondWith(
new Promise((resolve, reject) => {
someAppSpecificLogic()
.then((result) => {
resolve(result);
})
.catch((error) => {
reject(error);
});
}),
);
});
```
The promise returned by `respondWith()` resolves with a boolean to signal that it is ready to handle a payment request (`true`), or not (`false`).
### Handling the payment
After the {{domxref("PaymentRequest.show()")}} method is invoked, a {{domxref("ServiceWorkerGlobalScope.paymentrequest_event", "paymentrequest")}} event is fired on the service worker of the payment app. This event is listened for inside the payment app's service worker to begin the next stage of the payment process.
```js
let payment_request_event;
let resolver;
let client;
// `self` is the global object in service worker
self.addEventListener("paymentrequest", async (e) => {
if (payment_request_event) {
// If there's an ongoing payment transaction, reject it.
resolver.reject();
}
// Preserve the event for future use
payment_request_event = e;
// ...
});
```
When a `paymentrequest` event is received, the payment app can open a payment handler window by calling {{domxref("PaymentRequestEvent.openWindow()")}}. The payment handler window will present the customers with a payment app interface where they can authenticate, choose shipping address and options, and authorize the payment.
When the payment has been handled, {{domxref("PaymentRequestEvent.respondWith()")}} is used to pass the payment result back to the merchant website.
See [Receive a payment request event from the merchant](https://web.dev/articles/orchestrating-payment-transactions#receive-payment-request-event) for more details of this stage.
### Managing payment app functionality
Once a payment app service worker is registered, you can use the service worker's {{domxref("PaymentManager")}} instance (accessed via {{domxref("ServiceWorkerRegistration.paymentManager")}}) to manage various aspects of the payment app's functionality.
For example:
```js
navigator.serviceWorker.register("serviceworker.js").then((registration) => {
registration.paymentManager.userHint = "Card number should be 16 digits";
registration.paymentManager
.enableDelegations(["shippingAddress", "payerName"])
.then(() => {
// ...
});
// ...
});
```
- {{domxref("PaymentManager.userHint")}} is used to provide a hint for the browser to display along with the payment app's name and icon in the Payment Handler UI.
- {{domxref("PaymentManager.enableDelegations()")}} is used to delegate responsibility for providing various parts of the required payment information to the payment app rather than collecting it from the browser (for example, via autofill).
## Interfaces
- {{domxref("CanMakePaymentEvent")}}
- : The event object for the {{domxref("ServiceWorkerGlobalScope.canmakepayment_event", "canmakepayment")}} event, fired on a payment app's service worker when it has been successfully registered to signal that it is ready to handle payments.
- {{domxref("PaymentManager")}}
- : Used to manage various aspects of payment app functionality. Accessed via the {{domxref("ServiceWorkerRegistration.paymentManager")}} property.
- {{domxref("PaymentRequestEvent")}} {{Experimental_Inline}}
- : The event object for the {{domxref("ServiceWorkerGlobalScope.paymentrequest_event", "paymentrequest")}} event, fired on a payment app's service worker when a payment flow has been initiated on the merchant website via the {{domxref("PaymentRequest.show()")}} method.
## Extensions to other interfaces
- {{domxref("ServiceWorkerGlobalScope.canmakepayment_event", "canmakepayment")}} event
- : Fired on a payment app's {{domxref("ServiceWorkerGlobalScope")}} when it has been successfully registered, to signal that it is ready to handle payments.
- {{domxref("ServiceWorkerGlobalScope.paymentrequest_event", "paymentrequest")}} event
- : Fired on a payment app's {{domxref("ServiceWorkerGlobalScope")}} when a payment flow has been initiated on the merchant website via the {{domxref("PaymentRequest.show()")}} method.
- {{domxref("ServiceWorkerRegistration.paymentManager")}}
- : Returns a payment app's {{domxref("PaymentManager")}} instance, which is used to manage various payment app functionality.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [BobBucks sample payment app](https://bobbucks.dev/)
- [Web-based payment apps overview](https://web.dev/articles/web-based-payment-apps-overview)
- [Setting up a payment method](https://web.dev/articles/setting-up-a-payment-method)
- [Life of a payment transaction](https://web.dev/articles/life-of-a-payment-transaction)
- [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/contactaddress/index.md | ---
title: ContactAddress
slug: Web/API/ContactAddress
page-type: web-api-interface
status:
- experimental
browser-compat: api.ContactAddress
---
{{securecontext_header}}{{APIRef("Contact Picker API")}}{{SeeCompatTable}}
The **`ContactAddress`** interface of the [Contact Picker API](/en-US/docs/Web/API/Contact_Picker_API) represents a physical address. Instances of this interface are retrieved from the `address` property of the objects returned by {{domxref("ContactsManager.getProperties()")}}.
It may be useful to refer to the Universal Postal Union website's [Addressing S42 standard](https://www.upu.int/en/Postal-Solutions/Programmes-Services/Addressing-Solutions#addressing-s42-standard) materials, which provide information about international standards for postal addresses.
## Instance properties
- {{domxref('ContactAddress.addressLine')}} {{ReadOnlyInline}} {{experimental_inline}}
- : An array of strings providing each line of the address not included among the other properties. The exact size and content varies by country or location and can include, for example, a street name, house number, apartment number, rural delivery route, descriptive instructions, or post office box number.
- {{domxref('ContactAddress.country')}} {{ReadOnlyInline}} {{experimental_inline}}
- : A string specifying the country in which the address is located, using the [ISO-3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) standard. The string is always given in its canonical upper-case form. Some examples of valid `country` values: `"US"`, `"GB"`, `"CN"`, or `"JP"`.
- {{domxref('ContactAddress.city')}} {{ReadOnlyInline}} {{experimental_inline}}
- : A string which contains the city or town portion of the address.
- {{domxref('ContactAddress.dependentLocality')}} {{ReadOnlyInline}} {{experimental_inline}}
- : A string giving the dependent locality or sublocality within a city, for example, a neighborhood, borough, district, or UK dependent locality.
- {{domxref('ContactAddress.organization')}} {{ReadOnlyInline}} {{experimental_inline}}
- : A string specifying the name of the organization, firm, company, or institution at the address.
- {{domxref('ContactAddress.phone')}} {{ReadOnlyInline}} {{experimental_inline}}
- : A string specifying the telephone number of the recipient or contact person.
- {{domxref('ContactAddress.postalCode')}} {{ReadOnlyInline}} {{experimental_inline}}
- : A string specifying a code used by a jurisdiction for mail routing, for example, the ZIP code in the United States or the PIN code in India.
- {{domxref('ContactAddress.recipient')}} {{ReadOnlyInline}} {{experimental_inline}}
- : A string giving the name of the recipient, purchaser, or contact person at the address.
- {{domxref('ContactAddress.region')}} {{ReadOnlyInline}} {{experimental_inline}}
- : A string containing the top level administrative subdivision of the country, for example a state, province, oblast, or prefecture.
- {{domxref('ContactAddress.sortingCode')}} {{ReadOnlyInline}} {{experimental_inline}}
- : A string providing a postal sorting code such as is used in France.
## Instance methods
- {{domxref('ContactAddress.toJSON()')}} {{experimental_inline}}
- : A standard serializer that returns a JSON representation of the `ContactAddress` object's properties.
## Examples
The following example prompts the user to select contacts, then prints the first returned address to the console.
```js
const props = ["address"];
const opts = { multiple: true };
async function getContacts() {
try {
const contacts = await navigator.contacts.select(props, ops);
const contactAddress = contacts[0].address[0];
console.log(contactAddress);
} catch (ex) {
// Handle any errors here.
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/contactaddress | data/mdn-content/files/en-us/web/api/contactaddress/organization/index.md | ---
title: "ContactAddress: organization property"
short-title: organization
slug: Web/API/ContactAddress/organization
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ContactAddress.organization
---
{{securecontext_header}}{{APIRef("Contact Picker API")}}{{SeeCompatTable}}
The **`organization`** read-only property of the {{domxref("ContactAddress")}} interface returns a string containing the name of the organization, firm, company, or institution at the address.
## Value
A string whose value is the name of the organization or company located at the address described by the `ContactAddress` object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/contactaddress | data/mdn-content/files/en-us/web/api/contactaddress/sortingcode/index.md | ---
title: "ContactAddress: sortingCode property"
short-title: sortingCode
slug: Web/API/ContactAddress/sortingCode
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ContactAddress.sortingCode
---
{{securecontext_header}}{{APIRef("Contact Picker API")}}{{SeeCompatTable}}
The **`sortingCode`** read-only property of the {{domxref("ContactAddress")}} interface returns a string containing a postal sorting code such as is used in France.
## Value
A string containing the sorting code portion of the address.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/contactaddress | data/mdn-content/files/en-us/web/api/contactaddress/recipient/index.md | ---
title: "ContactAddress: recipient property"
short-title: recipient
slug: Web/API/ContactAddress/recipient
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ContactAddress.recipient
---
{{securecontext_header}}{{APIRef("Contact Picker API")}}{{SeeCompatTable}}
The read-only **`recipient`** property of the {{domxref("ContactAddress")}} interface returns a string containing the name of the recipient, purchaser, or contact person at the address.
## Value
A string giving the name of the person=, or the name of a contact person in other contexts. If no name is available, this string is empty.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/contactaddress | data/mdn-content/files/en-us/web/api/contactaddress/country/index.md | ---
title: "ContactAddress: country property"
short-title: country
slug: Web/API/ContactAddress/country
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ContactAddress.country
---
{{securecontext_header}}{{APIRef("Contact Picker API")}}{{SeeCompatTable}}
The **`country`** read-only property of the {{domxref("ContactAddress")}} interface is a string identifying the address's country using the [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) standard. The string is always in its canonical upper-case form.
Some examples of valid `country` values: `"US"`, `"GB"`, `"CN"`, or `"JP"`.
## Value
A string which contains the ISO3166-1 alpha-2 code identifying the country in which the address is located, or an empty string if no country is available, which frequently can be assumed to mean "same country as the site owner."
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/contactaddress | data/mdn-content/files/en-us/web/api/contactaddress/region/index.md | ---
title: "ContactAddress: region property"
short-title: region
slug: Web/API/ContactAddress/region
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ContactAddress.region
---
{{securecontext_header}}{{APIRef("Contact Picker API")}}{{SeeCompatTable}}
The read-only **`region`** property of the {{domxref("ContactAddress")}} interface returns a string containing the top-level administrative subdivision of the country in which the address is located. This may be a state, province, oblast, or prefecture.
## Value
A string specifying the top-level administrative subdivision within the country in which the address is located. This region has different names in different countries, such as: state, province, oblast, prefecture, or county.
## Usage notes
In some countries, like Belgium, it's uncommon for people to provide a region as part of their postal address. In such cases, the browser returns an empty string as the value of `region`. However, the address should still be acceptable to use for its intended purpose (e.g., to ship a product). However, always verify addresses to make sure what the user provides is usable.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/contactaddress | data/mdn-content/files/en-us/web/api/contactaddress/postalcode/index.md | ---
title: "ContactAddress: postalCode property"
short-title: postalCode
slug: Web/API/ContactAddress/postalCode
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ContactAddress.postalCode
---
{{securecontext_header}}{{APIRef("Contact Picker API")}}{{SeeCompatTable}}
The **`postalCode`** read-only property of the {{domxref("ContactAddress")}} interface returns a string containing a code used by a jurisdiction for mail routing, for example, the [ZIP Code](https://en.wikipedia.org/wiki/ZIP_Code) in the United States or the [Postal Index Number](https://en.wikipedia.org/wiki/Postal_Index_Number) (PIN code) in India.
## Value
A string which contains the postal code portion of the address. A postal code is a string (either numeric or alphanumeric) which is used by a postal service to optimize mail routing and delivery.
Various countries use different terms for this. In most of the world, it's known as the "post code" or "postal code". In the United States, the ZIP code is used. India uses PIN codes.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- Universal Postal Union: [Universal Post\*Code® Database](https://www.upu.int/en/Postal-Solutions/Programmes-Services/Addressing-Solutions)
| 0 |
data/mdn-content/files/en-us/web/api/contactaddress | data/mdn-content/files/en-us/web/api/contactaddress/phone/index.md | ---
title: "ContactAddress: phone property"
short-title: phone
slug: Web/API/ContactAddress/phone
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ContactAddress.phone
---
{{securecontext_header}}{{APIRef("Contact Picker API")}}{{SeeCompatTable}}
The read-only **`phone`** property of the {{domxref("ContactAddress")}} interface returns a string containing the telephone number of the recipient or contact person at the address.
## Value
A string containing the telephone number for the recipient of the shipment. If no phone number is available, this value is an empty string.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/contactaddress | data/mdn-content/files/en-us/web/api/contactaddress/addressline/index.md | ---
title: "ContactAddress: addressLine property"
short-title: addressLine
slug: Web/API/ContactAddress/addressLine
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ContactAddress.addressLine
---
{{securecontext_header}}{{APIRef("Contact Picker API")}}{{SeeCompatTable}}
The **`addressLine`** read-only property of the {{domxref("ContactAddress")}} interface is an array of strings, each specifying a line of the address that is not covered by one of the other properties of `ContactAddress`. The array may include the street name, the house number, apartment number, the rural delivery route, descriptive instructions, or the post office box.
## Value
An array of strings, each containing one line of the address. For example, the `addressLine` property for the Mozilla Space in London would have the following entries:
| Index | addressLine[] value |
| ----- | ------------------------- |
| 0 | Metal Box Factory |
| 1 | Suite 441, 4th floor |
| 2 | 30 Great Guildford Street |
These, combined with additional values for other properties of the {{domxref("ContactAddress")}}, would represent the full address, which is:
```plaintext
Mozilla
Metal Box Factory
Suite 441, 4th floor
30 Great Guildford Street
London SE1 0HS
United Kingdom
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/contactaddress | data/mdn-content/files/en-us/web/api/contactaddress/dependentlocality/index.md | ---
title: "ContactAddress: dependentLocality property"
short-title: dependentLocality
slug: Web/API/ContactAddress/dependentLocality
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ContactAddress.dependentLocality
---
{{securecontext_header}}{{APIRef("Contact Picker API")}}{{SeeCompatTable}}
The read-only **`dependentLocality`** property of the {{domxref("ContactAddress")}} interface is a string containing a locality or sublocality designation within a city, such as a neighborhood, borough, district, or, in the United Kingdom, a dependent locality. Also known as a _post town_.
## Value
A string indicating the sublocality portion of the address. This may be an empty string if no sublocality is available or required. It's used to provide disambiguation when a city may include areas that duplicate street names.
A sublocality is an area within a city, such as a neighborhood, borough, or district. In the United Kingdom, this is used to indicate the **post town** in the United Kingdom (known officially by the Royal Mail as the **dependent locality**). This is a disambiguating feature of addresses in places where a city may have areas that duplicate street names.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/contactaddress | data/mdn-content/files/en-us/web/api/contactaddress/city/index.md | ---
title: "ContactAddress: city property"
short-title: city
slug: Web/API/ContactAddress/city
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ContactAddress.city
---
{{securecontext_header}}{{APIRef("Contact Picker API")}}{{SeeCompatTable}}
The **`city`** read-only property of the {{domxref("ContactAddress")}} interface returns a string containing the city or town portion of the address.
## Value
A string indicating the city or town portion of the address described by the {{domxref("ContactAddress")}} object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/contactaddress | data/mdn-content/files/en-us/web/api/contactaddress/tojson/index.md | ---
title: "ContactAddress: toJSON() method"
short-title: toJSON()
slug: Web/API/ContactAddress/toJSON
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.ContactAddress.toJSON
---
{{securecontext_header}}{{APIRef("Contact Picker API")}}{{SeeCompatTable}}
The **`toJSON()`** method of the {{domxref("ContactAddress")}} interface is a standard serializer that returns a JSON representation of the `ContactAddress` object's properties.
## Syntax
```js-nolint
toJSON()
```
### Return value
A JSON object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/cryptokey/index.md | ---
title: CryptoKey
slug: Web/API/CryptoKey
page-type: web-api-interface
browser-compat: api.CryptoKey
---
{{APIRef("Web Crypto API")}}{{SecureContext_header}}
The **`CryptoKey`** interface of the [Web Crypto API](/en-US/docs/Web/API/Web_Crypto_API) represents a cryptographic {{glossary("key")}} obtained from one of the {{domxref("SubtleCrypto")}} methods {{domxref("SubtleCrypto.generateKey", "generateKey()")}}, {{domxref("SubtleCrypto.deriveKey", "deriveKey()")}}, {{domxref("SubtleCrypto.importKey", "importKey()")}}, or {{domxref("SubtleCrypto.unwrapKey", "unwrapKey()")}}.
For security reasons, the `CryptoKey` interface can only be used in a [secure context](/en-US/docs/Web/Security/Secure_Contexts).
## Instance properties
- {{domxref("CryptoKey.type")}} {{ReadOnlyInline}}
- : The type of key the object represents. It may take one of the following values: `"secret"`, `"private"` or `"public"`.
- {{domxref("CryptoKey.extractable")}} {{ReadOnlyInline}}
- : A boolean value indicating whether or not the key may be extracted using [`SubtleCrypto.exportKey()`](/en-US/docs/Web/API/SubtleCrypto/exportKey) or [`SubtleCrypto.wrapKey()`](/en-US/docs/Web/API/SubtleCrypto/wrapKey).
- {{domxref("CryptoKey.algorithm")}} {{ReadOnlyInline}}
- : An object describing the algorithm for which this key can be used and any associated extra parameters.
- {{domxref("CryptoKey.usages")}} {{ReadOnlyInline}}
- : An {{jsxref("Array")}} of strings, indicating what can be done with the key. Possible values for array elements are `"encrypt"`, `"decrypt"`, `"sign"`, `"verify"`, `"deriveKey"`, `"deriveBits"`, `"wrapKey"`, and `"unwrapKey"`.
## Examples
The examples for `SubtleCrypto` methods often use `CryptoKey` objects. For example:
- [`SubtleCrypto.generateKey()`](/en-US/docs/Web/API/SubtleCrypto/generateKey)
- [`SubtleCrypto.deriveKey()`](/en-US/docs/Web/API/SubtleCrypto/deriveKey)
- [`SubtleCrypto.importKey()`](/en-US/docs/Web/API/SubtleCrypto/importKey)
- [`SubtleCrypto.exportKey()`](/en-US/docs/Web/API/SubtleCrypto/exportKey)
- [`SubtleCrypto.wrapKey()`](/en-US/docs/Web/API/SubtleCrypto/wrapKey)
- [`SubtleCrypto.unwrapKey()`](/en-US/docs/Web/API/SubtleCrypto/unwrapKey)
- [`SubtleCrypto.encrypt()`](/en-US/docs/Web/API/SubtleCrypto/encrypt)
- [`SubtleCrypto.decrypt()`](/en-US/docs/Web/API/SubtleCrypto/decrypt)
- [`SubtleCrypto.sign()`](/en-US/docs/Web/API/SubtleCrypto/sign)
- [`SubtleCrypto.verify()`](/en-US/docs/Web/API/SubtleCrypto/verify)
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Crypto API](/en-US/docs/Web/API/Web_Crypto_API)
- [Web security](/en-US/docs/Web/Security)
- [Privacy, permissions, and information security](/en-US/docs/Web/Privacy)
- {{domxref("Crypto")}} and {{domxref("Crypto.subtle")}}.
| 0 |
data/mdn-content/files/en-us/web/api/cryptokey | data/mdn-content/files/en-us/web/api/cryptokey/extractable/index.md | ---
title: "CryptoKey: extractable property"
short-title: extractable
slug: Web/API/CryptoKey/extractable
page-type: web-api-instance-property
browser-compat: api.CryptoKey.extractable
---
{{APIRef("Web Crypto API")}}{{SecureContext_Header}}
The read-only **`extractable`** property of the {{DOMxRef("CryptoKey")}} interface indicates whether or not the key may be extracted using [`SubtleCrypto.exportKey()`](/en-US/docs/Web/API/SubtleCrypto/exportKey) or [`SubtleCrypto.wrapKey()`](/en-US/docs/Web/API/SubtleCrypto/wrapKey).
If the key cannot be exported, [`exportKey()`](/en-US/docs/Web/API/SubtleCrypto/exportKey) or [`wrapKey()`](/en-US/docs/Web/API/SubtleCrypto/wrapKey) will throw an exception if used to extract it.
## Value
A boolean value that is `true` if the key can be exported and `false` if not.
## Examples
In this example, the _Export_ button is disabled, and no listener added, if the key cannot be exported.
```js
// Export the given key and write it into the "exported-key" space.
async function exportCryptoKey(key) {
const exported = await window.crypto.subtle.exportKey("raw", key);
const exportedKeyBuffer = new Uint8Array(exported);
const exportKeyOutput = document.querySelector(".exported-key");
exportKeyOutput.textContent = `[${exportedKeyBuffer}]`;
}
// Enable or disable the exportButton if the key is extractable or not
function setExportButton(key) {
const exportButton = document.querySelector(".raw");
// Disable the button if the key is not extractable
exportButton.disabled = !key.extractable;
if (key.extractable) {
// Add an event listener to extract the key
exportButton.addEventListener("click", () => {
exportCryptoKey(key);
});
}
}
// Generate an encrypt/decrypt secret key,
// then enable and set up an event listener on the "Export" button.
window.crypto.subtle
.generateKey(
{
name: "AES-GCM",
length: 256,
},
true,
["encrypt", "decrypt"],
)
.then(setExportButton(key));
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cryptokey | data/mdn-content/files/en-us/web/api/cryptokey/algorithm/index.md | ---
title: "CryptoKey: algorithm property"
short-title: algorithm
slug: Web/API/CryptoKey/algorithm
page-type: web-api-instance-property
browser-compat: api.CryptoKey.algorithm
---
{{APIRef("Web Crypto API")}}{{SecureContext_Header}}
The read-only **`algorithm`** property of the {{DOMxRef("CryptoKey")}} interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters.
The object returned depends of the algorithm used to generate the key.
## Value
An object matching:
- [`AesKeyGenParams`](/en-US/docs/Web/API/AesKeyGenParams) if the algorithm is any of the AES variants.
- [`RsaHashedKeyGenParams`](/en-US/docs/Web/API/RsaHashedKeyGenParams) if the algorithm is any of the RSA variants.
- [`EcKeyGenParams`](/en-US/docs/Web/API/EcKeyGenParams) if the algorithm is any of the EC variants.
- [`HmacKeyGenParams`](/en-US/docs/Web/API/HmacKeyGenParams) if the algorithm is HMAC.
## Examples
```js
const rawKey = window.crypto.getRandomValues(new Uint8Array(16));
// Import an AES secret key from an ArrayBuffer containing the raw bytes.
// Takes an ArrayBuffer string containing the bytes, and returns a Promise
// that will resolve to a CryptoKey representing the secret key.
function importSecretKey(rawKey) {
return window.crypto.subtle.importKey("raw", rawKey, "AES-GCM", true, [
"encrypt",
"decrypt",
]);
}
const key = importSecretKey(rawKey);
console.log(`This key is to be used with the ${key.algorithm} algorithm.`);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cryptokey | data/mdn-content/files/en-us/web/api/cryptokey/type/index.md | ---
title: "CryptoKey: type property"
short-title: type
slug: Web/API/CryptoKey/type
page-type: web-api-instance-property
browser-compat: api.CryptoKey.type
---
{{APIRef("Web Crypto API")}}{{SecureContext_Header}}
The read-only **`type`** property of the {{DOMxRef("CryptoKey")}} interface indicates which kind of key is represented by the object. It can have the following values:
- `"secret"`: This key is a secret key for use with a {{Glossary("Symmetric-key cryptography", "symmetric algorithm")}}.
- `"private"`: This key is the private half of an {{Glossary("Public-key cryptography", "asymmetric algorithm's")}} [`CryptoKeyPair`](/en-US/docs/Web/API/CryptoKeyPair).
- `"public"`: This key is the public half of an {{Glossary("Public-key cryptography", "asymmetric algorithm's")}} [`CryptoKeyPair`](/en-US/docs/Web/API/CryptoKeyPair).
## Value
One of the following strings: `"secret"`, `"private"`, or `"public"`.
## Examples
This function verifies a message using {{domxref("SubtleCrypto.verify()")}} and a public key given in the parameter. If the key is not a public key, it always returns `"invalid"`, as such verification is fundamentally insecure.
```js
async function verifyMessage(publicKey) {
const signatureValue = document.querySelector(
".rsassa-pkcs1 .signature-value",
);
signatureValue.classList.remove("valid", "invalid");
let result = false; // By default, it is invalid
if (publicKey.type === "public") {
const encoded = getMessageEncoding();
result = await window.crypto.subtle.verify(
"RSASSA-PKCS1-v1_5",
publicKey,
signature,
encoded,
);
}
signatureValue.classList.add(result ? "valid" : "invalid");
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cryptokey | data/mdn-content/files/en-us/web/api/cryptokey/usages/index.md | ---
title: "CryptoKey: usages property"
short-title: usages
slug: Web/API/CryptoKey/usages
page-type: web-api-instance-property
browser-compat: api.CryptoKey.usages
---
{{APIRef("Web Crypto API")}}{{SecureContext_Header}}
The read-only **`usages`** property of the {{DOMxRef("CryptoKey")}} interface indicates what can be done with the key.
## Value
An {{jsxref("Array")}} of strings from the following list:
- `"encrypt"`: The key may be used to {{domxref("SubtleCrypto.encrypt()", "encrypt")}} messages.
- `"decrypt"`: The key may be used to {{domxref("SubtleCrypto.decrypt()", "decrypt")}} messages.
- `"sign"`: The key may be used to {{domxref("SubtleCrypto.sign()", "sign")}} messages.
- `"verify"`: The key may be used to {{domxref("SubtleCrypto.verify()", "verify")}} signatures.
- `"deriveKey"`: The key may be used in {{domxref("SubtleCrypto.deriveKey()", "deriving a new key")}}.
- `"deriveBits"`: The key may be used in {{domxref("SubtleCrypto.deriveBits()", "deriving bits")}}.
- `"wrapKey"`: The key may be used to {{domxref("SubtleCrypto.wrapKey()", "wrap a key")}}.
- `"unwrapKey"`: The key may be used to {{domxref("SubtleCrypto.unwrapKey()", "unwrap a key")}}.
## Examples
```js
const rawKey = window.crypto.getRandomValues(new Uint8Array(16));
// Import an AES secret key from an ArrayBuffer containing the raw bytes.
// Takes an ArrayBuffer string containing the bytes, and returns a Promise
// that will resolve to a CryptoKey representing the secret key.
function importSecretKey(rawKey) {
return window.crypto.subtle.importKey("raw", rawKey, "AES-GCM", true, [
"encrypt",
"decrypt",
]);
}
const key = importSecretKey(rawKey);
console.log(
`The following usages are reported for this key: ${key.usages.toString()}`,
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/mediacapabilities/index.md | ---
title: MediaCapabilities
slug: Web/API/MediaCapabilities
page-type: web-api-interface
browser-compat: api.MediaCapabilities
---
{{APIRef("Media Capabilities API")}}
The **`MediaCapabilities`** interface of the [Media Capabilities API](/en-US/docs/Web/API/Media_Capabilities_API) provides information about the decoding abilities of the device, system and browser. The API can be used to query the browser about the decoding abilities of the device based on codecs, profile, resolution, and bitrates. The information can be used to serve optimal media streams to the user and determine if playback should be smooth and power efficient.
The information is accessed through the **`mediaCapabilities`** property of the {{domxref("Navigator")}} interface.
## Instance methods
- {{domxref("MediaCapabilities.encodingInfo()")}}
- : When passed a valid media configuration, it returns a promise with information as to whether the media type is supported, and whether encoding such media would be smooth and power efficient.
- {{domxref("MediaCapabilities.decodingInfo()")}}
- : When passed a valid media configuration, it returns a promise with information as to whether the media type is supported, and whether decoding such media would be smooth and power efficient.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [HTMLMediaElement](/en-US/docs/Web/API/HTMLMediaElement)'s method [canPlayType()](/en-US/docs/Web/API/HTMLMediaElement/canPlayType)
- [MediaSource](/en-US/docs/Web/API/MediaSource)'s method [isTypeSupported()](/en-US/docs/Web/API/MediaSource/isTypeSupported_static)
- {{domxref("Navigator")}} interface
| 0 |
data/mdn-content/files/en-us/web/api/mediacapabilities | data/mdn-content/files/en-us/web/api/mediacapabilities/decodinginfo/index.md | ---
title: "MediaCapabilities: decodingInfo() method"
short-title: decodingInfo()
slug: Web/API/MediaCapabilities/decodingInfo
page-type: web-api-instance-method
browser-compat: api.MediaCapabilities.decodingInfo
---
{{APIRef("MediaCapabilities")}}
The **`MediaCapabilities.decodingInfo()`** method, part of the [Media Capabilities API](/en-US/docs/Web/API/MediaCapabilities), returns a promise with the tested media configuration's capabilities info.
This contains the three boolean properties `supported`, `smooth`, and `powerefficient`, which describe whether decoding the media described would be supported, smooth, and powerefficient.
## Syntax
```js-nolint
decodingInfo(configuration)
```
### Parameters
- `configuration`
- : An object with a property `type` and _either_ a `video` or `audio` property containing a configuration of the appropriate type: <!-- MediaDecodingConfiguration in the spec -->
- `type`
- : The type of media being tested. This takes one of three values:
- `file`
- : Represents a configuration that is meant to be used for a plain file playback.
- `media-source`
- : Represents a configuration that is meant to be used for playback of a {{domxref("MediaSource")}}.
- `webrtc`
- : Represents a configuration that is meant to be received using {{domxref("RTCPeerConnection")}}.
- `video`
- : Configuration object for a video media source.
This has the following properties: <!-- VideoConfiguration in the spec -->
- `contentType`
- : String containing a valid video MIME type, and (optionally) a [`codecs` parameter](/en-US/docs/Web/Media/Formats/codecs_parameter).
- `width`
- : The width of the video.
- `height`
- : The height of the video.
- `bitrate`
- : The number of bits used to encode one second of the video file.
- `framerate`
- : The number of frames making up one second of video playback.
- `audio`
- : Configuration object for an audio media source.
This has the following properties: <!-- AudioConfiguration in the spec -->
- `contentType`
- : String containing a valid audio MIME type, and (optionally) a [`codecs` parameter](/en-US/docs/Web/Media/Formats/codecs_parameter).
- `channels`
- : The number of channels used by the audio track.
- `bitrate`
- : The number of bits used to encode one second of the audio file.
- `samplerate`
- : The number of audio samples making up one second of the audio file.
### Return value
A {{jsxref('Promise')}} fulfilling with an object containing three Boolean attributes:
- `supported`
- : `true` if the media content can be decoded at all. Otherwise, it is `false`.
- `smooth`
- : `true` if playback of the media will be smooth (of high quality). Otherwise it is `false`.
- `powerEfficient`
- : `true` if playback of the media will be power efficient. Otherwise, it is `false`.
Browsers will report a supported media configuration as `smooth` and `powerEfficient` until stats on this device have been recorded.
All supported audio codecs are reported to be power efficient.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the `configuration` passed to the `decodingInfo()` method is invalid, either because the type is not video or audio, the `contentType` is not a valid codec MIME type, the media decoding configuration is not a valid value for the `type` (file, media-source, or webrtc), or any other error in the media configuration passed to the method, including omitting any values.
## Examples
This example shows how to create a media configuration for an audio file and then use it in `MediaCapabilities.decodingInfo()`.
```js
//Create media configuration to be tested
const mediaConfig = {
type: "file", // or 'media-source' or 'webrtc'
audio: {
contentType: "audio/ogg; codecs=vorbis", // valid content type
channels: 2, // audio channels used by the track
bitrate: 132700, // number of bits used to encode 1s of audio
samplerate: 5200, // number of audio samples making up that 1s.
},
};
// check support and performance
navigator.mediaCapabilities.decodingInfo(mediaConfig).then((result) => {
console.log(
`This configuration is ${result.supported ? "" : "not "}supported,`,
);
console.log(`${result.smooth ? "" : "not "}smooth, and`);
console.log(`${result.powerEfficient ? "" : "not "}power efficient.`);
});
```
Similarly, the code below shows the configuration for a video file.
```js
const mediaConfig = {
type: "file",
video: {
contentType: "video/webm;codecs=vp8", // valid content type
width: 800, // width of the video
height: 600, // height of the video
bitrate: 10000, // number of bits used to encode 1s of video
framerate: 30, // number of frames making up that 1s.
},
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("MediaCapabilities.encodingInfo()")}}
- {{domxref("HTMLMediaElement.canPlayType()")}} for file
- {{domxref("MediaSource.isTypeSupported_static", "MediaSource.isTypeSupported()")}} for media-source
| 0 |
data/mdn-content/files/en-us/web/api/mediacapabilities | data/mdn-content/files/en-us/web/api/mediacapabilities/encodinginfo/index.md | ---
title: "MediaCapabilities: encodingInfo() method"
short-title: encodingInfo()
slug: Web/API/MediaCapabilities/encodingInfo
page-type: web-api-instance-method
browser-compat: api.MediaCapabilities.encodingInfo
---
{{APIRef("MediaCapabilities")}}
The **`MediaCapabilities.encodingInfo()`** method, part of the {{domxref("MediaCapabilities")}} interface of the [Media Capabilities API](/en-US/docs/Web/API/MediaCapabilities), returns a promise with the tested media configuration's capabilities information.
This contains the three boolean properties `supported`, `smooth`, and `powerefficient`, which describe how compatible the device is with the type of media.
## Syntax
```js-nolint
encodingInfo(configuration)
```
### Parameters
- `configuration`
- : An object with a property `type` and _either_ a `video` or `audio` property containing a configuration of the appropriate type: <!-- MediaEncodingConfiguration in the spec -->
- `type`
- : The type of media being tested. This takes one of two values:
- `record`
- : Represents a configuration for recording of media, e.g. using {{domxref("MediaRecorder")}}.
- `webrtc`
- : Represents a configuration meant to be transmitted over electronic means (e.g. using {{domxref("RTCPeerConnection")}}). **Note:** Firefox uses `transmission` for this type, and `webrtc` does not work.
- `transmission` {{non-standard_inline}}
- : The synonym of `webrtc` to be used in Firefox.
- `video`
- : Configuration object for a video media source.
This has the following properties: <!-- VideoConfiguration in the spec -->
- `contentType`
- : String containing a valid video MIME type, and (optionally) a [`codecs` parameter](/en-US/docs/Web/Media/Formats/codecs_parameter).
- `width`
- : The width of the video.
- `height`
- : The height of the video.
- `bitrate`
- : The number of bits used to encode one second of the video file.
- `framerate`
- : The number of frames making up one second of video playback.
- `audio`
- : Configuration object for an audio media source.
This has the following properties: <!-- AudioConfiguration in the spec -->
- `contentType`
- : String containing a valid audio MIME type, and (optionally) a [`codecs` parameter](/en-US/docs/Web/Media/Formats/codecs_parameter).
- `channels`
- : The number of channels used by the audio track.
- `bitrate`
- : The number of bits used to encode one second of the audio file.
- `samplerate`
- : The number of audio samples making up one second of the audio file.
### Return value
A {{jsxref('Promise')}} fulfilling with an object containing three Boolean attributes:
- `supported`
- : `true` if the media content can be decoded at all. Otherwise, it is `false`.
- `smooth`
- : `true` if playback of the media will be smooth (of high quality). Otherwise it is `false`.
- `powerEfficient`
- : `true` if playback of the media will be power efficient. Otherwise, it is `false`.
Browsers will report a supported media configuration as `smooth` and `powerEfficient` until stats on this device have been recorded.
All supported audio codecs are reported to be power efficient.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the `configuration` passed to the `encodingInfo()` method is invalid, which may be for any of the following reasons:
- the type is not video or audio,
- the `contentType` is not a valid codec MIME type,
- there is some other error in the media configuration passed to the method, including omitting any of the `configuration` elements.
## Examples
```js
//Create media configuration to be tested
const mediaConfig = {
type: "record", // or 'transmission'
video: {
contentType: "video/webm;codecs=vp8.0", // valid content type
width: 1920, // width of the video
height: 1080, // height of the video
bitrate: 120000, // number of bits used to encode 1s of video
framerate: 48, // number of frames making up that 1s.
},
};
// check support and performance
navigator.mediaCapabilities.encodingInfo(mediaConfig).then((result) => {
console.log(
`This configuration is ${result.supported ? "" : "not "}supported,`,
);
console.log(`${result.smooth ? "" : "not "}smooth, and`);
console.log(`${result.powerEfficient ? "" : "not "}power efficient.`);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("MediaCapabilities.decodingInfo()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/viewtransition/index.md | ---
title: ViewTransition
slug: Web/API/ViewTransition
page-type: web-api-interface
status:
- experimental
browser-compat: api.ViewTransition
---
{{APIRef("View Transitions API")}}{{SeeCompatTable}}
The **`ViewTransition`** interface of the {{domxref("View Transitions API", "View Transitions API", "", "nocode")}} represents a view transition, and provides functionality to react to the transition reaching different states (e.g. ready to run the animation, or animation finished) or skip the transition altogether.
This object type is returned by the {{domxref("Document.startViewTransition()", "document.startViewTransition()")}} method. When `startViewTransition()` is invoked, a sequence of steps is followed as explained in [The view transition process](/en-US/docs/Web/API/View_Transitions_API#the_view_transition_process). This also explains when the different promises fulfill.
{{InheritanceDiagram}}
## Instance properties
- {{domxref("ViewTransition.finished")}} {{Experimental_Inline}}
- : A {{jsxref("Promise")}} that fulfills once the transition animation is finished, and the new page view is visible and interactive to the user.
- {{domxref("ViewTransition.ready")}} {{Experimental_Inline}}
- : A {{jsxref("Promise")}} that fulfills once the pseudo-element tree is created and the transition animation is about to start.
- {{domxref("ViewTransition.updateCallbackDone")}} {{Experimental_Inline}}
- : A {{jsxref("Promise")}} that fulfills when the promise returned by the {{domxref("Document.startViewTransition()", "document.startViewTransition()")}}'s callback fulfills.
## Instance methods
- {{domxref("ViewTransition.skipTransition", "skipTransition()")}} {{Experimental_Inline}}
- : Skips the animation part of the view transition, but doesn't skip running the {{domxref("Document.startViewTransition()", "document.startViewTransition()")}} callback that updates the DOM.
## Examples
In the following example, the {{domxref("ViewTransition.ready")}} promise is used to trigger a custom circular reveal view transition emanating from the position of the user's cursor on click, with animation provided by the {{domxref("Web Animations API", "Web Animations API", "", "nocode")}}.
```js
// Store the last click event
let lastClick;
addEventListener("click", (event) => (lastClick = event));
function spaNavigate(data) {
// Fallback for browsers that don’t support this API:
if (!document.startViewTransition) {
updateTheDOMSomehow(data);
return;
}
// Get the click position, or fallback to the middle of the screen
const x = lastClick?.clientX ?? innerWidth / 2;
const y = lastClick?.clientY ?? innerHeight / 2;
// Get the distance to the furthest corner
const endRadius = Math.hypot(
Math.max(x, innerWidth - x),
Math.max(y, innerHeight - y),
);
// Create a transition:
const transition = document.startViewTransition(() => {
updateTheDOMSomehow(data);
});
// Wait for the pseudo-elements to be created:
transition.ready.then(() => {
// Animate the root’s new view
document.documentElement.animate(
{
clipPath: [
`circle(0 at ${x}px ${y}px)`,
`circle(${endRadius}px at ${x}px ${y}px)`,
],
},
{
duration: 500,
easing: "ease-in",
// Specify which pseudo-element to animate
pseudoElement: "::view-transition-new(root)",
},
);
});
}
```
This animation also requires the following CSS, to turn off the default CSS animation and stop the old and new view states from blending in any way (the new state "wipes" right over the top of the old state, rather than transitioning in):
```css
::view-transition-image-pair(root) {
isolation: auto;
}
::view-transition-old(root),
::view-transition-new(root) {
animation: none;
mix-blend-mode: normal;
display: block;
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Smooth and simple transitions with the View Transitions API](https://developer.chrome.com/docs/web-platform/view-transitions/)
| 0 |
data/mdn-content/files/en-us/web/api/viewtransition | data/mdn-content/files/en-us/web/api/viewtransition/skiptransition/index.md | ---
title: "ViewTransition: skipTransition() method"
short-title: skipTransition()
slug: Web/API/ViewTransition/skipTransition
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.ViewTransition.skipTransition
---
{{APIRef("View Transitions API")}}{{SeeCompatTable}}
The **`skipTransition()`** method of the
{{domxref("ViewTransition")}} interface skips the animation part of the view transition, but doesn't skip running the {{domxref("Document.startViewTransition()", "document.startViewTransition()")}} callback that updates the DOM.
## Syntax
```js-nolint
skipTransition()
```
### Parameters
None.
### Return value
`undefined`.
## Examples
```js
// start new view transition
const transition = document.startViewTransition(() => displayNewImage());
// skip the animation and just update the DOM
transition.skipTransition();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Smooth and simple transitions with the View Transitions API](https://developer.chrome.com/docs/web-platform/view-transitions/)
| 0 |
data/mdn-content/files/en-us/web/api/viewtransition | data/mdn-content/files/en-us/web/api/viewtransition/ready/index.md | ---
title: "ViewTransition: ready property"
short-title: ready
slug: Web/API/ViewTransition/ready
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ViewTransition.ready
---
{{APIRef("View Transitions API")}}{{SeeCompatTable}}
The **`ready`** read-only property of the
{{domxref("ViewTransition")}} interface is a {{jsxref("Promise")}} that fulfills once the pseudo-element tree is created and the transition animation is about to start.
`ready` will reject if the transition cannot begin. This can be due to misconfiguration, for example duplicate {{cssxref("view-transition-name")}}s, or if the callback passed to {{domxref("Document.startViewTransition()")}} throws or returns a promise that rejects.
## Value
A promise.
## Examples
In the following example, `ready` is used to trigger a custom circular reveal view transition emanating from the position of the user's cursor on click, with animation provided by the {{domxref("Web Animations API", "Web Animations API", "", "nocode")}}.
```js
// Store the last click event
let lastClick;
addEventListener("click", (event) => (lastClick = event));
function spaNavigate(data) {
// Fallback for browsers that don’t support this API:
if (!document.startViewTransition) {
updateTheDOMSomehow(data);
return;
}
// Get the click position, or fallback to the middle of the screen
const x = lastClick?.clientX ?? innerWidth / 2;
const y = lastClick?.clientY ?? innerHeight / 2;
// Get the distance to the furthest corner
const endRadius = Math.hypot(
Math.max(x, innerWidth - x),
Math.max(y, innerHeight - y),
);
// Create a transition:
const transition = document.startViewTransition(() => {
updateTheDOMSomehow(data);
});
// Wait for the pseudo-elements to be created:
transition.ready.then(() => {
// Animate the root’s new view
document.documentElement.animate(
{
clipPath: [
`circle(0 at ${x}px ${y}px)`,
`circle(${endRadius}px at ${x}px ${y}px)`,
],
},
{
duration: 500,
easing: "ease-in",
// Specify which pseudo-element to animate
pseudoElement: "::view-transition-new(root)",
},
);
});
}
```
This animation also requires the following CSS, to turn off the default CSS animation and stop the old and new view states from blending in any way (the new state "wipes" right over the top of the old state, rather than transitioning in):
```css
::view-transition-image-pair(root) {
isolation: auto;
}
::view-transition-old(root),
::view-transition-new(root) {
animation: none;
mix-blend-mode: normal;
display: block;
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Smooth and simple transitions with the View Transitions API](https://developer.chrome.com/docs/web-platform/view-transitions/)
| 0 |
data/mdn-content/files/en-us/web/api/viewtransition | data/mdn-content/files/en-us/web/api/viewtransition/finished/index.md | ---
title: "ViewTransition: finished property"
short-title: finished
slug: Web/API/ViewTransition/finished
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ViewTransition.finished
---
{{APIRef("View Transitions API")}}{{SeeCompatTable}}
The **`finished`** read-only property of the
{{domxref("ViewTransition")}} interface is a {{jsxref("Promise")}} that fulfills once the transition animation is finished, and the new page view is visible and interactive to the user.
`finished` only rejects if the callback passed to {{domxref("Document.startViewTransition()", "document.startViewTransition()")}}throws or returns a promise that rejects, which indicates that the new state of the page wasn't created.
If a transition animation fails to start, or is skipped during the animation using {{domxref("ViewTransition.skipTransition()")}}, the end state is still reached therefore `finished` still fulfills.
## Value
A promise.
## Examples
### Different transitions for different navigations
Sometimes certain navigations will require specifically tailored transitions, for example a 'back' navigation may want a different transition to a 'forward' navigation. The best way to handle such cases is to set a class name on the `<html>` element, handle the transition — applying the correct animation using a tailored selector — and then remove the class name once the transition is finished.
```js
async function handleTransition() {
if (isBackNavigation) {
document.documentElement.classList.add("back-transition");
}
const transition = document.startViewTransition(() =>
updateTheDOMSomehow(data),
);
try {
await transition.finished;
} finally {
document.documentElement.classList.remove("back-transition");
}
}
```
> **Note:** `isBackNavigation` isn't a built-in feature; it's a theoretical function that could perhaps be implemented using the [Navigation API](/en-US/docs/Web/API/Navigation_API) or similar.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Smooth and simple transitions with the View Transitions API](https://developer.chrome.com/docs/web-platform/view-transitions/)
| 0 |
data/mdn-content/files/en-us/web/api/viewtransition | data/mdn-content/files/en-us/web/api/viewtransition/updatecallbackdone/index.md | ---
title: "ViewTransition: updateCallbackDone property"
short-title: updateCallbackDone
slug: Web/API/ViewTransition/updateCallbackDone
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ViewTransition.updateCallbackDone
---
{{APIRef("View Transitions API")}}{{SeeCompatTable}}
The **`updateCallbackDone`** read-only property of the
{{domxref("ViewTransition")}} interface is a {{jsxref("Promise")}} that fulfills when the promise returned by the {{domxref("Document.startViewTransition()", "document.startViewTransition()")}}'s callback fulfills, or rejects when it rejects.
`updateCallbackDone` is useful when you don't care about the success/failure of the transition animation, and just want to know if and when the DOM is updated.
## Value
A promise.
## Examples
```js
// start new view transition
const transition = document.startViewTransition(() => displayNewImage());
transition.updateCallbackDone.then(() => {
// Respond to the DOM being updated successfully
});
```
See [Transitions as an enhancement](https://developer.chrome.com/docs/web-platform/view-transitions/#transitions-as-an-enhancement) for a useful example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Smooth and simple transitions with the View Transitions API](https://developer.chrome.com/docs/web-platform/view-transitions/)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/scheduler/index.md | ---
title: Scheduler
slug: Web/API/Scheduler
page-type: web-api-interface
browser-compat: api.Scheduler
---
{{APIRef("Prioritized Task Scheduling API")}}
The **`Scheduler`** interface of the [Prioritized Task Scheduling API](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API) provides the {{domxref('Scheduler.postTask()')}} method that can be used for adding prioritized tasks to be scheduled.
A `Scheduler` can be accessed from the global object {{domxref("Window")}} or {{domxref("WorkerGlobalScope")}} (`this.scheduler`).
## Instance properties
None.
## Instance methods
- {{domxref('Scheduler.postTask()')}}
- : Adds a task to the scheduler as a callback, optionally specifying a priority, delay, and/or a signal for aborting the task.
## Examples
If the feature is defined, an instance of this object is returned by the global `this` in both workers and the main thread.
The only property of the interface is the {{domxref('Scheduler.postTask()','postTask()')}} method, which is used to post the task and returns a promise.
The code below shows a simple task that resolves with the text 'Task executing'.
This text is logged on success.
The code also shows a `catch` block, which would be required in more complex code to handle when a task is aborted or throws an error.
```js
if ("scheduler" in this) {
// Post task with default priority: 'user-visible' (no other options)
// When the task resolves, Promise.then() logs the result.
scheduler
.postTask(() => "Task executing")
.then((taskResult) => console.log(`${taskResult}`)) // Log result
.catch((error) => console.error(`Error: ${error}`)); // Log errors
}
```
For more comprehensive example code see [Prioritized Task Scheduling API > Examples](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#examples).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/scheduler | data/mdn-content/files/en-us/web/api/scheduler/posttask/index.md | ---
title: "Scheduler: postTask() method"
short-title: postTask()
slug: Web/API/Scheduler/postTask
page-type: web-api-instance-method
browser-compat: api.Scheduler.postTask
---
{{APIRef("Prioritized Task Scheduling API")}}
The **`postTask()`** method of the {{domxref("Scheduler")}} interface is used for adding tasks to be [scheduled](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API) according to their [priority](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#task_priorities).
The method allows users to optionally specify a minimum delay before the task will run, a priority for the task, and a signal that can be used to modify the task priority and/or abort the task.
It returns a promise that is resolved with the result of the task callback function, or rejected with the abort reason or an error thrown in the task.
Task priority can be [mutable or immutable](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#mutable_and_immutable_task_priority).
If the task priority will never need to change then it should be set using the `options.priority` parameter (any priority set through a signal will then be ignored).
You can still pass an {{domxref("AbortSignal")}} (which has no priority) or {{domxref("TaskSignal")}} to the `options.signal` parameter for aborting the task.
If the task priority might need to be changed the `options.priority` parameter must not be set.
Instead a {{domxref("TaskController")}} should be created and its {{domxref("TaskSignal")}} should be passed to `options.signal`.
The task priority will be initialized from the signal priority, and can later be modified using the signal's associated {{domxref("TaskController")}}.
If no priority is set then the task priority defaults to [`"user-visible"`](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#user-visible).
If a delay is specified and greater than 0, then the execution of the task will be delayed for at least that many milliseconds.
Otherwise the task is immediately scheduled for prioritization.
## Syntax
```js-nolint
postTask(callback)
postTask(callback, options)
```
### Parameters
- `callback`
- : An callback function that implements the task.
The return value of the callback is used to resolve the promise returned by this function.
- `options` {{optional_inline}}
- : Task options, including:
- `priority` {{optional_inline}}
- : The immutable [priority](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#task_priorities) of the task.
One of: [`"user-blocking"`](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#user-blocking), [`"user-visible"`](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#user-visible), [`"background"`](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#background).
If set, this priority is used for the lifetime of the task and priority set on the `signal` is ignored.
- `signal` {{optional_inline}}
- : A {{domxref("TaskSignal")}} or {{domxref("AbortSignal")}} that can be used to abort the task (from its associated controller).
If the `options.priority` parameter is set then the task priority cannot be changed, and any priority on the signal is ignored.
Otherwise, if the signal is a {{domxref("TaskSignal")}} its priority is used to set the initial task priority, and the signal's controller may later use it to change the task priority.
- `delay` {{optional_inline}}
- : The minimum amount of time after which the task will be added to the scheduler queue, in whole milliseconds.
The actual delay may be higher than specified, but will not be less.
The default delay is 0.
### Return Value
Returns a {{jsxref("Promise")}} that is resolved with the return value of the `callback` function, or which may be rejected with the `signal`'s abort reason ({{domxref("AbortSignal.reason")}}).
The promise may also be rejected with an error thrown by the callback during execution.
## Examples
The following examples are slightly simplified versions of the live examples provided in [Prioritized Task Scheduling API > Examples](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#examples).
### Feature checking
Check whether prioritized task scheduling is supported by testing for the `scheduler` property in the global "`this`" (such as [`Window.scheduler`](/en-US/docs/Web/API/Window#scheduler)).
For example, the code below logs "Feature: Supported" if the API is supported on this browser.
```js
// Check that feature is supported
if ("scheduler" in this) {
console.log("Feature: Supported");
} else {
console.error("Feature: NOT Supported");
}
```
### Basic usage
Tasks are posted specifying a callback function (task) in the first argument, and an optional second argument that can be used to specify a task priority, signal, and/or delay.
The method returns a {{jsxref("Promise")}} that resolves with the return value of the callback function, or rejects with either an abort error or an error thrown in the function.
Because it returns a promise, `postTask()` can be [chained with other promises](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#chained_promises).
Below we show how to wait on the promise to resolve using [`then`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) or reject using [`catch`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch).
The priority is not specified, so the default priority of `user-visible` will be used.
```js
// A function that defines a task
function myTask() {
return "Task 1: user-visible";
}
// Post task with default priority: 'user-visible' (no other options)
// When the task resolves, Promise.then() logs the result.
scheduler
.postTask(myTask, { signal: abortTaskController.signal })
.then((taskResult) => console.log(`${taskResult}`)) // Log resolved value
.catch((error) => console.error("Error:", error)); // Log error or abort
```
The method can also be used with [`await`](/en-US/docs/Web/JavaScript/Reference/Operators/await) inside an [async function](/en-US/docs/Web/JavaScript/Reference/Statements/async_function).
The code below shows how you might use this approach to wait on a `user-blocking` task.
```js
function myTask2() {
return "Task 2: user-blocking";
}
async function runTask2() {
const result = await scheduler.postTask(myTask2, {
priority: "user-blocking",
});
console.log(result); // 'Task 2: user-blocking'.
}
runTask2();
```
### Permanent priorities
[Task priorities](#task_priorities) may be set using `priority` parameter in the optional second argument.
Priorities that are set in this way cannot be changed (are [immutable](#mutable_and_immutable_task_priority)).
Below we post two groups of three tasks, each member in reverse order of priority.
The final task has the default priority.
When run, each task simply logs it's expected order (we're not waiting on the result because we don't need to in order to show execution order).
```js
// three tasks, in reverse order of priority
scheduler.postTask(() => console.log("bckg 1"), { priority: "background" });
scheduler.postTask(() => console.log("usr-vis 1"), {
priority: "user-visible",
});
scheduler.postTask(() => console.log("usr-blk 1"), {
priority: "user-blocking",
});
// three more tasks, in reverse order of priority
scheduler.postTask(() => console.log("bckg 2"), { priority: "background" });
scheduler.postTask(() => console.log("usr-vis 2"), {
priority: "user-visible",
});
scheduler.postTask(() => console.log("usr-blk 2"), {
priority: "user-blocking",
});
// Task with default priority: user-visible
scheduler.postTask(() => {
console.log("usr-vis 3 (default)");
});
```
The expected output is shown below: tasks are executed in priority order, and then declaration order.
```plain
usr-blk 1
usr-blk 2
usr-vis 1
usr-vis 2
usr-vis 3 (default)
bckg 1
bckg 2
```
### Changing task priorities
[Task priorities](#task_priorities) can also take their initial value from a {{domxref("TaskSignal")}} passed to `postTask()` in the optional second argument.
If set in this way, the priority of the task [can then be changed](#mutable_and_immutable_task_priority) using the controller associated with the signal.
> **Note:** Setting and changing task priorities using a signal only works when the `options.priority` argument to `postTask()` is not set, and when the `options.signal` is a {{domxref("TaskSignal")}} (and not an {{domxref("AbortSignal")}}).
The code below first shows how to create a {{domxref("TaskController")}}, setting the initial priority of its signal to `user-blocking` in the [`TaskController()` constructor](/en-US/docs/Web/API/TaskController/TaskController).
We then use `addEventListener()` to add an event listener to the controller's signal (we could alternatively use the `TaskSignal.onprioritychange` property to add an event handler).
The event handler uses {{domxref('TaskPriorityChangeEvent.previousPriority', 'previousPriority')}} on the event to get the original priority and {{domxref("TaskSignal.priority")}} on the event target to get the new/current priority.
```js
// Create a TaskController, setting its signal priority to 'user-blocking'
const controller = new TaskController({ priority: "user-blocking" });
// Listen for 'prioritychange' events on the controller's signal.
controller.signal.addEventListener("prioritychange", (event) => {
const previousPriority = event.previousPriority;
const newPriority = event.target.priority;
console.log(`Priority changed from ${previousPriority} to ${newPriority}.`);
});
```
Finally, the task is posted, passing in the signal, and then we immediately change the priority to `background` by calling {{domxref("TaskController.setPriority()")}} on the controller.
```js
// Post task using the controller's signal.
// The signal priority sets the initial priority of the task
scheduler.postTask(() => console.log("Task 1"), { signal: controller.signal });
// Change the priority to 'background' using the controller
controller.setPriority("background");
```
The expected output is shown below.
Note that in this case the priority is changed before the task is executed, but it could equally have been changed while the task was running.
```js
// Expected output
// Priority changed from user-blocking to background.
// Task 1
```
### Aborting tasks
Tasks can be aborted using either {{domxref("TaskController")}} and {{domxref("AbortController")}}, in exactly the same way.
The only difference is that you must use {{domxref("TaskController")}} if you also want to set the task priority.
The code below creates a controller and passes its signal to the task.
The task is then immediately aborted.
This causes the promise to be rejected with an `AbortError`, which is caught in the `catch` block and logged.
Note that we could also have listened for the [`abort` event](/en-US/docs/Web/API/AbortSignal/abort_event) fired on the {{domxref("TaskSignal")}} or {{domxref("AbortSignal")}} and logged the abort there.
```js
// Declare a TaskController with default priority
const abortTaskController = new TaskController();
// Post task passing the controller's signal
scheduler
.postTask(() => console.log("Task executing"), {
signal: abortTaskController.signal,
})
.then((taskResult) => console.log(`${taskResult}`)) //This won't run!
.catch((error) => console.error("Error:", error)); // Log the error
// Abort the task
abortTaskController.abort();
```
### Delaying tasks
Tasks can be delayed by specifying an integer number of milliseconds in the `options.delay` parameter to `postTask()`.
This effectively adds the task to the prioritized queue on a timeout, as might be created using [`setTimeout()`](/en-US/docs/Web/API/setTimeout).
The `delay` is the minimum amount of time before the task is added to the scheduler; it may be longer.
The code below shows two tasks added (as arrow functions) with a delay.
```js
// Post task as arrow function with delay of 2 seconds
scheduler
.postTask(() => "Task delayed by 2000ms", { delay: 2000 })
.then((taskResult) => console.log(`${taskResult}`));
scheduler
.postTask(() => "Next task should complete in about 2000ms", { delay: 1 })
.then((taskResult) => console.log(`${taskResult}`));
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/stylepropertymapreadonly/index.md | ---
title: StylePropertyMapReadOnly
slug: Web/API/StylePropertyMapReadOnly
page-type: web-api-interface
browser-compat: api.StylePropertyMapReadOnly
---
{{APIRef("CSS Typed Object Model API")}}
The **`StylePropertyMapReadOnly`** interface of the [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Object_Model#css_typed_object_model) provides a read-only representation of a CSS declaration block that is an alternative to {{domxref("CSSStyleDeclaration")}}. Retrieve an instance of this interface using {{domxref('Element.computedStyleMap','Element.computedStyleMap()')}}.
## Instance properties
- {{domxref('StylePropertyMapReadOnly.size')}}
- : Returns an unsigned long integer containing the size of the `StylePropertyMapReadOnly` object.
## Instance methods
- {{domxref('StylePropertyMapReadOnly.entries()')}}
- : Returns an array of a given object's own enumerable property `[key, value]` pairs, in the same order as that provided by a {{jsxref("Statements/for...in", "for...in")}} loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
- {{domxref('StylePropertyMapReadOnly.forEach()')}}
- : Executes a provided function once for each element of `StylePropertyMapReadOnly`.
- {{domxref('StylePropertyMapReadOnly.get()')}}
- : Returns the value of the specified property.
- {{domxref('StylePropertyMapReadOnly.getAll()')}}
- : Returns an array of {{domxref("CSSStyleValue")}} objects containing the values for the provided property.
- {{domxref('StylePropertyMapReadOnly.has()')}}
- : Indicates whether the specified property is in the `StylePropertyMapReadOnly` object.
- {{domxref('StylePropertyMapReadOnly.keys()')}}
- : Returns a new _array iterator_ containing the keys for each item in `StylePropertyMapReadOnly`.
- {{domxref('StylePropertyMapReadOnly.values()')}}
- : Returns a new _array iterator_ containing the values for each index in the `StylePropertyMapReadOnly` object.
## Examples
We have to have an element to observe:
```html
<p>
This is a paragraph with some text. We can add some CSS, or not. The style map
will include all the default and inherited CSS property values.
</p>
<dl id="output"></dl>
```
We add a touch of CSS with a custom property to better demonstrate the output:
```css
p {
--someVariable: 1.6em;
--someOtherVariable: translateX(33vw);
--anotherVariable: 42;
line-height: var(--someVariable);
}
```
We add JavaScript to grab our paragraph and return back a definition list of all the default CSS property values using {{domxref('Element.computedStyleMap()')}}.
```js
// get the element
const myElement = document.querySelector("p");
// get the <dl> we'll be populating
const stylesList = document.querySelector("#output");
// Retrieve all computed styles with computedStyleMap()
const stylePropertyMap = myElement.computedStyleMap();
// iterate through the map of all the properties and values, adding a <dt> and <dd> for each
for (const [prop, val] of stylePropertyMap) {
// properties
const cssProperty = document.createElement("dt");
cssProperty.innerText = prop;
stylesList.appendChild(cssProperty);
// values
const cssValue = document.createElement("dd");
cssValue.innerText = val;
stylesList.appendChild(cssValue);
}
```
{{EmbedLiveSample("Examples", 120, 300)}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/stylepropertymapreadonly | data/mdn-content/files/en-us/web/api/stylepropertymapreadonly/get/index.md | ---
title: "StylePropertyMapReadOnly: get() method"
short-title: get()
slug: Web/API/StylePropertyMapReadOnly/get
page-type: web-api-instance-method
browser-compat: api.StylePropertyMapReadOnly.get
---
{{APIRef("CSS Typed Object Model API")}}
The **`get()`** method of the
{{domxref("StylePropertyMapReadOnly")}} interface returns a {{domxref("CSSStyleValue")}}
object for the first value of the specified property.
## Syntax
```js-nolint
get(property)
```
### Parameters
- `property`
- : The name of the property to retrieve the value of.
### Return value
A {{domxref("CSSStyleValue")}} object.
## Examples
Let's get just a few properties and values. Let's start by creating a link inside a
paragraph in our HTML, and adding a definition list which we will populate with
JavaScript:
```html
<p>
<a href="https://example.com">Link</a>
</p>
<dl id="results"></dl>
```
We add a bit of CSS, including a custom property and an inheritable property:
```css
p {
font-weight: bold;
}
a {
--color: red;
color: var(--color);
}
```
We use the Element's
[`computedStyleMap()`](/en-US/docs/Web/API/Element/computedStyleMap)
to return a _StylePropertyMapReadOnly_ object. We create an array of properties
of interest and use the StylePropertyMapReadOnly's `get()` method to get only
those values.
```js
// get the element
const myElement = document.querySelector("a");
// Retrieve all computed styles with computedStyleMap()
const styleMap = myElement.computedStyleMap();
// get the <dl> we'll be populating
const stylesList = document.querySelector("#results");
// array of properties we're interested in
const ofInterest = ["font-weight", "border-left-color", "color", "--color"];
// iterate over our properties of interest
for (const property of ofInterest) {
// properties
const cssProperty = document.createElement("dt");
cssProperty.innerText = property;
stylesList.appendChild(cssProperty);
// values
const cssValue = document.createElement("dd");
// use get() to find the value
cssValue.innerText = styleMap.get(property);
stylesList.appendChild(cssValue);
}
```
{{EmbedLiveSample("Examples", 120, 300)}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API)
- [Learning Houdini: the CSS Typed Object Model](/en-US/docs/Web/API/CSS_Typed_OM_API/Guide)
| 0 |
data/mdn-content/files/en-us/web/api/stylepropertymapreadonly | data/mdn-content/files/en-us/web/api/stylepropertymapreadonly/has/index.md | ---
title: "StylePropertyMapReadOnly: has() method"
short-title: has()
slug: Web/API/StylePropertyMapReadOnly/has
page-type: web-api-instance-method
browser-compat: api.StylePropertyMapReadOnly.has
---
{{APIRef("CSS Typed Object Model API")}}
The **`has()`** method of the
{{domxref("StylePropertyMapReadOnly")}} interface indicates whether the specified
property is in the `StylePropertyMapReadOnly` object.
## Syntax
```js-nolint
has(property)
```
### Parameters
- `property`
- : The name of a property.
### Return value
A boolean value.
## Examples
Here we use the `has()` method to see if the padding-top property is present
within the button elements style attribute.
```js
// get the button element
const buttonEl = document.querySelector(".example");
// find what's in the style attribute with attributeStyleMap and has()
const hasPadTop = buttonEl.attributeStyleMap.has("padding-top");
console.log(hasPadTop); // logs true if padding-top is present in style attribute
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/stylepropertymapreadonly | data/mdn-content/files/en-us/web/api/stylepropertymapreadonly/keys/index.md | ---
title: "StylePropertyMapReadOnly: keys() method"
short-title: keys()
slug: Web/API/StylePropertyMapReadOnly/keys
page-type: web-api-instance-method
browser-compat: api.StylePropertyMapReadOnly.keys
---
{{APIRef("CSS Typed Object Model API")}}
The **`StylePropertyMapReadOnly.keys()`** method returns a new
_array iterator_ containing the keys for each item
in `StylePropertyMapReadOnly`
## Syntax
```js-nolint
keys()
```
### Parameters
None.
### Return value
A new {{jsxref("Array")}}.
## Examples
In this example we use the `keys()` method to be able to access the
properties within our {{domxref('Element.computedStyleMap()')}}.
```js
// get a button element
const buttonEl = document.querySelector("button");
// we can retrieve all computed styles with `computedStyleMap`
const allComputedStyles = buttonEl.computedStyleMap();
// keys returns an iterable list of properties
const props = allComputedStyles.keys();
console.log(props.next().value); // returns align-content
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/stylepropertymapreadonly | data/mdn-content/files/en-us/web/api/stylepropertymapreadonly/size/index.md | ---
title: "StylePropertyMapReadOnly: size property"
short-title: size
slug: Web/API/StylePropertyMapReadOnly/size
page-type: web-api-instance-property
browser-compat: api.StylePropertyMapReadOnly.size
---
{{APIRef("CSS Typed Object Model API")}}
The **`size`** read-only property of the
{{domxref("StylePropertyMapReadOnly")}} interface returns an unsigned long integer
containing the size of the `StylePropertyMapReadOnly` object.
## Value
An unsigned long integer.
## Examples
Here we use the size property to return the total entries within the button elements
{{domxref('Element.computedStyleMap()','computedStyleMap')}}.
```js
// grab our element
const buttonEl = document.querySelector("button");
// we can retrieve all computed styles with `computedStyleMap`
const allComputedStyles = buttonEl.computedStyleMap();
// use size to get the total styles within the map
const amountStyles = allComputedStyles.size;
console.log(amountStyles); // logs 338
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/stylepropertymapreadonly | data/mdn-content/files/en-us/web/api/stylepropertymapreadonly/values/index.md | ---
title: "StylePropertyMapReadOnly: values() method"
short-title: values()
slug: Web/API/StylePropertyMapReadOnly/values
page-type: web-api-instance-method
browser-compat: api.StylePropertyMapReadOnly.values
---
{{APIRef("CSS Typed Object Model API")}}
The **`StylePropertyMapReadOnly.values()`** method returns a
new _array iterator_ containing the values for each index in the
`StylePropertyMapReadOnly` object.
## Syntax
```js-nolint
values()
```
### Parameters
None.
### Return value
A new {{jsxref("Array")}}.
## Examples
In this example we use the `values()` method to be able to access the values
within our [`Element.computedStyleMap()`](/en-US/docs/Web/API/Element/computedStyleMap).
```js
// get a button element
const buttonEl = document.querySelector("button");
// we can retrieve all computed styles with `computedStyleMap`
const allComputedStyles = buttonEl.computedStyleMap();
// values returns an iterable list of the CSS values
const vals = allComputedStyles.values();
console.log(vals.next().value); // returns a CSSStyleValue
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/stylepropertymapreadonly | data/mdn-content/files/en-us/web/api/stylepropertymapreadonly/getall/index.md | ---
title: "StylePropertyMapReadOnly: getAll() method"
short-title: getAll()
slug: Web/API/StylePropertyMapReadOnly/getAll
page-type: web-api-instance-method
browser-compat: api.StylePropertyMapReadOnly.getAll
---
{{APIRef("CSS Typed Object Model API")}}
The **`getAll()`** method of the
{{domxref("StylePropertyMapReadOnly")}} interface returns an array of
{{domxref("CSSStyleValue")}} objects containing the values for the provided property.
## Syntax
```js-nolint
getAll(property)
```
### Parameters
- `property`
- : The name of the property to retrieve all values of.
### Return value
An array of {{domxref("CSSStyleValue")}} objects.
## Examples
The following example uses `getAll()` with the
{{cssxref('background-image')}} property. An {{jsxref('Array')}} is returned which
contains an item for each background image declared.
```js
// get a button element
const buttonEl = document.querySelector("button");
// we can retrieve all computed styles with `computedStyleMap`
const allComputedStyles = buttonEl.computedStyleMap();
// use getAll() with the background image property
const allBkImages = allComputedStyles.getAll("background-image");
console.log(allBkImages); // logs an array with each background image as an item
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/stylepropertymapreadonly | data/mdn-content/files/en-us/web/api/stylepropertymapreadonly/foreach/index.md | ---
title: "StylePropertyMapReadOnly: forEach() method"
short-title: forEach()
slug: Web/API/StylePropertyMapReadOnly/forEach
page-type: web-api-instance-method
browser-compat: api.StylePropertyMapReadOnly.forEach
---
{{APIRef("CSS Typed Object Model API")}}
The **`StylePropertyMapReadOnly.forEach()`** method executes a
provided function once for each element of {{domxref('StylePropertyMapReadOnly')}}.
## Syntax
```js-nolint
forEach(callbackFn)
forEach(callbackFn, thisArg)
```
### Parameters
- `callbackFn`
- : The function to execute for each element, taking three arguments:
- `currentValue`
- : The value of the current element being processed.
- `index` {{optional_inline}}
- : The index of the current element being processed.
- `array` {{optional_inline}}
- : The StylePropertyMapReadOnly that `forEach()` is being called on.
- `thisArg` {{Optional_inline}}
- : Value to use as **`this`** (i.e., the reference
`Object`) when executing `callback`.
### Return value
None ({{jsxref("undefined")}}).
## Examples
Here is an example of using `forEach()` on a retrieved
{{domxref('Element.computedStyleMap()')}}.
```js
// get a button element
const buttonEl = document.querySelector(".example");
// we can retrieve all computed styles with `computedStyleMap`
const allComputedStyles = buttonEl.computedStyleMap();
// forEach will allow us to run code over each prop/val pair
allComputedStyles.forEach((elem, index, arr) => {
// code to run for each pair
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/stylepropertymapreadonly | data/mdn-content/files/en-us/web/api/stylepropertymapreadonly/entries/index.md | ---
title: "StylePropertyMapReadOnly: entries() method"
short-title: entries()
slug: Web/API/StylePropertyMapReadOnly/entries
page-type: web-api-instance-method
browser-compat: api.StylePropertyMapReadOnly.entries
---
{{APIRef("CSS Typed Object Model API")}}
The **`StylePropertyMapReadOnly.entries()`** method returns an
array of a given object's own enumerable property `[key, value]` pairs, in
the same order as that provided by a {{jsxref("Statements/for...in", "for...in")}} loop
(the difference being that a for-in loop enumerates properties in the prototype chain as
well).
## Syntax
```js-nolint
entries()
```
### Parameters
None.
### Return value
An array of the given `StylePropertyMapReadOnly` object's own enumerable
property `[key, value]` pairs.
## Examples
Here shows an example of using `StylePropertyMapReadOnly.entries()` method
on an elements computed styles.
```js
// grab a DOM element
const buttonEl = document.querySelector("button");
// we can retrieve all computed styles with `computedStyleMap`
const allComputedStyles = buttonEl.computedStyleMap();
// entries returns an iterable of the items
const iterableStyles = allComputedStyles.entries();
// returns a two item array with align-content as the first item and CSSStyleValue as the second
console.log(iterableStyles.next().value);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/domtokenlist/index.md | ---
title: DOMTokenList
slug: Web/API/DOMTokenList
page-type: web-api-interface
browser-compat: api.DOMTokenList
---
{{APIRef("DOM")}}
The **`DOMTokenList`** interface represents a set of space-separated tokens. Such a set is returned by {{domxref("Element.classList")}} or {{domxref("HTMLLinkElement.relList")}}, and many others.
A `DOMTokenList` is indexed beginning with `0` as with JavaScript {{jsxref("Array")}} objects. `DOMTokenList` is always case-sensitive.
## Instance properties
- {{domxref("DOMTokenList.length")}} {{ReadOnlyInline}}
- : An `integer` representing the number of objects stored in the object.
- {{domxref("DOMTokenList.value")}}
- : A {{Glossary("stringifier")}} property that returns the value of the list as a string.
## Instance methods
- {{domxref("DOMTokenList.item()")}}
- : Returns the item in the list by its index, or `null` if the index is greater than or equal to the list's `length`.
- {{domxref("DOMTokenList.contains()")}}
- : Returns `true` if the list contains the given token, otherwise `false`.
- {{domxref("DOMTokenList.add()")}}
- : Adds the specified tokens to the list.
- {{domxref("DOMTokenList.remove()")}}
- : Removes the specified tokens from the list.
- {{domxref("DOMTokenList.replace()")}}
- : Replaces the token with another one.
- {{domxref("DOMTokenList.supports()")}}
- : Returns `true` if the given token is in the associated attribute's supported tokens.
- {{domxref("DOMTokenList.toggle()")}}
- : Removes the token from the list if it exists, or adds it to the list if it doesn't. Returns a boolean indicating whether the token is in the list after the operation.
- {{domxref("DOMTokenList.entries()")}}
- : Returns an {{jsxref("Iteration_protocols", "iterator", "", 1)}}, allowing you to go through all key/value pairs contained in this object.
- {{domxref("DOMTokenList.forEach()")}}
- : Executes a provided callback function once for each `DOMTokenList` element.
- {{domxref("DOMTokenList.keys()")}}
- : Returns an {{jsxref("Iteration_protocols", "iterator", "", 1)}}, allowing you to go through all keys of the key/value pairs contained in this object.
- {{domxref("DOMTokenList.values()")}}
- : Returns an {{jsxref("Iteration_protocols", "iterator", "", 1)}}, allowing you to go through all values of the key/value pairs contained in this object.
## Examples
In the following simple example, we retrieve the list of classes set on a {{htmlelement("p")}} element as a `DOMTokenList` using {{domxref("Element.classList")}}, add a class using {{domxref("DOMTokenList.add()")}}, and then update the {{domxref("Node.textContent")}} of the `<p>` to equal the `DOMTokenList`.
First, the HTML:
```html
<p class="a b c"></p>
```
Now the JavaScript:
```js
let para = document.querySelector("p");
let classes = para.classList;
para.classList.add("d");
para.textContent = `paragraph classList is "${classes}"`;
```
The output looks like this:
{{ EmbedLiveSample('Examples', '100%', 60) }}
## Trimming of whitespace and removal of duplicates
Methods that modify the `DOMTokenList` (such as {{domxref("DOMTokenList.add()")}}) automatically trim any excess {{Glossary("Whitespace")}} and remove duplicate values from the list. For example:
```html
<span class=" d d e f"></span>
```
```js
let span = document.querySelector("span");
let classes = span.classList;
span.classList.add("x");
span.textContent = `span classList is "${classes}"`;
```
The output looks like this:
{{ EmbedLiveSample('Trimming_of_whitespace_and_removal_of_duplicates', '100%', 60) }}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/domtokenlist | data/mdn-content/files/en-us/web/api/domtokenlist/remove/index.md | ---
title: "DOMTokenList: remove() method"
short-title: remove()
slug: Web/API/DOMTokenList/remove
page-type: web-api-instance-method
browser-compat: api.DOMTokenList.remove
---
{{APIRef("DOM")}}
The **`remove()`** method of the {{domxref("DOMTokenList")}} interface
removes the specified _tokens_ from the list.
## Syntax
```js-nolint
remove(token1)
remove(token1, token2)
remove(token1, token2, /* …, */ tokenN)
```
### Parameters
- `token1`, …, `tokenN`
- : A string representing the token you want to remove from the list.
If the string is not in the list, no error is thrown, and nothing happens.
### Return value
None ({{jsxref("undefined")}}).
## Examples
In the following example we retrieve the list of classes set on a
{{htmlelement("span")}} element as a `DOMTokenList` using
{{domxref("Element.classList")}}. We then remove a token from the list, and write the
list into the `<span>`'s {{domxref("Node.textContent")}}.
First, the HTML:
```html
<div id="ab" class="a b c"></div>
<div id="a" class="a b c"></div>
```
Now the JavaScript:
```js
const span = document.getElementById("ab");
const classes = span.classList;
classes.remove("c");
span.textContent = classes;
```
To remove multiple classes at once, you can supply multiple tokens. The order you
supply the tokens doesn't have to match the order they appear in the list:
```js
const span2 = document.getElementById("a");
const classes2 = span2.classList;
classes2.remove("c", "b");
span2.textContent = classes2;
```
The output looks like this:
{{ EmbedLiveSample('Examples', '100%', 60) }}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/domtokenlist | data/mdn-content/files/en-us/web/api/domtokenlist/add/index.md | ---
title: "DOMTokenList: add() method"
short-title: add()
slug: Web/API/DOMTokenList/add
page-type: web-api-instance-method
browser-compat: api.DOMTokenList.add
---
{{APIRef("DOM")}}
The **`add()`** method of the {{domxref("DOMTokenList")}} interface adds the given tokens to the list, omitting any that are already present.
## Syntax
```js-nolint
add(token1)
add(token1, token2)
add(token1, token2, /* …, */ tokenN)
```
### Parameters
- `tokenN`
- : A string representing a token (or tokens) to add to the `DOMTokenList`.
### Return value
None.
### Exceptions
- `SyntaxError` {{domxref("DOMException")}}
- : Thrown if one of the arguments is an empty string
- `InvalidCharacterError` {{domxref("DOMException")}}
- : Thrown if a token contains ASCII whitespace.
## Examples
In the following example, we retrieve the list of classes set on a {{htmlelement("span")}} element as a `DOMTokenList`, using {{domxref("Element.classList")}}.
We then add a new token to the list, and write the list into the `<span>`'s {{domxref("Node.textContent")}}.
First, the HTML:
```html
<span class="a b c"></span>
```
Now the JavaScript:
```js
const span = document.querySelector("span");
const classes = span.classList;
classes.add("d");
span.textContent = classes;
```
The output looks like this:
{{ EmbedLiveSample('Examples', '100%', 60) }}
You can add multiple tokens as well:
```js
span.classList.add("d", "e", "f");
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/domtokenlist | data/mdn-content/files/en-us/web/api/domtokenlist/length/index.md | ---
title: "DOMTokenList: length property"
short-title: length
slug: Web/API/DOMTokenList/length
page-type: web-api-instance-property
browser-compat: api.DOMTokenList.length
---
{{APIRef("DOM")}}
The read-only **`length`** property of the {{domxref("DOMTokenList")}} interface is an `integer` representing the number
of objects stored in the object.
## Value
An positive integer, or `0` if the list is empty.
## Examples
In the following example we retrieve the list of classes set on a
{{htmlelement("span")}} element as a `DOMTokenList` using
{{domxref("Element.classList")}}, then write the length of the list to the
`<span>`'s {{domxref("Node.textContent")}}.
First, the HTML:
```html
<span class="a b c"></span>
```
Now the JavaScript:
```js
const span = document.querySelector("span");
const classes = span.classList;
const length = classes.length;
span.textContent = `classList length = ${length}`;
```
The output looks like this:
{{ EmbedLiveSample('Examples', '100%', 60) }}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/domtokenlist | data/mdn-content/files/en-us/web/api/domtokenlist/supports/index.md | ---
title: "DOMTokenList: supports() method"
short-title: supports()
slug: Web/API/DOMTokenList/supports
page-type: web-api-instance-method
browser-compat: api.DOMTokenList.supports
---
{{APIRef("DOM")}}
The **`supports()`** method of the {{domxref("DOMTokenList")}} interface
returns `true` if a given `token` is in the associated attribute's supported tokens.
This method is intended to support feature detection.
## Syntax
```js-nolint
supports(token)
```
### Parameters
- `token`
- : A string containing the token to query for.
### Returns
A boolean value indicating whether the token was found.
## Example
```js
const iframe = document.getElementById("display");
if (iframe.sandbox.supports("an-upcoming-feature")) {
// support code for mystery future feature
} else {
// fallback code
}
if (iframe.sandbox.supports("allow-scripts")) {
// instruct frame to run JavaScript
//
// (NOTE: This feature is well-supported; this is just an example!)
//
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/domtokenlist | data/mdn-content/files/en-us/web/api/domtokenlist/keys/index.md | ---
title: "DOMTokenList: keys() method"
short-title: keys()
slug: Web/API/DOMTokenList/keys
page-type: web-api-instance-method
browser-compat: api.DOMTokenList.keys
---
{{APIRef("DOM")}}
The **`keys()`** method of the {{domxref("DOMTokenList")}} interface
returns an {{jsxref("Iteration_protocols",'iterator',"",1)}} allowing to go through all keys contained in this object.
The keys are unsigned integers.
## Syntax
```js-nolint
keys()
```
### Parameters
None.
### Return value
Returns an {{jsxref("Iteration_protocols","iterator","",1)}}.
## Examples
In the following example we retrieve the list of classes set on a
{{htmlelement("span")}} element as a `DOMTokenList` using
{{domxref("Element.classList")}}. We then retrieve an iterator containing the keys using `keys()`,
then iterate through those keys using a [for...of](/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loop,
writing each one to the `<span>`'s {{domxref("Node.textContent")}}.
First, the HTML:
```html
<span class="a b c"></span>
```
Now the JavaScript:
```js
const span = document.querySelector("span");
const classes = span.classList;
const iterator = classes.keys();
for (let value of iterator) {
span.textContent += `(${value}) `;
}
```
The output looks like this:
{{ EmbedLiveSample('Examples', '100%', 60) }}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("DOMTokenList.entries()")}}, {{domxref("DOMTokenList.forEach()")}} and {{domxref("DOMTokenList.values")}}.
| 0 |
data/mdn-content/files/en-us/web/api/domtokenlist | data/mdn-content/files/en-us/web/api/domtokenlist/item/index.md | ---
title: "DOMTokenList: item() method"
short-title: item()
slug: Web/API/DOMTokenList/item
page-type: web-api-instance-method
browser-compat: api.DOMTokenList.item
---
{{APIRef("DOM")}}
The **`item()`** method of the {{domxref("DOMTokenList")}} interface returns an item in the list,
determined by its position in the list, its index.
> **Note:** This method is equivalent as the [bracket notation](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#bracket_notation).
> So `aList.item(i)` is the same as `aList[i]`.
## Syntax
```js-nolint
tokenList.item(index)
```
### Parameters
- `index`
- : A number representing the index of the item you want to return. If it isn't an integer, only the integer part is considered.
### Return value
A string representing the returned item,
or `null` if the number is greater than or equal to the `length` of the list.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the `index` cannot be converted to an integer.
## Examples
In the following example we retrieve the list of classes set on a
{{htmlelement("span")}} element as a `DOMTokenList` using
{{domxref("Element.classList")}}. We then retrieve the last item in the list using
`item(tokenList.length - 1)`, and write it into the
`<span>`'s {{domxref("Node.textContent")}}.
First, the HTML:
```html
<span class="a b c"></span>
```
Now the JavaScript:
```js
const span = document.querySelector("span");
const classes = span.classList;
const item = classes.item(classes.length - 1);
span.textContent = item;
```
The output looks like this:
{{ EmbedLiveSample('Examples', '100%', 60) }}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.