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/websocket | data/mdn-content/files/en-us/web/api/websocket/websocket/index.md | ---
title: "WebSocket: WebSocket() constructor"
short-title: WebSocket()
slug: Web/API/WebSocket/WebSocket
page-type: web-api-constructor
browser-compat: api.WebSocket.WebSocket
---
{{APIRef("WebSockets API")}}
The **`WebSocket()`** constructor returns a new
{{domxref("WebSocket")}} object.
## Syntax
```js-nolint
new WebSocket(url)
new WebSocket(url, protocols)
```
### Parameters
- `url`
- : The URL to which to connect; this should be the URL to which the WebSocket server
will respond.
- `protocols` {{optional_inline}}
- : Either a single protocol string or an array of protocol strings. These strings are
used to indicate sub-protocols, so that a single server can implement multiple
WebSocket sub-protocols (for example, you might want one server to be able to handle
different types of interactions depending on the specified `protocol`).
If it is omitted, an empty array is used by default, i.e. `[]`.
### Exceptions
- `SyntaxError` {{domxref("DOMException")}}
- : Thrown if:
- parsing of [`url`](#url) fails
- [`url`](#url) has a scheme other than `ws` or `wss`
- [`url`](#url) has a [fragment](/en-US/docs/Web/HTTP/Basics_of_HTTP/Identifying_resources_on_the_Web#fragment)
- any of the values in [`protocols`](#protocols) occur more than once, or otherwise fail to match the requirements for elements that comprise the value of [`Sec-WebSocket-Protocol`](/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism#sec-websocket-protocol) fields as defined by the WebSocket Protocol specification
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [RFC 6455](https://www.rfc-editor.org/rfc/rfc6455.html) (the WebSocket Protocol specification)
| 0 |
data/mdn-content/files/en-us/web/api/websocket | data/mdn-content/files/en-us/web/api/websocket/bufferedamount/index.md | ---
title: "WebSocket: bufferedAmount property"
short-title: bufferedAmount
slug: Web/API/WebSocket/bufferedAmount
page-type: web-api-instance-property
browser-compat: api.WebSocket.bufferedAmount
---
{{APIRef("WebSockets API")}}
The **`WebSocket.bufferedAmount`** read-only property returns
the number of bytes of data that have been queued using calls to [`send()`](/en-US/docs/Web/API/WebSocket/send) but
not yet transmitted to the network. This value resets to zero once all queued data has
been sent. This value does not reset to zero when the connection is closed; if you keep
calling [`send()`](/en-US/docs/Web/API/WebSocket/send), this will continue to climb.
## Value
An `unsigned long`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/websocket | data/mdn-content/files/en-us/web/api/websocket/readystate/index.md | ---
title: "WebSocket: readyState property"
short-title: readyState
slug: Web/API/WebSocket/readyState
page-type: web-api-instance-property
browser-compat: api.WebSocket.readyState
---
{{APIRef("WebSockets API")}}
The **`WebSocket.readyState`** read-only property returns the
current state of the {{domxref("WebSocket")}} connection.
## Value
One of the following `unsigned short` values:
| Value | State | Description |
| ----- | ------------ | -------------------------------------------------------- |
| `0` | `CONNECTING` | Socket has been created. The connection is not yet open. |
| `1` | `OPEN` | The connection is open and ready to communicate. |
| `2` | `CLOSING` | The connection is in the process of closing. |
| `3` | `CLOSED` | The connection is closed or couldn't be opened. |
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/websocket | data/mdn-content/files/en-us/web/api/websocket/message_event/index.md | ---
title: "WebSocket: message event"
short-title: message
slug: Web/API/WebSocket/message_event
page-type: web-api-event
browser-compat: api.WebSocket.message_event
---
{{APIRef("WebSockets API")}}
The `message` event is fired when data is received through a `WebSocket`.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("message", (event) => {});
onmessage = (event) => {};
```
## Event type
A {{domxref("MessageEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("MessageEvent")}}
## Event properties
_In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._
- {{domxref("MessageEvent.data", "data")}} {{ReadOnlyInline}}
- : The data sent by the message emitter. The type of this property depends on the type of the WebSocket message and the value of {{domxref("WebSocket.binaryType")}}.
- If the message type is "text", then this field is a string.
- If the message type is "binary" type, then the type of this property can be inferred from the `binaryType` of this socket:
- {{jsxref("ArrayBuffer")}} if `binaryType` is `"arraybuffer"`,
- {{domxref("Blob")}} if `binaryType` is `"blob"`. This does not have an associated media type ({{domxref("Blob.type")}} is `""`).
- {{domxref("MessageEvent.origin", "origin")}} {{ReadOnlyInline}}
- : A string representing the origin of the message emitter.
Other properties from the {{domxref("MessageEvent")}} interface are present, but do not pertain to the WebSocket API and are left at their default values:
- {{domxref("MessageEvent.lastEventId", "lastEventId")}} {{ReadOnlyInline}}
- {{domxref("MessageEvent.source", "source")}} {{ReadOnlyInline}}
- {{domxref("MessageEvent.ports", "ports")}} {{ReadOnlyInline}}
## Examples
```js
// Create WebSocket connection.
const socket = new WebSocket("ws://localhost:8080");
// Listen for messages
socket.addEventListener("message", (event) => {
console.log("Message from server ", event.data);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebSocket: close event](/en-US/docs/Web/API/WebSocket/close_event)
- [WebSocket: error event](/en-US/docs/Web/API/WebSocket/error_event)
- [WebSocket: open event](/en-US/docs/Web/API/WebSocket/open_event)
- [Writing WebSocket client applications](/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications)
| 0 |
data/mdn-content/files/en-us/web/api/websocket | data/mdn-content/files/en-us/web/api/websocket/protocol/index.md | ---
title: "WebSocket: protocol property"
short-title: protocol
slug: Web/API/WebSocket/protocol
page-type: web-api-instance-property
browser-compat: api.WebSocket.protocol
---
{{APIRef("WebSockets API")}}
The **`WebSocket.protocol`** read-only property returns the
name of the sub-protocol the server selected; this will be one of the strings specified
in the `protocols` parameter when creating the {{domxref("WebSocket")}}
object, or the empty string if no connection is established.
## Value
A string.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/websocket | data/mdn-content/files/en-us/web/api/websocket/close/index.md | ---
title: "WebSocket: close() method"
short-title: close()
slug: Web/API/WebSocket/close
page-type: web-api-instance-method
browser-compat: api.WebSocket.close
---
{{APIRef("WebSockets API")}}
The **`WebSocket.close()`** method closes the
{{domxref("WebSocket")}} connection or connection attempt, if any. If the connection is
already `CLOSED`, this method does nothing.
> **Note:** The process of closing the connection begins with a [closing handshake](https://www.rfc-editor.org/rfc/rfc6455.html#section-1.4), and the `close()` method does not discard previously-sent messages before starting that closing handshake; even if the user agent is still busy sending those messages, the handshake will only start after the messages are sent.
## Syntax
```js-nolint
close()
close(code)
close(code, reason)
```
### Parameters
- `code` {{optional_inline}}
- : An integer [WebSocket connection close code](https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.5) value indicating a reason for closure:
- If unspecified, a close code for the connection is automatically set: to `1000` for a normal closure, or otherwise to [another standard value in the range `1001`-`1015`](https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1) that indicates the actual reason the connection was closed.
- If specified, the value of this `code` parameter overrides the automatic setting of the close code for the connection, and instead sets a custom code.
The value must be an integer: either `1000`, or else a custom code of your choosing in the range `3000`-`4999`. If you specify a `code` value, you should also specify a [`reason`](#reason) value.
- `reason` {{optional_inline}}
- : A string providing a custom [WebSocket connection close reason](https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.6) (a concise human-readable prose explanation for the closure). The value must be no longer than 123 bytes (encoded in UTF-8).
> **Note:** Because [UTF-8 uses two to four bytes](/en-US/docs/Glossary/UTF-8) to encode any non-[ASCII](/en-US/docs/Glossary/ASCII) characters, a 123-character `reason` value containing non-ASCII characters would exceed the 123-byte limit.
If you specify a `reason` value, you should also specify a [`code`](#code) value.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- `InvalidAccessError` {{domxref("DOMException")}}
- : Thrown if [`code`](#code) is neither an integer equal to `1000` nor an integer in the range `3000` – `4999`.
- `SyntaxError` {{domxref("DOMException")}}
- : Thrown if the UTF-8-encoded [`reason`](#reason) value is longer than 123 bytes.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [RFC 6455](https://www.rfc-editor.org/rfc/rfc6455.html) (the WebSocket Protocol specification)
| 0 |
data/mdn-content/files/en-us/web/api/websocket | data/mdn-content/files/en-us/web/api/websocket/error_event/index.md | ---
title: "WebSocket: error event"
short-title: error
slug: Web/API/WebSocket/error_event
page-type: web-api-event
browser-compat: api.WebSocket.error_event
---
{{APIRef("WebSockets API")}}
The `error` event is fired when a connection with a `WebSocket` has been closed due to an error (some data couldn't be sent for example).
## 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
```js
// Create WebSocket connection
const socket = new WebSocket("ws://localhost:8080");
// Listen for possible errors
socket.addEventListener("error", (event) => {
console.log("WebSocket error: ", event);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebSocket: close event](/en-US/docs/Web/API/WebSocket/close_event)
- [WebSocket: message event](/en-US/docs/Web/API/WebSocket/message_event)
- [WebSocket: open event](/en-US/docs/Web/API/WebSocket/open_event)
- [Writing WebSocket client applications](/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/rtctrackevent/index.md | ---
title: RTCTrackEvent
slug: Web/API/RTCTrackEvent
page-type: web-api-interface
browser-compat: api.RTCTrackEvent
---
{{APIRef("WebRTC")}}
The [WebRTC API](/en-US/docs/Web/API/WebRTC_API) interface **`RTCTrackEvent`** represents the {{domxref("RTCPeerConnection.track_event", "track")}} event, which is sent when a new {{domxref("MediaStreamTrack")}} is added to an {{domxref("RTCRtpReceiver")}} which is part of the {{domxref("RTCPeerConnection")}}.
The target is the `RTCPeerConnection` object to which the track is being added.
This event is sent by the WebRTC layer to the website or application, so you will not typically need to instantiate an `RTCTrackEvent` yourself.
{{InheritanceDiagram}}
## Constructor
- {{domxref("RTCTrackEvent.RTCTrackEvent", "RTCTrackEvent()")}}
- : Creates and returns a new `RTCTrackEvent` object. You will probably not need to create new track events yourself, since they're typically created by the WebRTC infrastructure and sent to the connection's {{domxref("RTCPeerConnection.track_event", "ontrack")}} event handler.
## Instance properties
_Since `RTCTrackEvent` is based on {{domxref("Event")}}, its properties are also available._
- {{domxref("RTCTrackEvent.receiver", "receiver")}} {{ReadOnlyInline}}
- : The {{domxref("RTCRtpReceiver")}} used by the track that's been added to the `RTCPeerConnection`.
- {{domxref("RTCTrackEvent.streams", "streams")}} {{ReadOnlyInline}} {{optional_inline}}
- : An array of {{domxref("MediaStream")}} objects, each representing one of the media streams to which the added {{domxref("RTCTrackEvent.track", "track")}} belongs. By default, the array is empty, indicating a streamless track.
- {{domxref("RTCTrackEvent.track", "track")}} {{ReadOnlyInline}}
- : The {{domxref("MediaStreamTrack")}} which has been added to the connection.
- {{domxref("RTCTrackEvent.transceiver", "transceiver")}} {{ReadOnlyInline}}
- : The {{domxref("RTCRtpTransceiver")}} being used by the new track.
## Track event types
There is only one type of track event.
### `track`
The {{domxref("RTCPeerConnection.track_event", "track")}} event is sent to the {{domxref("RTCPeerConnection")}} when a new track has been added to the connection. By the time the `track` event is delivered to the `RTCPeerConnection`'s {{domxref("RTCPeerConnection.track_event", "ontrack")}} handler, the new media has completed its negotiation for a specific {{domxref("RTCRtpReceiver")}} (which is specified by the event's {{domxref("RTCTrackEvent.receiver", "receiver")}} property).
In addition, the {{domxref("MediaStreamTrack")}} specified by the receiver's {{domxref("RTCRtpReceiver.track", "track")}} is the same one specified by the event's {{domxref("RTCTrackEvent.track", "track")}}, and the track has been added to any associated remote {{domxref("MediaStream")}} objects.
You can add a `track` event listener to be notified when the new track is available so that you can, for example, attach its media to a {{HTMLElement("video")}} element, using either {{domxref("EventTarget.addEventListener", "RTCPeerConnection.addEventListener()")}} or the `ontrack` event handler property.
> **Note:** It may be helpful to keep in mind that you receive the `track` event when a new inbound track has been added to your connection, and you call {{domxref("RTCPeerConnection.addTrack", "addTrack()")}} to add a track to the far end of the connection, thereby triggering a `track` event on the remote peer.
## Example
This simple example creates an event listener for the {{domxref("RTCPeerConnection.track_event", "track")}} event which sets the {{domxref("HTMLMediaElement.srcObject", "srcObject")}} of the {{HTMLElement("video")}} element with the ID `videobox` to the first stream in the list passed in the event's {{domxref("RTCTrackEvent.streams", "streams")}} array.
```js
peerConnection.addEventListener(
"track",
(e) => {
let videoElement = document.getElementById("videobox");
videoElement.srcObject = e.streams[0];
},
false,
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtctrackevent | data/mdn-content/files/en-us/web/api/rtctrackevent/transceiver/index.md | ---
title: "RTCTrackEvent: transceiver property"
short-title: transceiver
slug: Web/API/RTCTrackEvent/transceiver
page-type: web-api-instance-property
browser-compat: api.RTCTrackEvent.transceiver
---
{{APIRef("WebRTC")}}
The WebRTC API interface {{domxref("RTCTrackEvent")}}'s
read-only **`transceiver`** property indicates the
{{domxref("RTCRtpTransceiver")}} affiliated with the event's
{{domxref("RTCTrackEvent.track", "track")}}.
The transceiver pairs the track's
{{domxref("RTCTrackEvent.receiver", "receiver")}} with an {{domxref("RTCRtpSender")}}.
## Value
The {{domxref("RTCRtpTransceiver")}} which pairs the `receiver` with a
sender and other properties which establish a single bidirectional {{Glossary("RTP", "SRTP")}}
stream for use by the {{domxref("RTCTrackEvent.track", "track")}} associated with the
`RTCTrackEvent`.
> **Note:** The {{domxref("RTCRtpReceiver")}} referred to by this
> `RTCRtpReceiver`'s {{domxref("RTCRtpTransceiver.receiver", "receiver")}}
> property will always be the same as the {{domxref("RTCTrackEvent")}}'s
> {{domxref("RTCTrackEvent.receiver", "receiver")}} property.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtctrackevent | data/mdn-content/files/en-us/web/api/rtctrackevent/receiver/index.md | ---
title: "RTCTrackEvent: receiver property"
short-title: receiver
slug: Web/API/RTCTrackEvent/receiver
page-type: web-api-instance-property
browser-compat: api.RTCTrackEvent.receiver
---
{{APIRef("WebRTC")}}
The read-only **`receiver`** property
of the {{domxref("RTCTrackEvent")}} interface indicates the
{{domxref("RTCRtpReceiver")}} which is used to receive data containing media for the
{{domxref("RTCTrackEvent.track", "track")}} to which the event refers.
## Value
The {{domxref("RTCRtpTransceiver")}} which pairs the `receiver` with a
sender and other properties which establish a single bidirectional {{Glossary("RTP", "SRTP")}}
stream for use by the {{domxref("RTCTrackEvent.track", "track")}} associated with the
`RTCTrackEvent`.
> **Note:** The {{domxref("RTCTrackEvent.transceiver", "transceiver")}}
> includes its own {{domxref("RTCRtpTransceiver.receiver", "receiver")}} property, which
> will always be the same {{domxref("RTCRtpReceiver")}} as this one.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtctrackevent | data/mdn-content/files/en-us/web/api/rtctrackevent/rtctrackevent/index.md | ---
title: "RTCTrackEvent: RTCTrackEvent() constructor"
short-title: RTCTrackEvent()
slug: Web/API/RTCTrackEvent/RTCTrackEvent
page-type: web-api-constructor
browser-compat: api.RTCTrackEvent.RTCTrackEvent
---
{{APIRef("WebRTC")}}
The **`RTCTrackEvent()`** constructor creates and returns a new {{domxref("RTCTrackEvent")}} object,
configured to describe the track which has been added to the {{domxref("RTCPeerConnection")}}.
In general, you won't need to use this constructor, as `RTCTrackEvent`
objects are created by WebRTC and delivered to your `RTCPeerConnector`'s
{{domxref("RTCPeerConnection.track_event", "ontrack")}} event handler as appropriate.
## Syntax
```js-nolint
new RTCTrackEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers always set it to `track`.
- `options`
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties:
- `receiver`
- : The {{domxref("RTCRtpReceiver")}} which is being used to receive the track's media.
- `streams` {{optional_inline}}
- : An array of {{domxref("MediaStream")}} objects representing each of the streams that comprise the event's corresponding track.
It defaults to an empty array.
- `track`
- : The {{domxref("MediaStreamTrack")}} the event is associated with.
- `transceiver`
- : The {{domxref("RTCRtpTransceiver")}} associated with the event.
### Return value
A new {{domxref("RTCTrackEvent")}} describing a track which has been added to the
`RTCPeerConnection`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtctrackevent | data/mdn-content/files/en-us/web/api/rtctrackevent/streams/index.md | ---
title: "RTCTrackEvent: streams property"
short-title: streams
slug: Web/API/RTCTrackEvent/streams
page-type: web-api-instance-property
browser-compat: api.RTCTrackEvent.streams
---
{{APIRef("WebRTC")}}
The [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
interface {{domxref("RTCTrackEvent")}}'s read-only
**`streams`** property specifies an array of
{{domxref("MediaStream")}} objects, one for each of the streams that comprise the
track being added to the {{domxref("RTCPeerConnection")}}.
## Value
An {{jsxref("Array")}} of {{domxref("MediaStream")}} objects, one for each stream that
make up the new track.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtctrackevent | data/mdn-content/files/en-us/web/api/rtctrackevent/track/index.md | ---
title: "RTCTrackEvent: track property"
short-title: track
slug: Web/API/RTCTrackEvent/track
page-type: web-api-instance-property
browser-compat: api.RTCTrackEvent.track
---
{{APIRef("WebRTC")}}
The [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
interface {{domxref("RTCTrackEvent")}}'s read-only **`track`**
property specifies the {{domxref("MediaStreamTrack")}} that has been added to the
{{domxref("RTCPeerConnection")}}.
## Value
A {{domxref("MediaStreamTrack")}} indicating the track which has been added to the
{{domxref("RTCPeerConnection")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgfepointlightelement/index.md | ---
title: SVGFEPointLightElement
slug: Web/API/SVGFEPointLightElement
page-type: web-api-interface
browser-compat: api.SVGFEPointLightElement
---
{{APIRef("SVG")}}
The **`SVGFEPointLightElement`** interface corresponds to the {{SVGElement("fePointLight")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._
- {{domxref("SVGFEPointLightElement.x")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("x")}} attribute of the given element.
- {{domxref("SVGFEPointLightElement.y")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("y")}} attribute of the given element.
- {{domxref("SVGFEPointLightElement.z")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("z")}} attribute of the given element.
## Instance methods
_This interface does not provide any specific methods, but implements those of its parent, {{domxref("SVGElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{SVGElement("fePointLight")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties/index.md | ---
title: BluetoothCharacteristicProperties
slug: Web/API/BluetoothCharacteristicProperties
page-type: web-api-interface
status:
- experimental
browser-compat: api.BluetoothCharacteristicProperties
---
{{APIRef("Bluetooth API")}}{{securecontext_header}}{{SeeCompatTable}}
The **`BluetoothCharacteristicProperties`** interface of the [Web Bluetooth API](/en-US/docs/Web/API/Web_Bluetooth_API) provides the operations that are valid on the given {{domxref('BluetoothRemoteGATTCharacteristic')}}.
This interface is returned by calling {{DOMxRef("BluetoothRemoteGATTCharacteristic.properties")}}.
## Instance properties
- {{DOMxRef("BluetoothCharacteristicProperties.authenticatedSignedWrites","authenticatedSignedWrites")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a `boolean` that is `true` if signed writing to the characteristic value is permitted.
- {{DOMxRef("BluetoothCharacteristicProperties.broadcast", "broadcast")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a `boolean` that is `true` if the broadcast of the characteristic value is permitted using the Server Characteristic Configuration Descriptor.
- {{DOMxRef("BluetoothCharacteristicProperties.indicate","indicate")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a `boolean` that is `true` if indications of the characteristic value with acknowledgement is permitted.
- {{DOMxRef("BluetoothCharacteristicProperties.notify","notify")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a `boolean` that is `true` if notifications of the characteristic value without acknowledgement is permitted.
- {{DOMxRef("BluetoothCharacteristicProperties.read", "read")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a `boolean` that is `true` if the reading of the characteristic value is permitted.
- {{DOMxRef("BluetoothCharacteristicProperties.reliableWrite","reliableWrite")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a `boolean` that is `true` if reliable writes to the characteristic is permitted.
- {{DOMxRef("BluetoothCharacteristicProperties.writableAuxiliaries","writableAuxiliaries")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a `boolean` that is `true` if reliable writes to the characteristic descriptor is permitted.
- {{DOMxRef("BluetoothCharacteristicProperties.write","write")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a `boolean` that is `true` if the writing to the characteristic with response is permitted.
- {{DOMxRef("BluetoothCharacteristicProperties.writeWithoutResponse","writeWithoutResponse")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a `boolean` that is `true` if the writing to the characteristic without response is permitted.
## Examples
The following example shows how tell if a GATT characteristic supports value change notifications.
```js
let device = await navigator.bluetooth.requestDevice({
filters: [{ services: ["heart_rate"] }],
});
let gatt = await device.gatt.connect();
let service = await gatt.getPrimaryService("heart_rate");
let characteristic = await service.getCharacteristic("heart_rate_measurement");
if (characteristic.properties.notify) {
characteristic.addEventListener(
"characteristicvaluechanged",
async (event) => {
console.log(`Received heart rate measurement: ${event.target.value}`);
},
);
await characteristic.startNotifications();
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties | data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties/reliablewrite/index.md | ---
title: "BluetoothCharacteristicProperties: reliableWrite property"
short-title: reliableWrite
slug: Web/API/BluetoothCharacteristicProperties/reliableWrite
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.BluetoothCharacteristicProperties.reliableWrite
---
{{securecontext_header}}{{APIRef("Bluetooth API")}}{{SeeCompatTable}}
The **`reliableWrite`** read-only property of
the {{domxref("BluetoothCharacteristicProperties")}} interface returns a
`boolean` that is `true` if reliable writes to the characteristic
is permitted.
## Value
A boolean value.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties | data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties/writewithoutresponse/index.md | ---
title: "BluetoothCharacteristicProperties: writeWithoutResponse property"
short-title: writeWithoutResponse
slug: Web/API/BluetoothCharacteristicProperties/writeWithoutResponse
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.BluetoothCharacteristicProperties.writeWithoutResponse
---
{{securecontext_header}}{{APIRef("Bluetooth API")}}{{SeeCompatTable}}
The **`writeWithoutResponse`** read-only
property of the {{domxref("BluetoothCharacteristicProperties")}} interface returns a
`boolean` that is `true` if the writing to the characteristic
without response is permitted.
## Value
A boolean value.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties | data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties/read/index.md | ---
title: "BluetoothCharacteristicProperties: read property"
short-title: read
slug: Web/API/BluetoothCharacteristicProperties/read
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.BluetoothCharacteristicProperties.read
---
{{securecontext_header}}{{APIRef("Bluetooth API")}}{{SeeCompatTable}}
The **`read`** read-only property of the
{{domxref("BluetoothCharacteristicProperties")}} interface returns a
`boolean` that is `true` if the reading of the characteristic
value is permitted.
## Value
A boolean value.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties | data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties/write/index.md | ---
title: "BluetoothCharacteristicProperties: write property"
short-title: write
slug: Web/API/BluetoothCharacteristicProperties/write
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.BluetoothCharacteristicProperties.write
---
{{securecontext_header}}{{APIRef("Bluetooth API")}}{{SeeCompatTable}}
The **`write`** read-only property of the
{{domxref("BluetoothCharacteristicProperties")}} interface returns a
`boolean` that is `true` if the writing to the characteristic with
response is permitted.
## Value
A boolean value.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
null
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties | data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties/notify/index.md | ---
title: "BluetoothCharacteristicProperties: notify property"
short-title: notify
slug: Web/API/BluetoothCharacteristicProperties/notify
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.BluetoothCharacteristicProperties.notify
---
{{securecontext_header}}{{APIRef("")}}{{SeeCompatTable}}
The **`notify`** read-only property of the
{{domxref("BluetoothCharacteristicProperties")}} interface returns a
`boolean` that is `true` if notifications of the characteristic
value without acknowledgement is permitted.
## Value
A boolean value.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties | data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties/authenticatedsignedwrites/index.md | ---
title: "BluetoothCharacteristicProperties: authenticatedSignedWrites property"
short-title: authenticatedSignedWrites
slug: Web/API/BluetoothCharacteristicProperties/authenticatedSignedWrites
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.BluetoothCharacteristicProperties.authenticatedSignedWrites
---
{{securecontext_header}}{{APIRef("Bluetooth API")}}{{SeeCompatTable}}
The **`authenticatedSignedWrites`** read-only
property of the {{domxref("BluetoothCharacteristicProperties")}} interface returns a
`boolean` that is `true` if signed writing to the characteristic
value is permitted.
## Value
A boolean value.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties | data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties/writableauxiliaries/index.md | ---
title: "BluetoothCharacteristicProperties: writableAuxiliaries property"
short-title: writableAuxiliaries
slug: Web/API/BluetoothCharacteristicProperties/writableAuxiliaries
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.BluetoothCharacteristicProperties.writableAuxiliaries
---
{{securecontext_header}}{{APIRef("Bluetooth API")}}{{SeeCompatTable}}
The **`writableAuxiliaries`** read-only
property of the {{domxref("BluetoothCharacteristicProperties")}} interface returns a
`boolean` that is `true` if reliable writes to the characteristic
descriptor is permitted.
## Value
A boolean value.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties | data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties/broadcast/index.md | ---
title: "BluetoothCharacteristicProperties: broadcast property"
short-title: broadcast
slug: Web/API/BluetoothCharacteristicProperties/broadcast
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.BluetoothCharacteristicProperties.broadcast
---
{{securecontext_header}}{{APIRef("Bluetooth API")}}{{SeeCompatTable}}
The **`broadcast`** read-only property of the
{{domxref("BluetoothCharacteristicProperties")}} interface returns a
`boolean` that is `true` if the broadcast of the characteristic
value is permitted using the Server Characteristic Configuration Descriptor.
## Value
A boolean value.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties | data/mdn-content/files/en-us/web/api/bluetoothcharacteristicproperties/indicate/index.md | ---
title: "BluetoothCharacteristicProperties: indicate property"
short-title: indicate
slug: Web/API/BluetoothCharacteristicProperties/indicate
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.BluetoothCharacteristicProperties.indicate
---
{{securecontext_header}}{{APIRef("Bluetooth API")}}{{SeeCompatTable}}
The **`indicate`** read-only property of the
{{domxref("BluetoothCharacteristicProperties")}} interface returns a
`boolean` that is `true` if indications of the characteristic
value with acknowledgement is permitted.
## Value
A boolean value.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svghkernelement/index.md | ---
title: SVGHKernElement
slug: Web/API/SVGHKernElement
page-type: web-api-interface
status:
- deprecated
browser-compat: api.SVGHKernElement
---
{{APIRef("SVG")}}{{deprecated_header}}
The **`SVGHKernElement`** interface corresponds to the {{SVGElement("hkern")}} elements.
Object-oriented access to the attributes of the {{SVGElement("hkern")}} element via the SVG DOM is not possible.
{{InheritanceDiagram}}
## Instance properties
_This interface has no properties but inherits properties from its parent, {{domxref("SVGElement")}}._
## Instance methods
_This interface has no methods but inherits methods from its parent, {{domxref("SVGElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{SVGElement("hkern")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/viewtimeline/index.md | ---
title: ViewTimeline
slug: Web/API/ViewTimeline
page-type: web-api-interface
status:
- experimental
browser-compat: api.ViewTimeline
---
{{APIRef("Web Animations")}}{{SeeCompatTable}}
The **`ViewTimeline`** interface of the {{domxref("Web Animations API", "Web Animations API", "", "nocode")}} represents a view progress timeline (see [CSS scroll-driven animations](/en-US/docs/Web/CSS/CSS_scroll-driven_animations) for more details).
Pass a `ViewTimeline` instance to the {{domxref("Animation.Animation", "Animation()")}} constructor or the {{domxref("Element.animate()", "animate()")}} method to specify it as the timeline that will control the progress of the animation.
{{InheritanceDiagram}}
## Constructor
- {{domxref("ViewTimeline.ViewTimeline", "ViewTimeline()")}} {{Experimental_Inline}}
- : Creates a new `ViewTimeline` object instance.
## Instance properties
_This interface also inherits the properties of its parent, {{domxref("ScrollTimeline")}}._
- {{domxref("ViewTimeline.subject", "subject")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a reference to the subject element whose visibility within its nearest ancestor scrollable element (scroller) is driving the progress of the timeline and therefore the animation.
- {{domxref("ViewTimeline.startOffset", "startOffset")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a {{domxref("CSSNumericValue")}} representing the starting (0% progress) scroll position of the timeline as an offset from the start of the overflowing section of content in the scroller.
- {{domxref("ViewTimeline.endOffset", "endOffset")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a {{domxref("CSSNumericValue")}} representing the ending (100% progress) scroll position of the timeline as an offset from the start of the overflowing section of content in the scroller.
## Instance methods
_This interface inherits the methods of its parent, {{domxref("ScrollTimeline")}}._
## Examples
### Displaying the subject and offsets of a view progress timeline
In this example, we animate an element with a `class` of `subject` along a view progress timeline — it animates when moved upwards through the document as it scrolls. We also output the `subject`, `startOffset`, and `endOffset` values to an output element in the top-right corner.
#### HTML
The HTML for the example is shown below.
```html
<div class="content">
<h1>Content</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Risus quis varius quam
quisque id. Et ligula ullamcorper malesuada proin libero nunc consequat
interdum varius. Elit ullamcorper dignissim cras tincidunt lobortis feugiat
vivamus at augue.
</p>
<p>
Dolor sed viverra ipsum nunc aliquet. Sed sed risus pretium quam vulputate
dignissim. Tortor aliquam nulla facilisi cras. A erat nam at lectus urna
duis convallis convallis. Nibh ipsum consequat nisl vel pretium lectus.
Sagittis aliquam malesuada bibendum arcu vitae elementum. Malesuada bibendum
arcu vitae elementum curabitur vitae nunc sed velit.
</p>
<div class="subject animation"></div>
<p>
Adipiscing enim eu turpis egestas pretium aenean pharetra magna ac. Arcu
cursus vitae congue mauris rhoncus aenean vel. Sit amet cursus sit amet
dictum. Augue neque gravida in fermentum et. Gravida rutrum quisque non
tellus orci ac auctor augue mauris. Risus quis varius quam quisque id diam
vel quam elementum. Nibh praesent tristique magna sit amet purus gravida
quis. Duis ultricies lacus sed turpis tincidunt id aliquet. In egestas erat
imperdiet sed euismod nisi. Eget egestas purus viverra accumsan in nisl nisi
scelerisque. Netus et malesuada fames ac.
</p>
<div class="output"></div>
</div>
```
#### CSS
The CSS for the example looks like this:
```css
.subject {
width: 300px;
height: 200px;
margin: 0 auto;
background-color: deeppink;
}
.content {
width: 75%;
max-width: 800px;
margin: 0 auto;
}
.output {
position: fixed;
top: 5px;
right: 5px;
}
p,
h1,
div {
font-family: Arial, Helvetica, sans-serif;
}
h1 {
font-size: 3rem;
}
p {
font-size: 1.5rem;
line-height: 1.5;
}
```
#### JavaScript
In the JavaScript, we grab references to the `subject` and `output` `<div>`s, then create a new {{domxref("ViewTimeline")}}, associating it with the `subject` element to specify that the timeline progress is based on this element's visibility through its scrolling ancestor, setting a `block` axis, and setting `inset` values to adjust the position of the box in which the subject is deemed to be visible.
We then animate the `subject` element with the Web Animations API. Last of all, we display the `subject`, `startOffset`, and `endOffset` values in the `output` element.
```js
const subject = document.querySelector(".subject");
const output = document.querySelector(".output");
const timeline = new ViewTimeline({
subject,
axis: "block",
inset: [CSS.px("200"), CSS.px("300")],
});
subject.animate(
{
opacity: [0, 1],
transform: ["scaleX(0)", "scaleX(1)"],
},
{
fill: "both",
timeline,
},
);
output.textContent += `Subject element: ${timeline.subject.nodeName}, `;
output.textContent += `start offset: ${timeline.startOffset}, `;
output.textContent += `end offset: ${timeline.endOffset}.`;
```
#### Result
Scroll to see the subject element being animated.
{{EmbedLiveSample("Tracking the progress of a view progress timeline", "100%", "480px")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
- [CSS scroll-driven animations](/en-US/docs/Web/CSS/CSS_scroll-driven_animations)
- {{domxref("AnimationTimeline")}}, {{domxref("ScrollTimeline")}}
| 0 |
data/mdn-content/files/en-us/web/api/viewtimeline | data/mdn-content/files/en-us/web/api/viewtimeline/startoffset/index.md | ---
title: "ViewTimeline: startOffset property"
short-title: startOffset
slug: Web/API/ViewTimeline/startOffset
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ViewTimeline.startOffset
---
{{APIRef("Web Animations")}}{{SeeCompatTable}}
The **`startOffset`** read-only property of the {{domxref("ViewTimeline")}} interface returns a {{domxref("CSSNumericValue")}} representing the starting (0% progress) scroll position of the timeline as an offset from the start of the overflowing section of content in the scroller.
## Value
A {{domxref("CSSNumericValue")}}.
## Examples
See the main {{domxref("ScrollTimeline")}} page for an example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
- [CSS scroll-driven animations](/en-US/docs/Web/CSS/CSS_scroll-driven_animations)
- {{domxref("ViewTimeline")}}
- {{domxref("AnimationTimeline")}}, {{domxref("ScrollTimeline")}}
| 0 |
data/mdn-content/files/en-us/web/api/viewtimeline | data/mdn-content/files/en-us/web/api/viewtimeline/viewtimeline/index.md | ---
title: "ViewTimeline: ViewTimeline() constructor"
short-title: ViewTimeline()
slug: Web/API/ViewTimeline/ViewTimeline
page-type: web-api-constructor
status:
- experimental
browser-compat: api.ViewTimeline.ViewTimeline
---
{{APIRef("History API")}}{{SeeCompatTable}}
The **`ViewTimeline()`** constructor creates a new {{domxref("ViewTimeline")}} object instance.
## Syntax
```js-nolint
new ViewTimeline(options)
```
### Parameters
- `options`
- : An object that can contain the following properties:
- `subject`
- : A reference to an {{domxref("Element")}} representing the subject element whose visibility within its nearest ancestor scrollable element (scroller) will drive the progress of the timeline.
- `axis` {{optional_inline}}
- : An enumerated value representing the scroll axis that will drive the progress of the timeline. Possible values are:
- `"block"`: The scrollbar on the block axis of the scroll container, which is the axis in the direction perpendicular to the flow of text within a line. For horizontal writing modes, such as standard English, this is the same as `"y"`, while for vertical writing modes, it is the same as `"x"`.
- `"inline"`: The scrollbar on the inline axis of the scroll container, which is the axis in the direction parallel to the flow of text in a line. For horizontal writing modes, this is the same as `"x"`, while for vertical writing modes, this is the same as `"y"`.
- `"y"`: The scrollbar on the vertical axis of the scroll container.
- `"x"`: The scrollbar on the horizontal axis of the scroll container.
If omitted, `axis` defaults to `"block"`.
- `inset` {{optional_inline}}
- : A value or array of values representing an adjustment to the position of the scrollport (see {{glossary("Scroll container")}} for more details) in which the subject is deemed to be visible. Possible values are:
- `"auto"`: The default box position is used.
- A string: If a string is specified, it can consist of one or two values equal to `auto` or a CSS {{cssxref("length-percentage")}} value. To put it another way, the string should be a valid {{cssxref("view-timeline-inset")}} value.
- An array of one or two values, which can be `"auto"` or a suitable {{domxref("CSSNumericValue")}} to represent a length or percentage offset (for example `CSS.px()` or `CSS.percent()`. If an array is provided, the first value represents the start inset (which affects the {{domxref("ViewTimeline.endOffset")}} value) and the second value represents the end inset (which affects the {{domxref("ViewTimeline.startOffset")}} value).
If the array has only one value, it is duplicated.
If omitted, `inset` defaults to `auto`.
### Return value
A new {{domxref("ViewTimeline")}} object instance.
## Examples
See the main {{domxref("ViewTimeline")}} page for an example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
- [CSS scroll-driven animations](/en-US/docs/Web/CSS/CSS_scroll-driven_animations)
- {{domxref("ViewTimeline")}}
- {{domxref("AnimationTimeline")}}, {{domxref("ScrollTimeline")}}
| 0 |
data/mdn-content/files/en-us/web/api/viewtimeline | data/mdn-content/files/en-us/web/api/viewtimeline/endoffset/index.md | ---
title: "ViewTimeline: endOffset property"
short-title: endOffset
slug: Web/API/ViewTimeline/endOffset
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ViewTimeline.endOffset
---
{{APIRef("Web Animations")}}{{SeeCompatTable}}
The **`endOffset`** read-only property of the {{domxref("ViewTimeline")}} interface returns a {{domxref("CSSNumericValue")}} representing the ending (100% progress) scroll position of the timeline as an offset from the start of the overflowing section of content in the scroller.
## Value
A {{domxref("CSSNumericValue")}}.
## Examples
See the main {{domxref("ScrollTimeline")}} page for an example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
- [CSS scroll-driven animations](/en-US/docs/Web/CSS/CSS_scroll-driven_animations)
- {{domxref("ViewTimeline")}}
- {{domxref("AnimationTimeline")}}, {{domxref("ScrollTimeline")}}
| 0 |
data/mdn-content/files/en-us/web/api/viewtimeline | data/mdn-content/files/en-us/web/api/viewtimeline/subject/index.md | ---
title: "ViewTimeline: subject property"
short-title: subject
slug: Web/API/ViewTimeline/subject
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ViewTimeline.subject
---
{{APIRef("Web Animations")}}{{SeeCompatTable}}
The **`subject`** read-only property of the {{domxref("ViewTimeline")}} interface returns a reference to the subject element whose visibility within its nearest ancestor scrollable element (scroller) is driving the progress of the timeline.
## Value
An {{domxref("Element")}}.
## Examples
See the main {{domxref("ViewTimeline")}} page for an example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
- [CSS scroll-driven animations](/en-US/docs/Web/CSS/CSS_scroll-driven_animations)
- {{domxref("ViewTimeline")}}
- {{domxref("AnimationTimeline")}}, {{domxref("ScrollTimeline")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/web_components/index.md | ---
title: Web Components
slug: Web/API/Web_components
page-type: web-api-overview
browser-compat:
- html.elements.template
- api.ShadowRoot
---
{{DefaultAPISidebar("Web Components")}}
Web Components is a suite of different technologies allowing you to create reusable custom elements — with their functionality encapsulated away from the rest of your code — and utilize them in your web apps.
## Concepts and usage
As developers, we all know that reusing code as much as possible is a good idea. This has traditionally not been so easy for custom markup structures — think of the complex HTML (and associated style and script) you've sometimes had to write to render custom UI controls, and how using them multiple times can turn your page into a mess if you are not careful.
Web Components aims to solve such problems — it consists of three main technologies, which can be used together to create versatile custom elements with encapsulated functionality that can be reused wherever you like without fear of code collisions.
- **Custom elements**
- : A set of JavaScript APIs that allow you to define custom elements and their behavior, which can then be used as desired in your user interface.
- **Shadow DOM**
- : A set of JavaScript APIs for attaching an encapsulated "shadow" DOM tree to an element — which is rendered separately from the main document DOM — and controlling associated functionality. In this way, you can keep an element's features private, so they can be scripted and styled without the fear of collision with other parts of the document.
- **HTML templates**
- : The {{HTMLElement("template")}} and {{HTMLElement("slot")}} elements enable you to write markup templates that are not displayed in the rendered page. These can then be reused multiple times as the basis of a custom element's structure.
The basic approach for implementing a web component generally looks something like this:
1. Create a class in which you specify your web component functionality, using the [class](/en-US/docs/Web/JavaScript/Reference/Classes) syntax.
2. Register your new custom element using the {{domxref("CustomElementRegistry.define()")}} method, passing it the element name to be defined, the class or function in which its functionality is specified, and optionally, what element it inherits from.
3. If required, attach a shadow DOM to the custom element using {{domxref("Element.attachShadow()")}} method. Add child elements, event listeners, etc., to the shadow DOM using regular DOM methods.
4. If required, define an HTML template using {{htmlelement("template")}} and {{htmlelement("slot")}}. Again use regular DOM methods to clone the template and attach it to your shadow DOM.
5. Use your custom element wherever you like on your page, just like you would any regular HTML element.
## Guides
- [Using custom elements](/en-US/docs/Web/API/Web_components/Using_custom_elements)
- : A guide showing how to use the features of custom elements to create simple web components, as well as looking into lifecycle callbacks and some other more advanced features.
- [Using shadow DOM](/en-US/docs/Web/API/Web_components/Using_shadow_DOM)
- : A guide that looks at shadow DOM fundamentals, showing how to attach a shadow DOM to an element, add to the shadow DOM tree, style it, and more.
- [Using templates and slots](/en-US/docs/Web/API/Web_components/Using_templates_and_slots)
- : A guide showing how to define a reusable HTML structure using {{htmlelement("template")}} and {{htmlelement("slot")}} elements, and then use that structure inside your web components.
## Reference
### Custom elements
- {{domxref("CustomElementRegistry")}}
- : Contains functionality related to custom elements, most notably the {{domxref("CustomElementRegistry.define()")}} method used to register new custom elements so they can then be used in your document.
- {{domxref("Window.customElements")}}
- : Returns a reference to the `CustomElementRegistry` object.
- [Life cycle callbacks](/en-US/docs/Web/API/Web_components/Using_custom_elements#using_the_lifecycle_callbacks)
- : Special callback functions defined inside the custom element's class definition, which affect its behavior:
- `connectedCallback()`
- : Invoked when the custom element is first connected to the document's DOM.
- `disconnectedCallback()`
- : Invoked when the custom element is disconnected from the document's DOM.
- `adoptedCallback()`
- : Invoked when the custom element is moved to a new document.
- `attributeChangedCallback()`
- : Invoked when one of the custom element's attributes is added, removed, or changed.
- Extensions for creating custom built-in elements
- : The following extensions are defined:
- The [`is`](/en-US/docs/Web/HTML/Global_attributes/is) global HTML attribute
- : Allows you to specify that a standard HTML element should behave like a registered custom built-in element.
- The "is" option of the {{domxref("Document.createElement()")}} method
- : Allows you to create an instance of a standard HTML element that behaves like a given registered custom built-in element.
- CSS pseudo-classes
- : Pseudo-classes relating specifically to custom elements:
- {{cssxref(":defined")}}
- : Matches any element that is defined, including built in elements and custom elements defined with `CustomElementRegistry.define()`.
- {{cssxref(":host")}}
- : Selects the shadow host of the [shadow DOM](/en-US/docs/Web/API/Web_components/Using_shadow_DOM) containing the CSS it is used inside.
- {{cssxref(":host", ":host()")}}
- : Selects the shadow host of the [shadow DOM](/en-US/docs/Web/API/Web_components/Using_shadow_DOM) containing the CSS it is used inside (so you can select a custom element from inside its shadow DOM) — but only if the selector given as the function's parameter matches the shadow host.
- {{cssxref(":host-context", ":host-context()")}}
- : Selects the shadow host of the [shadow DOM](/en-US/docs/Web/API/Web_components/Using_shadow_DOM) containing the CSS it is used inside (so you can select a custom element from inside its shadow DOM) — but only if the selector given as the function's parameter matches the shadow host's ancestor(s) in the place it sits inside the DOM hierarchy.
- {{CSSxRef(":state",":state()")}}
- : Matches custom elements that are in a specified custom state.
More precisely, it matches anonymous custom elements where the specified state is present in the element's {{domxref("CustomStateSet")}}.
- CSS pseudo-elements
- : Pseudo-elements relating specifically to custom elements:
- {{cssxref("::part")}}
- : Represents any element within a [shadow tree](/en-US/docs/Web/API/Web_components/Using_shadow_DOM) that has a matching [`part`](/en-US/docs/Web/HTML/Global_attributes#part) attribute.
### Shadow DOM
- {{domxref("ShadowRoot")}}
- : Represents the root node of a shadow DOM subtree.
- {{domxref("Element")}} extensions
- : Extensions to the `Element` interface related to shadow DOM:
- The {{domxref("Element.attachShadow()")}} method attaches a shadow DOM tree to the specified element.
- The {{domxref("Element.shadowRoot")}} property returns the shadow root attached to the specified element, or `null` if there is no shadow root attached.
- Relevant {{domxref("Node")}} additions
- : Additions to the `Node` interface relevant to shadow DOM:
- The {{domxref("Node.getRootNode()")}} method returns the context object's root, which optionally includes the shadow root if it is available.
- The {{domxref("Node.isConnected")}} property returns a boolean indicating whether or not the Node is connected (directly or indirectly) to the context object, e.g. the {{domxref("Document")}} object in the case of the normal DOM, or the {{domxref("ShadowRoot")}} in the case of a shadow DOM.
- {{domxref("Event")}} extensions
- : Extensions to the `Event` interface related to shadow DOM:
- {{domxref("Event.composed")}}
- : Returns `true` if the event will propagate across the shadow DOM boundary into the standard DOM, otherwise `false`.
- {{domxref("Event.composedPath")}}
- : Returns the event's path (objects on which listeners will be invoked). This does not include nodes in shadow trees if the shadow root was created with {{domxref("ShadowRoot.mode")}} closed.
### HTML templates
- {{htmlelement("template")}}
- : Contains an HTML fragment that is not rendered when a containing document is initially loaded, but can be displayed at runtime using JavaScript, mainly used as the basis of custom element structures. The associated DOM interface is {{domxref("HTMLTemplateElement")}}.
- {{htmlelement("slot")}}
- : A placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together. The associated DOM interface is {{domxref("HTMLSlotElement")}}.
- The [`slot`](/en-US/docs/Web/HTML/Global_attributes/slot) global HTML attribute
- : Assigns a slot in a shadow DOM shadow tree to an element.
- {{domxref("Element.assignedSlot")}}
- : A read-only attribute which returns a reference to the {{htmlelement("slot")}} in which this element is inserted.
- {{domxref("Text.assignedSlot")}}
- : A read-only attribute which returns a reference to the {{htmlelement("slot")}} in which this text node is inserted.
- {{domxref("Element")}} extensions
- : Extensions to the `Element` interface related to slots:
- {{domxref("Element.slot")}}
- : Returns the name of the shadow DOM slot attached to the element.
- CSS pseudo-elements
- : Pseudo-elements relating specifically to slots:
- {{cssxref("::slotted")}}
- : Matches any content that is inserted into a slot.
- The {{domxref("HTMLSlotElement/slotchange_event", "slotchange")}} event
- : Fired on an {{domxref("HTMLSlotElement")}} instance ({{htmlelement("slot")}} element) when the node(s) contained in that slot change.
## Examples
We are building up a number of examples in our [web-components-examples](https://github.com/mdn/web-components-examples) GitHub repo. More will be added as time goes on.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/web_components | data/mdn-content/files/en-us/web/api/web_components/using_templates_and_slots/index.md | ---
title: Using templates and slots
slug: Web/API/Web_components/Using_templates_and_slots
page-type: guide
---
{{DefaultAPISidebar("Web Components")}}
This article explains how you can use the {{htmlelement("template")}} and {{htmlelement("slot")}} elements to create a flexible template that can then be used to populate the shadow DOM of a web component.
## The truth about templates
When you have to reuse the same markup structures repeatedly on a web page, it makes sense to use some kind of a template rather than repeating the same structure over and over again.
This was possible before, but it is made a lot easier by the HTML {{htmlelement("template")}} element.
This element and its contents are not rendered in the DOM, but it can still be referenced using JavaScript.
Let's look at a trivial quick example:
```html
<template id="my-paragraph">
<p>My paragraph</p>
</template>
```
This won't appear in your page until you grab a reference to it with JavaScript and then append it to the DOM, using something like the following:
```js
let template = document.getElementById("my-paragraph");
let templateContent = template.content;
document.body.appendChild(templateContent);
```
Although trivial, you can already start to see how this could be useful.
## Using templates with web components
Templates are useful on their own, but they work even better with web components.
Let's define a web component that uses our template as the content of its shadow DOM.
We'll call it `<my-paragraph>` as well:
```js
customElements.define(
"my-paragraph",
class extends HTMLElement {
constructor() {
super();
let template = document.getElementById("my-paragraph");
let templateContent = template.content;
const shadowRoot = this.attachShadow({ mode: "open" });
shadowRoot.appendChild(templateContent.cloneNode(true));
}
},
);
```
The key point to note here is that we append a clone of the template content to the shadow root, created using the {{domxref("Node.cloneNode()")}} method.
And because we are appending its contents to a shadow DOM, we can include some styling information inside the template in a {{htmlelement("style")}} element, which is then encapsulated inside the custom element.
This wouldn't work if we just appended it to the standard DOM.
So for example:
```html
<template id="my-paragraph">
<style>
p {
color: white;
background-color: #666;
padding: 5px;
}
</style>
<p>My paragraph</p>
</template>
```
Now we can use it by just adding it to our HTML document:
```html
<my-paragraph></my-paragraph>
```
## Adding flexibility with slots
So far so good, but the element isn't very flexible.
We can only display one bit of text inside it, meaning that at the moment it is even less useful than a regular paragraph! We can make it possible to display different text in each element instance in a nice declarative way using the {{htmlelement("slot")}} element.
Slots are identified by their `name` attribute, and allow you to define placeholders in your template that can be filled with any markup fragment you want when the element is used in the markup.
So, if we want to add a slot into our trivial example, we could update our template's paragraph element like this:
```html
<p><slot name="my-text">My default text</slot></p>
```
If the slot's content isn't defined when the element is included in the markup, or if the browser doesn't support slots, `<my-paragraph>` just contains the fallback content "My default text".
To define the slot's content, we include an HTML structure inside the `<my-paragraph>` element with a [`slot`](/en-US/docs/Web/HTML/Global_attributes#slot) attribute whose value is equal to the name of the slot we want it to fill. As before, this can be anything you like, for example:
```html
<my-paragraph>
<span slot="my-text">Let's have some different text!</span>
</my-paragraph>
```
or
```html
<my-paragraph>
<ul slot="my-text">
<li>Let's have some different text!</li>
<li>In a list!</li>
</ul>
</my-paragraph>
```
> **Note:** Nodes that can be inserted into slots are known as _Slottable_ nodes; when a node has been inserted in a slot, it is said to be _slotted_.
> **Note:** An unnamed {{HTMLElement("slot")}} will be filled with all of the custom element's top-level child nodes that do not have the [`slot`](/en-US/docs/Web/HTML/Global_attributes#slot) attribute. This includes text nodes.
And that's it for our trivial example.
If you want to play with it some more, you can [find it on GitHub](https://github.com/mdn/web-components-examples/tree/main/simple-template) (see it [running live](https://mdn.github.io/web-components-examples/simple-template/) also).
## A more involved example
To finish off the article, let's look at something a little less trivial.
The following set of code snippets show how to use {{HTMLElement("slot")}} together with {{HTMLElement("template")}} and some JavaScript to:
- create a **`<element-details>`** element with [named slots](/en-US/docs/Web/HTML/Element/slot#name) in its [shadow root](/en-US/docs/Web/API/ShadowRoot)
- design the **`<element-details>`** element in such a way that, when used in documents, it is rendered from composing the element's content together with content from its [shadow root](/en-US/docs/Web/API/ShadowRoot)—that is, pieces of the element's content are used to fill in [named slots](/en-US/docs/Web/HTML/Element/slot#name) in its [shadow root](/en-US/docs/Web/API/ShadowRoot)
Note that it is technically possible to use {{HTMLElement("slot")}} element without a {{HTMLElement("template")}} element, e.g., within say a regular {{HTMLElement("div")}} element, and still take advantage of the place-holder features of {{HTMLElement("slot")}} for Shadow DOM content, and doing so may indeed avoid the small trouble of needing to first access the template element's `content` property (and clone it).
However, it is generally more practical to add slots within a {{HTMLElement("template")}} element, since you are unlikely to need to define a pattern based on an already-rendered element.
In addition, even if it is not already rendered, the purpose of the container as a template should be more semantically clear when using the {{HTMLElement("template")}}. In addition, {{HTMLElement("template")}} can have items directly added to it, like {{HTMLElement("td")}}, which would disappear when added to a {{HTMLElement("div")}}.
> **Note:** You can find this complete example at [element-details](https://github.com/mdn/web-components-examples/tree/main/element-details) (see it [running live](https://mdn.github.io/web-components-examples/element-details/) also).
### Creating a template with some slots
First of all, we use the {{HTMLElement("slot")}} element within a {{HTMLElement("template")}} element to create a new "element-details-template" [document fragment](/en-US/docs/Web/API/DocumentFragment) containing some [named slots](/en-US/docs/Web/HTML/Element/slot#name):
```html
<template id="element-details-template">
<style>
details {
font-family: "Open Sans Light", Helvetica, Arial;
}
.name {
font-weight: bold;
color: #217ac0;
font-size: 120%;
}
h4 {
margin: 10px 0 -8px 0;
}
h4 span {
background: #217ac0;
padding: 2px 6px 2px 6px;
}
h4 span {
border: 1px solid #cee9f9;
border-radius: 4px;
}
h4 span {
color: white;
}
.attributes {
margin-left: 22px;
font-size: 90%;
}
.attributes p {
margin-left: 16px;
font-style: italic;
}
</style>
<details>
<summary>
<span>
<code class="name"
><<slot name="element-name">NEED NAME</slot>></code
>
<span class="desc"
><slot name="description">NEED DESCRIPTION</slot></span
>
</span>
</summary>
<div class="attributes">
<h4><span>Attributes</span></h4>
<slot name="attributes"><p>None</p></slot>
</div>
</details>
<hr />
</template>
```
That {{HTMLElement("template")}} element has several features:
- The {{HTMLElement("template")}} has a {{HTMLElement("style")}} element with a set of CSS styles that are scoped just to the document fragment the {{HTMLElement("template")}} creates.
- The {{HTMLElement("template")}} uses {{HTMLElement("slot")}} and its [`name`](/en-US/docs/Web/HTML/Element/slot#name) attribute to make three [named slots](/en-US/docs/Web/HTML/Element/slot#name):
- `<slot name="element-name">`
- `<slot name="description">`
- `<slot name="attributes">`
- The {{HTMLElement("template")}} wraps the [named slots](/en-US/docs/Web/HTML/Element/slot#name) in a {{HTMLElement("details")}} element.
### Creating a new \<element-details> element from the \<template>
Next, let's create a new custom element named **`<element-details>`** and use {{DOMXref("Element.attachShadow")}} to attach to it, as its [shadow root](/en-US/docs/Web/API/ShadowRoot), that document fragment we created with our {{HTMLElement("template")}} element above.
This uses exactly the same pattern as we saw in our earlier trivial example.
```js
customElements.define(
"element-details",
class extends HTMLElement {
constructor() {
super();
const template = document.getElementById(
"element-details-template",
).content;
const shadowRoot = this.attachShadow({ mode: "open" });
shadowRoot.appendChild(template.cloneNode(true));
}
},
);
```
### Using the \<element-details> custom element with named slots
Now let's take that **`<element-details>`** element and actually use it in our document:
```html
<element-details>
<span slot="element-name">slot</span>
<span slot="description"
>A placeholder inside a web component that users can fill with their own
markup, with the effect of composing different DOM trees together.</span
>
<dl slot="attributes">
<dt>name</dt>
<dd>The name of the slot.</dd>
</dl>
</element-details>
<element-details>
<span slot="element-name">template</span>
<span slot="description"
>A mechanism for holding client- side content that is not to be rendered
when a page is loaded but may subsequently be instantiated during runtime
using JavaScript.</span
>
</element-details>
```
About that snippet, notice these points:
- The snippet has two instances of **`<element-details>`** elements which both use the [`slot`](/en-US/docs/Web/HTML/Global_attributes#slot) attribute to reference the [named slots](/en-US/docs/Web/HTML/Element/slot#name) `"element-name"` and `"description"` we put in the `<element-details>` [shadow root](/en-US/docs/Web/API/ShadowRoot) .
- Only the first of those two **`<element-details>`** elements references the `"attributes"` [named slot](/en-US/docs/Web/HTML/Element/slot#name). The second `<element-details>` element lacks any reference to the `"attributes"` [named slot](/en-US/docs/Web/HTML/Element/slot#name).
- The first `<element-details>` element references the `"attributes"` [named slot](/en-US/docs/Web/HTML/Element/slot#name) using a {{HTMLElement("dl")}} element with {{HTMLElement("dt")}} and {{HTMLElement("dd")}} children.
### Adding a final bit of style
As a finishing touch, we'll add a tiny bit more CSS for the {{HTMLElement("dl")}}, {{HTMLElement("dt")}}, and {{HTMLElement("dd")}} elements in our doc:
```css
dl {
margin-left: 6px;
}
dt {
color: #217ac0;
font-family: Consolas, "Liberation Mono", Courier;
font-size: 110%;
font-weight: bold;
}
dd {
margin-left: 16px;
}
```
```css hidden
body {
margin-top: 47px;
}
```
### Result
Finally let's put all the snippets together and see what the rendered result looks like.
{{EmbedLiveSample('A_more_involved_example', '300','400')}}
Notice the following points about this rendered result:
- Even though the instances of the **`<element-details>`** element in the document do not directly use the {{HTMLElement("details")}} element, they get rendered using {{HTMLElement("details")}} because the [shadow root](/en-US/docs/Web/API/ShadowRoot) causes them to get populated with that.
- Within the rendered {{HTMLElement("details")}} output, the content in the **`<element-details>`** elements fills the [named slots](/en-US/docs/Web/HTML/Element/slot#name) from the [shadow root](/en-US/docs/Web/API/ShadowRoot). In other words, the DOM tree from the **`<element-details>`** elements get _composed_ together with the content of the [shadow root](/en-US/docs/Web/API/ShadowRoot).
- For both **`<element-details>`** elements, an **Attributes** heading gets automatically added from the [shadow root](/en-US/docs/Web/API/ShadowRoot) before the position of the `"attributes"` [named slot](/en-US/docs/Web/HTML/Element/slot#name).
- Because the first **`<element-details>`** has a {{HTMLElement("dl")}} element which explicitly references the `"attributes"` [named slot](/en-US/docs/Web/HTML/Element/slot#name) from its [shadow root](/en-US/docs/Web/API/ShadowRoot), the contents of that {{HTMLElement("dl")}} replace the `"attributes"` [named slot](/en-US/docs/Web/HTML/Element/slot#name) from the [shadow root](/en-US/docs/Web/API/ShadowRoot).
- Because the second **`<element-details>`** doesn't explicitly reference the `"attributes"` [named slot](/en-US/docs/Web/HTML/Element/slot#name) from its [shadow root](/en-US/docs/Web/API/ShadowRoot), its content for that [named slot](/en-US/docs/Web/HTML/Element/slot#name) gets filled with the default content for it from the [shadow root](/en-US/docs/Web/API/ShadowRoot).
| 0 |
data/mdn-content/files/en-us/web/api/web_components | data/mdn-content/files/en-us/web/api/web_components/using_custom_elements/index.md | ---
title: Using custom elements
slug: Web/API/Web_components/Using_custom_elements
page-type: guide
---
{{DefaultAPISidebar("Web Components")}}
One of the key features of web components is the ability to create _custom elements_: that is, HTML elements whose behavior is defined by the web developer, that extend the set of elements available in the browser.
This article introduces custom elements, and walks through some examples.
## Types of custom element
There are two types of custom element:
- **Customized built-in elements** inherit from standard HTML elements such as {{domxref("HTMLImageElement")}} or {{domxref("HTMLParagraphElement")}}. Their implementation customizes the behavior of the standard element.
- **Autonomous custom elements** inherit from the HTML element base class {{domxref("HTMLElement")}}. You have to implement their behavior from scratch.
## Implementing a custom element
A custom element is implemented as a [class](/en-US/docs/Web/JavaScript/Reference/Classes) which extends {{domxref("HTMLElement")}} (in the case of autonomous elements) or the interface you want to customize (in the case of customized built-in elements).
Here's the implementation of a minimal custom element that customizes the {{HTMLElement("p")}} element:
```js
class WordCount extends HTMLParagraphElement {
constructor() {
super();
}
// Element functionality written in here
}
```
Here's the implementation of a minimal autonomous custom element:
```js
class PopupInfo extends HTMLElement {
constructor() {
super();
}
// Element functionality written in here
}
```
In the class [constructor](/en-US/docs/Web/JavaScript/Reference/Classes/constructor), you can set up initial state and default values, register event listeners and perhaps create a shadow root. At this point, you should not inspect the element's attributes or children, or add new attributes or children. See [Requirements for custom element constructors and reactions](https://html.spec.whatwg.org/multipage/custom-elements.html#custom-element-conformance) for the complete set of requirements.
### Custom element lifecycle callbacks
Once your custom element is registered, the browser will call certain methods of your class when code in the page interacts with your custom element in certain ways. By providing an implementation of these methods, which the specification calls _lifecycle callbacks_, you can run code in response to these events.
Custom element lifecycle callbacks include:
- `connectedCallback()`: called each time the element is added to the document. The specification recommends that, as far as possible, developers should implement custom element setup in this callback rather than the constructor.
- `disconnectedCallback()`: called each time the element is removed from the document.
- `adoptedCallback()`: called each time the element is moved to a new document.
- `attributeChangedCallback()`: called when attributes are changed, added, removed, or replaced. See [Responding to attribute changes](#responding_to_attribute_changes) for more details about this callback.
Here's a minimal custom element that logs these lifecycle events:
```js
// Create a class for the element
class MyCustomElement extends HTMLElement {
static observedAttributes = ["color", "size"];
constructor() {
// Always call super first in constructor
super();
}
connectedCallback() {
console.log("Custom element added to page.");
}
disconnectedCallback() {
console.log("Custom element removed from page.");
}
adoptedCallback() {
console.log("Custom element moved to new page.");
}
attributeChangedCallback(name, oldValue, newValue) {
console.log(`Attribute ${name} has changed.`);
}
}
customElements.define("my-custom-element", MyCustomElement);
```
## Registering a custom element
To make a custom element available in a page, call the {{domxref("CustomElementRegistry.define()", "define()")}} method of {{domxref("Window.customElements")}}.
The `define()` method takes the following arguments:
- `name`
- : The name of the element. This must start with a lowercase letter, contain a hyphen, and satisfy certain other rules listed in the specification's [definition of a valid name](https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name).
- `constructor`
- : The custom element's constructor function.
- `options`
- : Only included for customized built-in elements, this is an object containing a single property `extends`, which is a string naming the built-in element to extend.
For example, this code registers the `WordCount` customized built-in element:
```js
customElements.define("word-count", WordCount, { extends: "p" });
```
This code registers the `PopupInfo` autonomous custom element:
```js
customElements.define("popup-info", PopupInfo);
```
## Using a custom element
Once you've defined and registered a custom element, you can use it in your code.
To use a customized built-in element, use the built-in element but with the custom name as the value of the [`is`](/en-US/docs/Web/HTML/Global_attributes/is) attribute:
```html
<p is="word-count"></p>
```
To use an autonomous custom element, use the custom name just like a built-in HTML element:
```html
<popup-info>
<!-- content of the element -->
</popup-info>
```
## Responding to attribute changes
Like built-in elements, custom elements can use HTML attributes to configure the element's behavior. To use attributes effectively, an element has to be able to respond to changes in an attribute's value. To do this, a custom element needs to add the following members to the class that implements the custom element:
- A static property named `observedAttributes`. This must be an array containing the names of all attributes for which the element needs change notifications.
- An implementation of the `attributeChangedCallback()` lifecycle callback.
The `attributeChangedCallback()` callback is then called whenever an attribute whose name is listed in the element's `observedAttributes` property is added, modified, removed, or replaced.
The callback is passed three arguments:
- The name of the attribute which changed.
- The attribute's old value.
- The attribute's new value.
For example, this autonomous element will observe a `size` attribute, and log the old and new values when they change:
```js
// Create a class for the element
class MyCustomElement extends HTMLElement {
static observedAttributes = ["size"];
constructor() {
super();
}
attributeChangedCallback(name, oldValue, newValue) {
console.log(
`Attribute ${name} has changed from ${oldValue} to ${newValue}.`,
);
}
}
customElements.define("my-custom-element", MyCustomElement);
```
Note that if the element's HTML declaration includes an observed attribute, then `attributeChangedCallback()` will be called after the attribute is initialized, when the element's declaration is parsed for the first time. So in the following example, `attributeChangedCallback()` will be called when the DOM is parsed, even if the attribute is never changed again:
```html
<my-custom-element size="100"></my-custom-element>
```
For a complete example showing the use of `attributeChangedCallback()`, see [Lifecycle callbacks](#lifecycle_callbacks) in this page.
### Custom states and custom state pseudo-class CSS selectors
Built in HTML elements can have different _states_, such as "hover", "disabled", and "read only".
Some of these states can be set as attributes using HTML or JavaScript, while others are internal, and cannot.
Whether external or internal, commonly these states have corresponding CSS [pseudo-classes](/en-US/docs/Web/CSS/Pseudo-classes) that can be used to select and style the element when it is in a particular state.
Autonomous custom elements (but not elements based on built-in elements) also allow you to define states and select against them using the [`:state()`](/en-US/docs/Web/CSS/:state) pseudo-class function.
The code below shows how this works using the example of an autonomous custom element that has an internal state "`collapsed`".
The `collapsed` state is represented as a boolean property (with setter and getter methods) that is not visible outside of the element.
To make this state selectable in CSS the custom element first calls {{domxref("HTMLElement.attachInternals()")}} in its constructor in order to attach an {{domxref("ElementInternals")}} object, which in turn provides access to a {{domxref("CustomStateSet")}} through the {{domxref("ElementInternals.states")}} property.
The setter for the (internal) collapsed state adds the _identifier_ `hidden` to the `CustomStateSet` when the state is `true`, and removes it when the state is `false`.
The identifier is just a string: in this case we called it `hidden`, but we could have just as easily called it `collapsed`.
```js
class MyCustomElement extends HTMLElement {
constructor() {
super();
this._internals = this.attachInternals();
}
get collapsed() {
return this._internals.states.has("hidden");
}
set collapsed(flag) {
if (flag) {
// Existence of identifier corresponds to "true"
this._internals.states.add("hidden");
} else {
// Absence of identifier corresponds to "false"
this._internals.states.delete("hidden");
}
}
}
// Register the custom element
customElements.define("my-custom-element", MyCustomElement);
```
We can use the identifier added to the custom element's `CustomStateSet` (`this._internals.states`) for matching the element's custom state.
This is matched by passing the identifier to the [`:state()`](/en-US/docs/Web/CSS/:state) pseudo-class.
For example, below we select on the `hidden` state being true (and hence the element's `collapsed` state) using the `:hidden` selector, and remove the border.
```css
my-custom-element {
border: dashed red;
}
my-custom-element:state(hidden) {
border: none;
}
```
The `:state()` pseudo-class can also be used within the [`:host()`](/en-US/docs/Web/CSS/:host_function) pseudo-class function to match a custom state [within a custom element's shadow DOM](/en-US/docs/Web/CSS/:state#matching_a_custom_state_in_a_custom_elements_shadow_dom). Additionally, the `:state()` pseudo-class can be used after the [`::part()`](/en-US/docs/Web/CSS/::part) pseudo-element to match the [shadow parts](/en-US/docs/Web/CSS/CSS_shadow_parts) of a custom element that is in a particular state.
There are several live examples in {{domxref("CustomStateSet")}} showing how this works.
## Examples
In the rest of this guide we'll look at a few example custom elements. You can find the source for all these examples, and more, in the [web-components-examples](https://github.com/mdn/web-components-examples) repository, and you can see them all live at <https://mdn.github.io/web-components-examples/>.
### An autonomous custom element
First, we'll look at an autonomous custom element. The `<popup-info>` custom element takes an image icon and a text string as attributes, and embeds the icon into the page. When the icon is focused, it displays the text in a pop up information box to provide further in-context information.
- [See the example running live](https://mdn.github.io/web-components-examples/popup-info-box-web-component)
- [See the source code](https://github.com/mdn/web-components-examples/tree/main/popup-info-box-web-component)
To begin with, the JavaScript file defines a class called `PopupInfo`, which extends the {{domxref("HTMLElement")}} class.
```js
// Create a class for the element
class PopupInfo extends HTMLElement {
constructor() {
// Always call super first in constructor
super();
}
connectedCallback() {
// Create a shadow root
const shadow = this.attachShadow({ mode: "open" });
// Create spans
const wrapper = document.createElement("span");
wrapper.setAttribute("class", "wrapper");
const icon = document.createElement("span");
icon.setAttribute("class", "icon");
icon.setAttribute("tabindex", 0);
const info = document.createElement("span");
info.setAttribute("class", "info");
// Take attribute content and put it inside the info span
const text = this.getAttribute("data-text");
info.textContent = text;
// Insert icon
let imgUrl;
if (this.hasAttribute("img")) {
imgUrl = this.getAttribute("img");
} else {
imgUrl = "img/default.png";
}
const img = document.createElement("img");
img.src = imgUrl;
icon.appendChild(img);
// Create some CSS to apply to the shadow dom
const style = document.createElement("style");
console.log(style.isConnected);
style.textContent = `
.wrapper {
position: relative;
}
.info {
font-size: 0.8rem;
width: 200px;
display: inline-block;
border: 1px solid black;
padding: 10px;
background: white;
border-radius: 10px;
opacity: 0;
transition: 0.6s all;
position: absolute;
bottom: 20px;
left: 10px;
z-index: 3;
}
img {
width: 1.2rem;
}
.icon:hover + .info, .icon:focus + .info {
opacity: 1;
}
`;
// Attach the created elements to the shadow dom
shadow.appendChild(style);
console.log(style.isConnected);
shadow.appendChild(wrapper);
wrapper.appendChild(icon);
wrapper.appendChild(info);
}
}
```
The class definition contains the [`constructor()`](/en-US/docs/Web/JavaScript/Reference/Classes/constructor) for the class, which always starts by calling [`super()`](/en-US/docs/Web/JavaScript/Reference/Operators/super) so that the correct prototype chain is established.
Inside the method `connectedCallback()`, we define all the functionality the element will have when the element is connected to the DOM. In this case we attach a shadow root to the custom element, use some DOM manipulation to create the element's internal shadow DOM structure — which is then attached to the shadow root — and finally attach some CSS to the shadow root to style it. We don't do this work in the constructor because an element's attributes are unavailable until it is connected to the DOM.
Finally, we register our custom element in the `CustomElementRegistry` using the `define()` method we mentioned earlier — in the parameters we specify the element name, and then the class name that defines its functionality:
```js
customElements.define("popup-info", PopupInfo);
```
It is now available to use on our page. Over in our HTML, we use it like so:
```html
<popup-info
img="img/alt.png"
data-text="Your card validation code (CVC)
is an extra security feature — it is the last 3 or 4 numbers on the
back of your card."></popup-info>
```
### Referencing external styles
In the above example we apply styles to the shadow DOM using a {{htmlelement("style")}} element, but you can reference an external stylesheet from a {{htmlelement("link")}} element instead. In this example we'll modify the `<popup-info>` custom element to use an external stylesheet.
- [See the example running live](https://mdn.github.io/web-components-examples/popup-info-box-external-stylesheet/)
- [See the source code](https://github.com/mdn/web-components-examples/blob/main/popup-info-box-external-stylesheet/)
Here's the class definition:
```js
// Create a class for the element
class PopupInfo extends HTMLElement {
constructor() {
// Always call super first in constructor
super();
}
connectedCallback() {
// Create a shadow root
const shadow = this.attachShadow({ mode: "open" });
// Create spans
const wrapper = document.createElement("span");
wrapper.setAttribute("class", "wrapper");
const icon = document.createElement("span");
icon.setAttribute("class", "icon");
icon.setAttribute("tabindex", 0);
const info = document.createElement("span");
info.setAttribute("class", "info");
// Take attribute content and put it inside the info span
const text = this.getAttribute("data-text");
info.textContent = text;
// Insert icon
let imgUrl;
if (this.hasAttribute("img")) {
imgUrl = this.getAttribute("img");
} else {
imgUrl = "img/default.png";
}
const img = document.createElement("img");
img.src = imgUrl;
icon.appendChild(img);
// Apply external styles to the shadow dom
const linkElem = document.createElement("link");
linkElem.setAttribute("rel", "stylesheet");
linkElem.setAttribute("href", "style.css");
// Attach the created elements to the shadow dom
shadow.appendChild(linkElem);
shadow.appendChild(wrapper);
wrapper.appendChild(icon);
wrapper.appendChild(info);
}
}
```
It's just like the original `<popup-info>` example, except that we link to an external stylesheet using a {{HTMLElement("link")}} element, which we add to the shadow DOM.
Note that {{htmlelement("link")}} elements do not block paint of the shadow root, so there may be a flash of unstyled content (FOUC) while the stylesheet loads.
Many modern browsers implement an optimization for {{htmlelement("style")}} tags either cloned from a common node or that have identical text, to allow them to share a single backing stylesheet. With this optimization the performance of external and internal styles should be similar.
### Customized built-in elements
Now let's have a look at a customized built in element example. This example extends the built-in {{HTMLElement("ul")}} element to support expanding and collapsing the list items.
- [See the example running live](https://mdn.github.io/web-components-examples/expanding-list-web-component/)
- [See the source code](https://github.com/mdn/web-components-examples/tree/main/expanding-list-web-component)
First of all, we define our element's class:
```js
// Create a class for the element
class ExpandingList extends HTMLUListElement {
constructor() {
// Always call super first in constructor
// Return value from super() is a reference to this element
self = super();
}
connectedCallback() {
// Get ul and li elements that are a child of this custom ul element
// li elements can be containers if they have uls within them
const uls = Array.from(self.querySelectorAll("ul"));
const lis = Array.from(self.querySelectorAll("li"));
// Hide all child uls
// These lists will be shown when the user clicks a higher level container
uls.forEach((ul) => {
ul.style.display = "none";
});
// Look through each li element in the ul
lis.forEach((li) => {
// If this li has a ul as a child, decorate it and add a click handler
if (li.querySelectorAll("ul").length > 0) {
// Add an attribute which can be used by the style
// to show an open or closed icon
li.setAttribute("class", "closed");
// Wrap the li element's text in a new span element
// so we can assign style and event handlers to the span
const childText = li.childNodes[0];
const newSpan = document.createElement("span");
// Copy text from li to span, set cursor style
newSpan.textContent = childText.textContent;
newSpan.style.cursor = "pointer";
// Add click handler to this span
newSpan.addEventListener("click", (e) => {
// next sibling to the span should be the ul
const nextul = e.target.nextElementSibling;
// Toggle visible state and update class attribute on ul
if (nextul.style.display == "block") {
nextul.style.display = "none";
nextul.parentNode.setAttribute("class", "closed");
} else {
nextul.style.display = "block";
nextul.parentNode.setAttribute("class", "open");
}
});
// Add the span and remove the bare text node from the li
childText.parentNode.insertBefore(newSpan, childText);
childText.parentNode.removeChild(childText);
}
});
}
}
```
Note that this time we extend {{domxref("HTMLUListElement")}}, rather than {{domxref("HTMLElement")}}. This means that we get the default behavior of a list, and only have to implement our own customizations.
As before, most of the code is in the `connectedCallback()` lifecycle callback.
Next, we register the element using the `define()` method as before, except that this time it also includes an options object that details what element our custom element inherits from:
```js
customElements.define("expanding-list", ExpandingList, { extends: "ul" });
```
Using the built-in element in a web document also looks somewhat different:
```html
<ul is="expanding-list">
…
</ul>
```
You use a `<ul>` element as normal, but specify the name of the custom element inside the `is` attribute.
Note that in this case we must ensure that the script defining our custom element is executed after the DOM has been fully parsed, because `connectedCallback()` is called as soon as the expanding list is added to the DOM, and at that point its children have not been added yet, so the `querySelectorAll()` calls will not find any items. One way to ensure this is to add the [defer](/en-US/docs/Web/HTML/Element/script#defer) attribute to the line that includes the script:
```html
<script src="main.js" defer></script>
```
### Lifecycle callbacks
So far we've seen only one lifecycle callback in action: `connectedCallback()`. In the final example, `<custom-square>`, we'll see some of the others. The `<custom-square>` autonomous custom element draws a square whose size and color are determined by two attributes, named `"size"` and `"color"`.
- [See the example running live](https://mdn.github.io/web-components-examples/life-cycle-callbacks/)
- [See the source code](https://github.com/mdn/web-components-examples/tree/main/life-cycle-callbacks)
In the class constructor, we attach a shadow DOM to the element, then attach empty {{htmlelement("div")}} and {{htmlelement("style")}} elements to the shadow root:
```js
constructor() {
// Always call super first in constructor
super();
const shadow = this.attachShadow({ mode: "open" });
const div = document.createElement("div");
const style = document.createElement("style");
shadow.appendChild(style);
shadow.appendChild(div);
}
```
The key function in this example is `updateStyle()` — this takes an element, gets its shadow root, finds its `<style>` element, and adds {{cssxref("width")}}, {{cssxref("height")}}, and {{cssxref("background-color")}} to the style.
```js
function updateStyle(elem) {
const shadow = elem.shadowRoot;
shadow.querySelector("style").textContent = `
div {
width: ${elem.getAttribute("size")}px;
height: ${elem.getAttribute("size")}px;
background-color: ${elem.getAttribute("color")};
}
`;
}
```
The actual updates are all handled by the lifecycle callbacks. The `connectedCallback()` runs each time the element is added to the DOM — here we run the `updateStyle()` function to make sure the square is styled as defined in its attributes:
```js
connectedCallback() {
console.log("Custom square element added to page.");
updateStyle(this);
}
```
The `disconnectedCallback()` and `adoptedCallback()` callbacks log messages to the console to inform us when the element is either removed from the DOM, or moved to a different page:
```js
disconnectedCallback() {
console.log("Custom square element removed from page.");
}
adoptedCallback() {
console.log("Custom square element moved to new page.");
}
```
The `attributeChangedCallback()` callback is run whenever one of the element's attributes is changed in some way. As you can see from its parameters, it is possible to act on attributes individually, looking at their name, and old and new attribute values. In this case however, we are just running the `updateStyle()` function again to make sure that the square's style is updated as per the new values:
```js
attributeChangedCallback(name, oldValue, newValue) {
console.log("Custom square element attributes changed.");
updateStyle(this);
}
```
Note that to get the `attributeChangedCallback()` callback to fire when an attribute changes, you have to observe the attributes. This is done by specifying a `static get observedAttributes()` method inside the custom element class - this should return an array containing the names of the attributes you want to observe:
```js
static get observedAttributes() {
return ["color", "size"];
}
```
| 0 |
data/mdn-content/files/en-us/web/api/web_components | data/mdn-content/files/en-us/web/api/web_components/using_shadow_dom/index.md | ---
title: Using shadow DOM
slug: Web/API/Web_components/Using_shadow_DOM
page-type: guide
---
{{DefaultAPISidebar("Web Components")}}
An important aspect of custom elements is encapsulation, because a custom element, by definition, is a piece of reusable functionality: it might be dropped into any web page and be expected to work. So it's important that code running in the page should not be able to accidentally break a custom element by modifying its internal implementation. Shadow DOM enables you to attach a DOM tree to an element, and have the internals of this tree hidden from JavaScript and CSS running in the page.
This article covers the basics of using the shadow DOM.
## High-level view
This article assumes you are already familiar with the concept of the [DOM (Document Object Model)](/en-US/docs/Web/API/Document_Object_Model/Introduction) — a tree-like structure of connected nodes that represents the different elements and strings of text appearing in a markup document (usually an HTML document in the case of web documents). As an example, consider the following HTML fragment:
```html
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>DOM example</title>
</head>
<body>
<section>
<img src="dinosaur.png" alt="A red Tyrannosaurus Rex." />
<p>
Here we will add a link to the
<a href="https://www.mozilla.org/">Mozilla homepage</a>
</p>
</section>
</body>
</html>
```
This fragment produces the following DOM structure (excluding whitespace-only text nodes):
```plain
- HTML
- HEAD
- META charset="utf-8"
- TITLE
- #text: DOM example
- BODY
- SECTION
- IMG src="dinosaur.png" alt="A red Tyrannosaurus Rex."
- P
- #text: Here we will add a link to the
- A href="https://www.mozilla.org/"
- #text: Mozilla homepage
```
_Shadow_ DOM allows hidden DOM trees to be attached to elements in the regular DOM tree — this shadow DOM tree starts with a shadow root, underneath which you can attach any element, in the same way as the normal DOM.

There are some bits of shadow DOM terminology to be aware of:
- **Shadow host**: The regular DOM node that the shadow DOM is attached to.
- **Shadow tree**: The DOM tree inside the shadow DOM.
- **Shadow boundary**: the place where the shadow DOM ends, and the regular DOM begins.
- **Shadow root**: The root node of the shadow tree.
You can affect the nodes in the shadow DOM in exactly the same way as non-shadow nodes — for example appending children or setting attributes, styling individual nodes using element.style.foo, or adding style to the entire shadow DOM tree inside a {{htmlelement("style")}} element. The difference is that none of the code inside a shadow DOM can affect anything outside it, allowing for handy encapsulation.
Before shadow DOM was made available to web developers, browsers were already using it to encapsulate the inner structure of an element. Think for example of a {{htmlelement("video")}} element, with the default browser controls exposed. All you see in the DOM is the `<video>` element, but it contains a series of buttons and other controls inside its shadow DOM. The shadow DOM spec enables you to manipulate the shadow DOM of your own custom elements.
## Creating a shadow DOM
### Imperatively with JavaScript
The following page contains two elements, a {{htmlelement("div")}} element with an [`id`](/en-US/docs/Web/HTML/Global_attributes/id) of `"host"`, and a {{htmlelement("span")}} element containing some text:
```html
<div id="host"></div>
<span>I'm not in the shadow DOM</span>
```
We're going to use the `"host"` element as the shadow host. We call {{domxref("Element.attachShadow()", "attachShadow()")}} on the host to create the shadow DOM, and can then add nodes to the shadow DOM just like we would to the main DOM. In this example we add a single `<span>` element:
```js
const host = document.querySelector("#host");
const shadow = host.attachShadow({ mode: "open" });
const span = document.createElement("span");
span.textContent = "I'm in the shadow DOM";
shadow.appendChild(span);
```
The result looks like this:
{{EmbedLiveSample("Imperatively with JavaScript")}}
### Declaratively with HTML
Creating a shadow DOM via JavaScript API might be a good option for client-side rendered applications. For other applications, a server-side rendered UI might have better performance and, therefore, a better user experience. In such cases, you can use the {{htmlelement("template")}} element to declaratively define the shadow DOM. The key to this behavior is the {{glossary("enumerated")}} `shadowrootmode` attribute, which can be set to either `open` or `closed`, the same values as the `mode` option of {{domxref("Element.attachShadow()", "attachShadow()")}} method.
```html
<div id="host">
<template shadowrootmode="open">
<span>I'm in the shadow DOM</span>
</template>
</div>
```
{{EmbedGHLiveSample("dom-examples/shadow-dom/shadowrootmode/simple.html", "", "")}}
> **Note:** By default, contents of `<template>` are not displayed. In this case, because the `shadowrootmode="open"` was included, the shadow root is rendered. In supporting browsers, the visible contents within that shadow root are displayed.
After the browser parses the HTML, it replaces {{htmlelement("template")}} element with its content wrapped in a [shadow root](/en-US/docs/Glossary/Shadow_tree) that's attached to the parent element, the `<div id="host">` in our example. The resulting DOM tree looks like this:
```plain
- DIV id="host"
- #shadow-root
- SPAN
- #text: I'm in the shadow DOM
```
Note that there's no `<template>` element in the DOM tree.
## Encapsulation from JavaScript
So far this might not look like much. But let's see what happens if code running in the page tries to access elements in the shadow DOM.
This page is just like the last one, except we've added two {{htmlelement("button")}} elements.
```html
<div id="host"></div>
<span>I'm not in the shadow DOM</span>
<br />
<button id="upper" type="button">Uppercase span elements</button>
<button id="reload" type="button">Reload</button>
```
Clicking the "Uppercase span elements" button finds all `<span>` elements in the page and changes their text to uppercase.
Clicking the "Reload" button just reloads the page, so you can try again.
```js
const host = document.querySelector("#host");
const shadow = host.attachShadow({ mode: "open" });
const span = document.createElement("span");
span.textContent = "I'm in the shadow DOM";
shadow.appendChild(span);
const upper = document.querySelector("button#upper");
upper.addEventListener("click", () => {
const spans = Array.from(document.querySelectorAll("span"));
for (const span of spans) {
span.textContent = span.textContent.toUpperCase();
}
});
const reload = document.querySelector("#reload");
reload.addEventListener("click", () => document.location.reload());
```
If you click "Uppercase span elements", you'll see that {{domxref("Document.querySelectorAll()")}} doesn't find the elements in our shadow DOM: they are effectively hidden from JavaScript in the page:
{{EmbedLiveSample("Encapsulation from JavaScript")}}
## Element.shadowRoot and the "mode" option
In the example above, we pass an argument `{ mode: "open" }` to `attachShadow()`. With `mode` set to `"open"`, the JavaScript in the page is able to access the internals of your shadow DOM through the {{domxref("Element.shadowRoot", "shadowRoot")}} property of the shadow host.
In this example, as before, the HTML contains the shadow host, a `<span>` element in the main DOM tree, and two buttons:
```html
<div id="host"></div>
<span>I'm not in the shadow DOM</span>
<br />
<button id="upper" type="button">Uppercase shadow DOM span elements</button>
<button id="reload" type="button">Reload</button>
```
This time the "Uppercase" button uses `shadowRoot` to find the `<span>` elements in the DOM:
```js
const host = document.querySelector("#host");
const shadow = host.attachShadow({ mode: "open" });
const span = document.createElement("span");
span.textContent = "I'm in the shadow DOM";
shadow.appendChild(span);
const upper = document.querySelector("button#upper");
upper.addEventListener("click", () => {
const spans = Array.from(host.shadowRoot.querySelectorAll("span"));
for (const span of spans) {
span.textContent = span.textContent.toUpperCase();
}
});
const reload = document.querySelector("#reload");
reload.addEventListener("click", () => document.location.reload());
```
This time, the JavaScript running in the page can access the shadow DOM internals:
{{EmbedLiveSample("Element.shadowRoot and the \"mode\" option")}}
The `{mode: "open"}` argument gives the page a way to break the encapsulation of your shadow DOM. If you don't want to give the page this ability, pass `{mode: "closed"}` instead, and then `shadowRoot` returns `null`.
However, you should not consider this a strong security mechanism, because there are ways it can be evaded, for example by browser extensions running in the page. It's more of an indication that the page should not access the internals of your shadow DOM tree.
## Encapsulation from CSS
In this version of the page, the HTML is the same as the original:
```html
<div id="host"></div>
<span>I'm not in the shadow DOM</span>
```
In the JavaScript, we create the shadow DOM:
```js
const host = document.querySelector("#host");
const shadow = host.attachShadow({ mode: "open" });
const span = document.createElement("span");
span.textContent = "I'm in the shadow DOM";
shadow.appendChild(span);
```
This time, we'll have some CSS targeting `<span>` elements in the page:
```css
span {
color: blue;
border: 1px solid black;
}
```
The page CSS does not affect nodes inside the shadow DOM:
{{EmbedLiveSample("Encapsulation from CSS")}}
## Applying styles inside the shadow DOM
In this section we'll look at two different ways to apply styles inside a shadow DOM tree:
- [_Programmatically_](#constructable_stylesheets), by constructing a {{domxref("CSSStyleSheet")}} object and attaching it to the shadow root.
- [_Declaratively_](#adding_style_elements_in_template_declarations), by adding a {{htmlelement("style")}} element in a {{htmlelement("template")}} element's declaration.
In both cases, the styles defined in the shadow DOM tree are scoped to that tree, so just as page styles don't affect elements in the shadow DOM, shadow DOM styles don't affect elements in the rest of the page.
### Constructable stylesheets
To style page elements in the shadow DOM with constructable stylesheets, we can:
1. Create an empty {{domxref("CSSStyleSheet")}} object
2. Set its content using {{domxref("CSSStyleSheet.replace()")}} or {{domxref("CSSStyleSheet.replaceSync()")}}
3. Add it to the shadow root by assigning it to {{domxref("ShadowRoot.adoptedStyleSheets")}}
Rules defined in the `CSSStyleSheet` will be scoped to the shadow DOM tree, as well as any other DOM trees to which we have assigned it.
Here, again, is the HTML containing our host and a `<span>`:
```html
<div id="host"></div>
<span>I'm not in the shadow DOM</span>
```
This time we will create the shadow DOM and assign a `CSSStyleSheet` object to it:
```js
const sheet = new CSSStyleSheet();
sheet.replaceSync("span { color: red; border: 2px dotted black;}");
const host = document.querySelector("#host");
const shadow = host.attachShadow({ mode: "open" });
shadow.adoptedStyleSheets = [sheet];
const span = document.createElement("span");
span.textContent = "I'm in the shadow DOM";
shadow.appendChild(span);
```
The styles defined in the shadow DOM tree are not applied in the rest of the page:
{{EmbedLiveSample("Constructable stylesheets")}}
### Adding `<style>` elements in `<template>` declarations
An alternative to constructing `CSSStyleSheet` objects is to include a {{htmlelement("style")}} element inside the {{htmlelement("template")}} element used to define a web component.
In this case the HTML includes the `<template>` declaration
```html
<template id="my-element">
<style>
span {
color: red;
border: 2px dotted black;
}
</style>
<span>I'm in the shadow DOM</span>
</template>
<div id="host"></div>
<span>I'm not in the shadow DOM</span>
```
In the JavaScript, we will create the shadow DOM and add the content of the `<template>` to it:
```js
const host = document.querySelector("#host");
const shadow = host.attachShadow({ mode: "open" });
const template = document.getElementById("my-element");
shadow.appendChild(template.content);
```
Again, the styles defined in the `<template>` are applied only within the shadow DOM tree, and not in the rest of the page:
{{EmbedLiveSample("adding_style_elements_in_template_declarations")}}
### Choosing between programmatic and declarative options
Which of these options to use is dependent on your application and personal preference.
Creating a `CSSStyleSheet` and assigning it to the shadow root using `adoptedStyleSheets` allows you to create a single stylesheet and share it among many DOM trees. For example, a component library could create a single stylesheet and then share it among all the custom elements belonging to that library. The browser will parse that stylesheet once. Also, you can make dynamic changes to the stylesheet and have them propagate to all components that use the sheet.
The approach of attaching a `<style>` element is great if you want to be declarative, have few styles, and don't need to share styles across different components.
## Shadow DOM and custom elements
Without the encapsulation provided by shadow DOM, [custom elements](/en-US/docs/Web/API/Web_components/Using_custom_elements) would be impossibly fragile. It would be too easy for a page to accidentally break a custom element's behavior or layout by running some page JavaScript or CSS. As a custom element developer, you'd never know whether the selectors applicable inside your custom element conflicted with those that applied in a page that chose to use your custom element.
Custom elements are implemented as a class which extends either the base {{domxref("HTMLElement")}} or a built-in HTML element such as {{domxref("HTMLParagraphElement")}}. Typically, the custom element itself is a shadow host, and the element creates multiple elements under that root, to provide the internal implementation of the element.
The example below creates a `<filled-circle>` custom element that just renders a circle filled with a solid color.
```js
class FilledCircle extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
// Create a shadow root
// The custom element itself is the shadow host
const shadow = this.attachShadow({ mode: "open" });
// create the internal implementation
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
const circle = document.createElementNS(
"http://www.w3.org/2000/svg",
"circle",
);
circle.setAttribute("cx", "50");
circle.setAttribute("cy", "50");
circle.setAttribute("r", "50");
circle.setAttribute("fill", this.getAttribute("color"));
svg.appendChild(circle);
shadow.appendChild(svg);
}
}
customElements.define("filled-circle", FilledCircle);
```
```html
<filled-circle color="blue"></filled-circle>
```
{{EmbedLiveSample("Shadow DOM and custom elements", 100, 160)}}
For more examples, illustrating different aspects of custom element implementation, see our [guide to custom elements](/en-US/docs/Web/API/Web_components/Using_custom_elements).
## See also
- [Using custom elements](/en-US/docs/Web/API/Web_components/Using_custom_elements)
- [Using templates and slots](/en-US/docs/Web/API/Web_components/Using_templates_and_slots)
- {{domxref("Element.attachShadow()")}}
- {{domxref("ShadowRoot.adoptedStyleSheets")}}
- {{domxref("CSSStyleSheet.replace()")}}
- {{domxref("CSSStyleSheet.replaceSync()")}}
- {{HTMLelement("template")}}
- [CSS scoping](/en-US/docs/Web/CSS/CSS_scoping) module
- {{CSSXref(":host")}}
- {{CSSXref(":host_function", ":host()")}}
- {{CSSXref(":host-context", ":host-context()")}}
- {{CSSXref("::slotted", "::slotted()")}}
- [CSS shadow parts](/en-US/docs/Web/CSS/CSS_shadow_parts) module
- {{CSSXref("::part")}}
| 0 |
data/mdn-content/files/en-us/web/api/web_components | data/mdn-content/files/en-us/web/api/web_components/using_shadow_dom/shadowdom.svg | <svg xmlns="http://www.w3.org/2000/svg" width="1107.438" height="509.114" viewBox="0 0 293.01 134.703"><defs><marker orient="auto" refY="0" refX="0" id="a" style="overflow:visible"><path d="m5.77 0-8.65 5V-5z" style="fill:#0e0e0e;fill-opacity:1;fill-rule:evenodd;stroke:#0e0e0e;stroke-width:1.00000003pt;stroke-opacity:1" transform="scale(.8)"/></marker></defs><g transform="translate(111.753 -38.267)"><path style="opacity:1;fill:#ffefcc;fill-opacity:1;stroke:#000;stroke-width:.49999997;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" d="M64.093 38.517h116.914V172.72H64.093z"/><path style="opacity:1;fill:#cbcbcb;fill-opacity:1;stroke:#000;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" d="M-30.314 84.388h67.469v88.068h-67.469z"/><path d="m-2.934 111.283-12.294 9.755" style="fill:none;stroke:#000;stroke-width:.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"/><path style="opacity:1;fill:#fff;fill-opacity:1;stroke:#000;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" d="M-111.503 59.631h67.469v95.061h-67.469z"/><circle r="9.354" cy="104.907" cx="3.697" style="opacity:1;fill:#3465a4;fill-opacity:1;stroke:#000;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"/><path style="fill:none;stroke:#000;stroke-width:.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m10.172 111.283 12.294 9.755m-.296 16.834v17.954"/><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:4.29636812px;line-height:1.25;font-family:sans-serif;-inkscape-font-specification:sans-serif;font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:middle;fill:#fff;fill-opacity:1;stroke:none;stroke-width:.26458332" x="3.672" y="103.824"><tspan x="3.672" y="103.824" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:sans-serif;-inkscape-font-specification:sans-serif;fill:#fff;stroke-width:.26458332">shadow</tspan><tspan x="3.672" y="109.194" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:sans-serif;-inkscape-font-specification:sans-serif;fill:#fff;stroke-width:.26458332">root</tspan></text><path style="fill:none;stroke:#000;stroke-width:.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m-84.123 86.525-12.294 9.756m25.4-9.756 12.294 9.756"/><circle style="opacity:1;fill:#3465a4;fill-opacity:1;stroke:#000;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" cx="-77.492" cy="80.15" r="9.354"/><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.5097146px;line-height:1.25;font-family:sans-serif;-inkscape-font-specification:sans-serif;font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:middle;fill:#fff;fill-opacity:1;stroke:none;stroke-width:.26458332" x="-77.546" y="81.458"><tspan x="-77.546" y="81.458" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:sans-serif;-inkscape-font-specification:sans-serif;fill:#fff;fill-opacity:1;stroke-width:.26458332">document</tspan></text><path style="fill:none;stroke:#000;stroke-width:.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="M-95.966 113.115v17.953"/><circle r="9.354" cy="104.813" cx="-95.966" style="opacity:1;fill:#4ece98;fill-opacity:1;stroke:#000;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"/><circle style="opacity:1;fill:#4ece98;fill-opacity:1;stroke:#000;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" cx="-95.966" cy="136.563" r="9.354"/><g style="opacity:1"><circle r="9.354" cy="104.813" cx="-59.018" style="opacity:1;fill:#4ece98;fill-opacity:1;stroke:#000;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"/><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:4.29636812px;line-height:1.25;font-family:sans-serif;-inkscape-font-specification:sans-serif;font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:middle;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="-59.044" y="103.729"><tspan x="-59.044" y="103.729" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:sans-serif;-inkscape-font-specification:sans-serif;stroke-width:.26458332">shadow</tspan><tspan x="-59.044" y="109.1" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:sans-serif;-inkscape-font-specification:sans-serif;stroke-width:.26458332">host</tspan></text></g><text y="65.66" x="-107.948" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:5.56728649px;line-height:1.25;font-family:sans-serif;-inkscape-font-specification:sans-serif;font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" xml:space="preserve"><tspan style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:sans-serif;-inkscape-font-specification:sans-serif;text-align:start;text-anchor:start;fill:#000;fill-opacity:1;stroke-width:.26458332" y="65.66" x="-107.948">Document Tree</tspan></text><path style="fill:none;stroke:#0e0e0e;stroke-width:.26499999;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:2.1199999,1.05999995;stroke-dashoffset:0;stroke-opacity:1;marker-end:url(#a)" d="M-49.496 104.813h42.22"/><circle style="opacity:1;fill:#f8cbcb;fill-opacity:1;stroke:#000;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" cx="-14.776" cy="129.57" r="9.354"/><circle r="9.354" cy="161.32" cx="22.171" style="opacity:1;fill:#f8cbcb;fill-opacity:1;stroke:#000;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"/><text y="-30.535" x="-147.139" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:5.56728649px;line-height:1.25;font-family:sans-serif;-inkscape-font-specification:sans-serif;font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:middle;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" xml:space="preserve" transform="rotate(-90)"><tspan style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:sans-serif;-inkscape-font-specification:sans-serif;fill:#000;fill-opacity:1;stroke-width:.26458332" y="-30.535" x="-147.139">Shadow Boundary</tspan></text><text y="90.418" x="-26.669" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:5.56728649px;line-height:1.25;font-family:sans-serif;-inkscape-font-specification:sans-serif;font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" xml:space="preserve"><tspan style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:sans-serif;-inkscape-font-specification:sans-serif;text-align:start;text-anchor:start;fill:#000;fill-opacity:1;stroke-width:.26458332" y="90.418" x="-26.669">Shadow Tree</tspan></text><path style="fill:none;stroke:#000;stroke-width:.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m92.259 67.768-12.295 9.755m25.393-9.755 21.097 9.755"/><circle style="opacity:1;fill:#3465a4;fill-opacity:1;stroke:#000;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" cx="98.89" cy="61.392" r="9.354"/><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:3.5097146px;line-height:1.25;font-family:sans-serif;-inkscape-font-specification:sans-serif;font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:middle;fill:#fff;fill-opacity:1;stroke:none;stroke-width:.26458332" x="98.836" y="62.701"><tspan x="98.836" y="62.701" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:sans-serif;-inkscape-font-specification:sans-serif;fill:#fff;fill-opacity:1;stroke-width:.26458332">document</tspan></text><path style="fill:none;stroke:#000;stroke-width:.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="M80.416 94.357v19.157"/><circle r="9.354" cy="86.055" cx="80.416" style="opacity:1;fill:#4ece98;fill-opacity:1;stroke:#000;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"/><circle style="opacity:1;fill:#4ece98;fill-opacity:1;stroke:#000;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" cx="80.416" cy="121.985" r="9.354"/><g transform="translate(188.733 -18.758)" style="opacity:1"><circle r="9.354" cy="104.813" cx="-59.018" style="opacity:1;fill:#4ece98;fill-opacity:1;stroke:#000;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"/><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:4.29636812px;line-height:1.25;font-family:sans-serif;-inkscape-font-specification:sans-serif;font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:middle;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="-59.044" y="103.729"><tspan x="-59.044" y="103.729" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:sans-serif;-inkscape-font-specification:sans-serif;stroke-width:.26458332">shadow</tspan><tspan x="-59.044" y="109.1" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:sans-serif;-inkscape-font-specification:sans-serif;stroke-width:.26458332">host</tspan></text></g><path style="fill:none;stroke:#000;stroke-width:.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m123.083 92.974-12.294 20.478m25.4-20.478 12.294 20.478m-.295 16.834v17.954"/><circle style="opacity:1;fill:#f8cbcb;fill-opacity:1;stroke:#000;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" cx="148.188" cy="153.735" r="9.354"/><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:5.56728649px;line-height:1.25;font-family:sans-serif;-inkscape-font-specification:sans-serif;font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:start;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="67.648" y="44.546"><tspan x="67.648" y="44.546" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:sans-serif;-inkscape-font-specification:sans-serif;text-align:start;text-anchor:start;fill:#000;fill-opacity:1;stroke-width:.26458332">Flattened Tree (for rendering)</tspan></text><path style="opacity:1;fill:none;fill-opacity:1;stroke:#000;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:3.00000008,3.00000008;stroke-dashoffset:0;stroke-opacity:1" d="M98.51 108.977h80.832v57.867H98.51z"/><text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:5.56728697px;line-height:1.25;font-family:sans-serif;-inkscape-font-specification:sans-serif;font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:end;letter-spacing:0;word-spacing:0;writing-mode:lr-tb;text-anchor:end;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="177.639" y="114.654"><tspan x="177.639" y="114.654" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:sans-serif;-inkscape-font-specification:sans-serif;text-align:end;text-anchor:end;fill:#000;fill-opacity:1;stroke-width:.26458332">Shadow</tspan><tspan x="177.639" y="121.614" style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:sans-serif;-inkscape-font-specification:sans-serif;text-align:end;text-anchor:end;fill:#000;fill-opacity:1;stroke-width:.26458332">Tree</tspan></text><path style="opacity:1;fill:#fff72c;fill-opacity:.50196078;stroke:#0e0e0e;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" d="M56.25 66.474v3.28H40.023v6.414H56.25v3.28l6.443-6.487z"/><circle r="9.354" cy="129.57" cx="22.171" style="opacity:1;fill:#f8cbcb;fill-opacity:1;stroke:#000;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"/><circle r="9.354" cy="121.985" cx="148.188" style="opacity:1;fill:#f8cbcb;fill-opacity:1;stroke:#000;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"/><circle style="opacity:1;fill:#f8cbcb;fill-opacity:1;stroke:#000;stroke-width:.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" cx="111.241" cy="121.985" r="9.354"/></g></svg> | 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/webgl_draw_buffers/index.md | ---
title: WEBGL_draw_buffers extension
short-title: WEBGL_draw_buffers
slug: Web/API/WEBGL_draw_buffers
page-type: webgl-extension
browser-compat: api.WEBGL_draw_buffers
---
{{APIRef("WebGL")}}
The **`WEBGL_draw_buffers`** extension is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and enables a fragment shader to write to several textures, which is useful for [deferred shading](https://hacks.mozilla.org/2014/01/webgl-deferred-shading/), for example.
WebGL extensions are available using the {{domxref("WebGLRenderingContext.getExtension()")}} method. For more information, see also [Using Extensions](/en-US/docs/Web/API/WebGL_API/Using_Extensions) in the [WebGL tutorial](/en-US/docs/Web/API/WebGL_API/Tutorial).
> **Note:** This extension is only available to {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}} contexts. In {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}}, the functionality of this extension is available on the WebGL2 context by default. In WebGL 2, the constants are available without the "WEBGL" suffix and the new GLSL built-ins require GLSL `#version 300 es`.
## Constants
This extension exposes new constants, which can be used in the {{domxref("WebGLRenderingContext.framebufferRenderbuffer()", "gl.framebufferRenderbuffer()")}}, {{domxref("WebGLRenderingContext.framebufferTexture2D()", "gl.framebufferTexture2D()")}}, {{domxref("WebGLRenderingContext.getFramebufferAttachmentParameter()", "gl.getFramebufferAttachmentParameter()")}} {{domxref("WEBGL_draw_buffers.drawBuffersWEBGL()", "ext.drawBuffersWEBGL()")}}, and {{domxref("WebGLRenderingContext.getParameter()", "gl.getParameter()")}} methods.
- `ext.COLOR_ATTACHMENT0_WEBGL ext.COLOR_ATTACHMENT1_WEBGL ext.COLOR_ATTACHMENT2_WEBGL ext.COLOR_ATTACHMENT3_WEBGL ext.COLOR_ATTACHMENT4_WEBGL ext.COLOR_ATTACHMENT5_WEBGL ext.COLOR_ATTACHMENT6_WEBGL ext.COLOR_ATTACHMENT7_WEBGL ext.COLOR_ATTACHMENT8_WEBGL ext.COLOR_ATTACHMENT9_WEBGL ext.COLOR_ATTACHMENT10_WEBGL ext.COLOR_ATTACHMENT11_WEBGL ext.COLOR_ATTACHMENT12_WEBGL ext.COLOR_ATTACHMENT13_WEBGL ext.COLOR_ATTACHMENT14_WEBGL ext.COLOR_ATTACHMENT15_WEBGL`
- : A {{domxref("WebGL_API/Types", "GLenum")}} specifying a color buffer.
- `ext.DRAW_BUFFER0_WEBGL ext.DRAW_BUFFER1_WEBGL ext.DRAW_BUFFER2_WEBGL ext.DRAW_BUFFER3_WEBGL ext.DRAW_BUFFER4_WEBGL ext.DRAW_BUFFER5_WEBGL ext.DRAW_BUFFER6_WEBGL ext.DRAW_BUFFER7_WEBGL ext.DRAW_BUFFER8_WEBGL ext.DRAW_BUFFER9_WEBGL ext.DRAW_BUFFER10_WEBGL ext.DRAW_BUFFER11_WEBGL ext.DRAW_BUFFER12_WEBGL ext.DRAW_BUFFER13_WEBGL ext.DRAW_BUFFER14_WEBGL ext.DRAW_BUFFER15_WEBGL`
- : A {{domxref("WebGL_API/Types", "GLenum")}} returning a draw buffer.
- `ext.MAX_COLOR_ATTACHMENTS_WEBGL`
- : A {{domxref("WebGL_API/Types", "GLint")}} indicating the maximum number of framebuffer color attachment points.
- `ext.MAX_DRAW_BUFFERS_WEBGL`
- : A {{domxref("WebGL_API/Types", "GLint")}} indicating the maximum number of draw buffers.
## Instance methods
This extension exposes one new method.
- {{domxref("WEBGL_draw_buffers.drawBuffersWEBGL()", "ext.drawBuffersWEBGL()")}}
- : Defines the draw buffers to which all fragment colors are written. (When using {{domxref("WebGL2RenderingContext", "WebGL2")}}, this method is available as {{domxref("WebGL2RenderingContext.drawBuffers()", "gl.drawBuffers()")}} by default).
## Examples
Enabling the extension:
```js
const ext = gl.getExtension("WEBGL_draw_buffers");
```
Binding multiple textures (to a `tx[]` array) to different framebuffer color attachments:
```js
const fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
ext.COLOR_ATTACHMENT0_WEBGL,
gl.TEXTURE_2D,
tx[0],
0,
);
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
ext.COLOR_ATTACHMENT1_WEBGL,
gl.TEXTURE_2D,
tx[1],
0,
);
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
ext.COLOR_ATTACHMENT2_WEBGL,
gl.TEXTURE_2D,
tx[2],
0,
);
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
ext.COLOR_ATTACHMENT3_WEBGL,
gl.TEXTURE_2D,
tx[3],
0,
);
```
Mapping the color attachments to draw buffer slots that the fragment shader will write to using `gl_FragData`:
```js
ext.drawBuffersWEBGL([
ext.COLOR_ATTACHMENT0_WEBGL, // gl_FragData[0]
ext.COLOR_ATTACHMENT1_WEBGL, // gl_FragData[1]
ext.COLOR_ATTACHMENT2_WEBGL, // gl_FragData[2]
ext.COLOR_ATTACHMENT3_WEBGL, // gl_FragData[3]
]);
```
Shader code that writes to multiple textures:
```html
<script type="x-shader/x-fragment">
#extension GL_EXT_draw_buffers : require
precision highp float;
void main(void) {
gl_FragData[0] = vec4(0.25);
gl_FragData[1] = vec4(0.5);
gl_FragData[2] = vec4(0.75);
gl_FragData[3] = vec4(1.0);
}
</script>
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("WebGLRenderingContext.getExtension()")}}
- {{domxref("WebGL2RenderingContext.drawBuffers()")}}
- [WebGL deferred shading - Mozilla Hacks blog](https://hacks.mozilla.org/2014/01/webgl-deferred-shading/)
| 0 |
data/mdn-content/files/en-us/web/api/webgl_draw_buffers | data/mdn-content/files/en-us/web/api/webgl_draw_buffers/drawbufferswebgl/index.md | ---
title: "WEBGL_draw_buffers: drawBuffersWEBGL() method"
short-title: drawBuffersWEBGL()
slug: Web/API/WEBGL_draw_buffers/drawBuffersWEBGL
page-type: webgl-extension-method
browser-compat: api.WEBGL_draw_buffers.drawBuffersWEBGL
---
{{APIRef("WebGL")}}
The **`WEBGL_draw_buffers.drawBuffersWEBGL()`** method is part
of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and allows you to define
the draw buffers to which all fragment colors are written.
This method is part of the {{domxref("WEBGL_draw_buffers")}} extension.
> **Note:** When using {{domxref("WebGL2RenderingContext", "WebGL2")}},
> this method is available as {{domxref("WebGL2RenderingContext.drawBuffers()", "gl.drawBuffers()")}}
> by default and the constants are named `gl.COLOR_ATTACHMENT1` etc. without the "WEBGL" suffix.
## Syntax
```js-nolint
drawBuffersWEBGL(buffers)
```
### Parameters
- `buffers`
- : An {{jsxref("Array")}} of {{domxref("WebGL_API/Types", "GLenum")}} constants defining drawing buffers.
Possible values:
- `gl.NONE`: The fragment shader is not written to any color buffer.
- `gl.BACK`: The fragment shader is written to the back color buffer.
- `ext.COLOR_ATTACHMENT0_WEBGL` The fragment shader is written the
n-th color attachment of the framebuffer.
- `ext.COLOR_ATTACHMENT1_WEBGL`
- `ext.COLOR_ATTACHMENT2_WEBGL`
- `ext.COLOR_ATTACHMENT3_WEBGL`
- `ext.COLOR_ATTACHMENT4_WEBGL`
- `ext.COLOR_ATTACHMENT5_WEBGL`
- `ext.COLOR_ATTACHMENT6_WEBGL`
- `ext.COLOR_ATTACHMENT7_WEBGL`
- `ext.COLOR_ATTACHMENT8_WEBGL`
- `ext.COLOR_ATTACHMENT9_WEBGL`
- `ext.COLOR_ATTACHMENT10_WEBGL`
- `ext.COLOR_ATTACHMENT11_WEBGL`
- `ext.COLOR_ATTACHMENT12_WEBGL`
- `ext.COLOR_ATTACHMENT13_WEBGL`
- `ext.COLOR_ATTACHMENT14_WEBGL`
- `ext.COLOR_ATTACHMENT15_WEBGL`
### Return value
None ({{jsxref("undefined")}}).
## Examples
See {{domxref("WEBGL_draw_buffers")}} for more context with this example code.
```js
ext.drawBuffersWEBGL([
ext.COLOR_ATTACHMENT0_WEBGL, // gl_FragData[0]
ext.COLOR_ATTACHMENT1_WEBGL, // gl_FragData[1]
ext.COLOR_ATTACHMENT2_WEBGL, // gl_FragData[2]
ext.COLOR_ATTACHMENT3_WEBGL, // gl_FragData[3]
]);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("WEBGL_draw_buffers")}}
- {{domxref("WebGLRenderingContext.getExtension()")}}
- {{domxref("WebGLRenderingContext.framebufferRenderbuffer()")}}
- {{domxref("WebGLRenderingContext.framebufferTexture2D()")}}
- {{domxref("WebGLRenderingContext.getFramebufferAttachmentParameter()")}}
- {{domxref("WebGLRenderingContext.getParameter()")}}
- [WebGL deferred shading - Mozilla Hacks blog](https://hacks.mozilla.org/2014/01/webgl-deferred-shading/)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/paymentrequestevent/index.md | ---
title: PaymentRequestEvent
slug: Web/API/PaymentRequestEvent
page-type: web-api-interface
status:
- experimental
browser-compat: api.PaymentRequestEvent
---
{{SeeCompatTable}}{{APIRef("Payment Handler API")}}
The **`PaymentRequestEvent`** interface of the {{domxref("Payment Handler API", "", "", "nocode")}} is the object passed to a payment handler when a {{domxref("PaymentRequest")}} is made.
{{InheritanceDiagram}}
## Constructor
- {{domxref("PaymentRequestEvent.PaymentRequestEvent","PaymentRequestEvent()")}} {{Experimental_Inline}}
- : Creates a new `PaymentRequestEvent` object instance.
## Instance properties
- {{domxref("PaymentRequestEvent.instrumentKey","instrumentKey")}} {{ReadOnlyInline}} {{Deprecated_Inline}} {{Non-standard_Inline}}
- : Returns an object reflecting the payment instrument selected by the user or an empty string if the user has not registered or chosen a payment instrument.
- {{domxref("PaymentRequestEvent.methodData","methodData")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns an array of objects containing payment method identifiers for the payment methods that the website accepts and any associated payment method specific data.
- {{domxref("PaymentRequestEvent.modifiers","modifiers")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns an array of objects containing changes to payment details.
- {{domxref("PaymentRequestEvent.paymentRequestId","paymentRequestId")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the ID of the {{domxref("PaymentRequest")}} object.
- {{domxref("PaymentRequestEvent.paymentRequestOrigin","paymentRequestOrigin")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the origin where the {{domxref("PaymentRequest")}} object was initialized.
- {{domxref("PaymentRequestEvent.topOrigin","topOrigin")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the top-level origin where the {{domxref("PaymentRequest")}} object was initialized.
- {{domxref("PaymentRequestEvent.total","total")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the total amount being requested for payment.
## Instance methods
- {{domxref("PaymentRequestEvent.openWindow","openWindow()")}} {{Experimental_Inline}}
- : Opens the specified URL in a new window, if and only if the given URL is on the same origin as the calling page. It returns a {{jsxref("Promise")}} that resolves with a reference to a {{domxref("WindowClient")}}.
- {{domxref("PaymentRequestEvent.respondWith","respondWith()")}} {{Experimental_Inline}}
- : Prevents the default event handling and allows you to provide a {{jsxref("Promise")}} for a {{domxref("PaymentResponse")}} object yourself.
## Examples
When 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.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [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/paymentrequestevent | data/mdn-content/files/en-us/web/api/paymentrequestevent/toporigin/index.md | ---
title: "PaymentRequestEvent: topOrigin property"
short-title: topOrigin
slug: Web/API/PaymentRequestEvent/topOrigin
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.PaymentRequestEvent.topOrigin
---
{{SeeCompatTable}}{{APIRef("Payment Handler API")}}
The **`topOrigin`** read-only property of the
{{domxref("PaymentRequestEvent")}} interface returns the top-level payee origin where
the {{domxref("PaymentRequest")}} object was initialized.
## Value
A string.
## Examples
```js
self.addEventListener("paymentrequest", (e) => {
console.log(e.topOrigin);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [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/paymentrequestevent | data/mdn-content/files/en-us/web/api/paymentrequestevent/methoddata/index.md | ---
title: "PaymentRequestEvent: methodData property"
short-title: methodData
slug: Web/API/PaymentRequestEvent/methodData
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.PaymentRequestEvent.methodData
---
{{SeeCompatTable}}{{APIRef("Payment Handler API")}}
The **`methodData`** read-only property of the
{{domxref("PaymentRequestEvent")}} interface returns an array of
`PaymentMethodData` objects containing payment method identifiers for the
payment methods that the website accepts and any associated payment method-specific
data.
## Value
An array of `PaymentMethodData` objects. Each object contains the following properties:
- `supportedMethods`
- : A payment method identifier for a payment method that the merchant website accepts.
- `data`
- : An object that provides optional information that might be needed by the supported payment methods. If supplied, it will be JSON-serialized.
## Examples
```js
self.addEventListener("paymentrequest", (e) => {
console.log(e.methodData);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [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/paymentrequestevent | data/mdn-content/files/en-us/web/api/paymentrequestevent/paymentrequestid/index.md | ---
title: "PaymentRequestEvent: paymentRequestId property"
short-title: paymentRequestId
slug: Web/API/PaymentRequestEvent/paymentRequestId
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.PaymentRequestEvent.paymentRequestId
---
{{SeeCompatTable}}{{APIRef("Payment Handler API")}}
The **`paymentRequestId`** read-only property of the
{{domxref("PaymentRequestEvent")}} interface returns the ID of the
{{domxref("PaymentRequest")}} object.
## Value
A string containing the ID.
## Examples
```js
self.addEventListener("paymentrequest", (e) => {
console.log(e.paymentRequestId);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [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/paymentrequestevent | data/mdn-content/files/en-us/web/api/paymentrequestevent/modifiers/index.md | ---
title: "PaymentRequestEvent: modifiers property"
short-title: modifiers
slug: Web/API/PaymentRequestEvent/modifiers
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.PaymentRequestEvent.modifiers
---
{{SeeCompatTable}}{{APIRef("Payment Handler API")}}
The **`modifiers`** read-only property of the
{{domxref("PaymentRequestEvent")}} interface returns an {{jsxref("Array")}} of `PaymentDetailsModifier` objects containing modifiers for payment details.
## Value
An array of objects containing modifiers for payment details. These objects contain the following properties:
- `supportedMethods`
- : A payment method identifier. The members of the object only apply to the payment if the user selects this payment method.
- `total`
- : A `PaymentItem` object containing the following properties:
- `label`
- : A string containing a human-readable description of the item, which may be displayed to the user.
- `amount`
- : A `PaymentCurrencyAmount` object (see [`total` > Value](/en-US/docs/Web/API/PaymentRequestEvent/total#value)).
- `pending`
- : A boolean. When set to true it means that the `amount` member is not final. This is commonly used to show items such as shipping or tax amounts that depend upon selection of shipping address or shipping option.
- `additionalDisplayItems`
- : An array of `PaymentItem` objects providing additional display items to be included in the payment details. This member is commonly used to add a discount or surcharge line item indicating the reason for the different total amount for the selected payment method that the user agent MAY display.
- `data`
- : An object that provides optional information that might be needed by the supported payment methods. If supplied, it will be JSON-serialized.
## Examples
```js
self.addEventListener("paymentrequest", (e) => {
console.log(e.modifiers);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [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/paymentrequestevent | data/mdn-content/files/en-us/web/api/paymentrequestevent/paymentrequestorigin/index.md | ---
title: "PaymentRequestEvent: paymentRequestOrigin property"
short-title: paymentRequestOrigin
slug: Web/API/PaymentRequestEvent/paymentRequestOrigin
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.PaymentRequestEvent.paymentRequestOrigin
---
{{SeeCompatTable}}{{APIRef("Payment Handler API")}}
The **`paymentRequestOrigin`** read-only property of the
{{domxref("PaymentRequestEvent")}} interface returns the origin where the
{{domxref("PaymentRequest")}} object was initialized.
## Value
A string.
## Examples
```js
self.addEventListener("paymentrequest", (e) => {
console.log(e.paymentRequestOrigin);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [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/paymentrequestevent | data/mdn-content/files/en-us/web/api/paymentrequestevent/changepaymentmethod/index.md | ---
title: "PaymentRequestEvent: changePaymentMethod() method"
short-title: changePaymentMethod()
slug: Web/API/PaymentRequestEvent/changePaymentMethod
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.PaymentRequestEvent.changePaymentMethod
---
{{APIRef("Payment Handler API")}}{{SeeCompatTable}}
The **`changePaymentMethod()`** method of the {{domxref("PaymentRequestEvent")}} interface is used by the payment handler to get an updated total, given such payment method details as the billing address.
When this method is invoked, a {{domxref("PaymentMethodChangeEvent")}} is fired.
## Syntax
```js-nolint
changePaymentMethod(methodName)
changePaymentMethod(methodName, methodDetails)
```
### Parameters
- `methodName`
- : The name of the payment method to be used.
- `methodDetails` {{optional_inline}}
- : An object containing method-specific details that are being updated.
### Return value
A {{jsxref("Promise")}} that resolves with a `PaymentRequestDetailsUpdate` object. This object contains the following properties:
- `error`
- : A string that explains why the user-selected payment method cannot be used.
- `total`
- : An updated total based on the changed payment method. The total can change, for example, because the billing address of the payment method selected by the user changes the applicable sales tax.
- `modifiers`
- : An {{jsxref("Array")}} of `PaymentDetailsModifier` objects, whose properties are described in {{domxref("PaymentRequestEvent.modifiers")}}.
- `paymentMethodErrors`
- : An object containing validation errors for the payment method, if any.
## Examples
The following shows a trivial code snippet that could be used in a service worker to send a payment method change notification to the main payment handler window. For a complete test example, see [Payment handler for testing payment method change event](https://rsolomakhin.github.io/pr/apps/pmc/).
```js
function notifyPaymentMethodChanged(e) {
e.changePaymentMethod("someMethod")
.then((paymentMethodChangeResponse) => {
paymentHandlerWindow.postMessage(paymentMethodChangeResponse);
})
.catch((error) => {
sendMessage({ error: error.message });
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [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/paymentrequestevent | data/mdn-content/files/en-us/web/api/paymentrequestevent/instrumentkey/index.md | ---
title: "PaymentRequestEvent: instrumentKey property"
short-title: instrumentKey
slug: Web/API/PaymentRequestEvent/instrumentKey
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.PaymentRequestEvent.instrumentKey
---
{{APIRef("Payment Handler API")}}{{deprecated_header}}{{non-standard_header}}
The **`instrumentKey`** read-only property of the
{{domxref("PaymentRequestEvent")}} interface returns a
`PaymentInstrument` object reflecting the payment instrument selected by
the user or an empty string if the user has not registered or chosen a payment
instrument.
## Value
A `PaymentInstrument` object.
## Specifications
This feature is no longer part of any specification.
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/paymentrequestevent | data/mdn-content/files/en-us/web/api/paymentrequestevent/total/index.md | ---
title: "PaymentRequestEvent: total property"
short-title: total
slug: Web/API/PaymentRequestEvent/total
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.PaymentRequestEvent.total
---
{{SeeCompatTable}}{{APIRef("Payment Handler API")}}
The **`total`** read-only property of the {{domxref("PaymentRequestEvent")}} interface returns a
`PaymentCurrencyAmount` object containing the total amount being requested for payment.
## Value
A `PaymentCurrencyAmount` object. This object contains the following properties:
- `currency`
- : A string containing a three-letter [ISO 4217](https://www.iso.org/iso-4217-currency-codes.html) standard currency code representing the currency of the payment. Examples include `USD`, `CAN`, and `GBP`.
- `value`
- : A string containing a decimal monetary value, e.g. `2.55`.
## Examples
```js
self.addEventListener("paymentrequest", (e) => {
console.log(e.total);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [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/paymentrequestevent | data/mdn-content/files/en-us/web/api/paymentrequestevent/paymentrequestevent/index.md | ---
title: "PaymentRequestEvent: PaymentRequestEvent() constructor"
short-title: PaymentRequestEvent()
slug: Web/API/PaymentRequestEvent/PaymentRequestEvent
page-type: web-api-constructor
status:
- experimental
browser-compat: api.PaymentRequestEvent.PaymentRequestEvent
---
{{APIRef("Payment Handler API")}}{{SeeCompatTable}}
The **`PaymentRequestEvent`** constructor creates a new {{domxref("PaymentRequestEvent")}} object instance.
## Syntax
```js-nolint
new PaymentRequestEvent(type)
new PaymentRequestEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers set it to `paymentrequest`.
- `options` {{optional_inline}}
- : An object that, in addition of the properties defined in {{domxref("ExtendableEvent/ExtendableEvent", "ExtendableEvent()")}}, can have the following properties:
- `methodData`
- : An array of `PaymentMethodData` objects (see [`methodData` > Value](/en-US/docs/Web/API/PaymentRequestEvent/methodData#value)) containing payment method identifiers for the payment methods
that the website accepts and any associated payment method-specific data.
- `modifiers`
- : An array of objects containing changes to payment details.
- `paymentRequestId`
- : The ID of the {{domxref("PaymentRequest")}} object.
- `paymentRequestOrigin`
- : The origin where the {{domxref("PaymentRequest")}} object was initialized.
- `topOrigin`
- : The top-level origin where the {{domxref("PaymentRequest")}} object was initialized.
- `total`
- : The total amount being requested for payment.
## Return value
A new {{domxref("PaymentRequestEvent")}} object.
## Examples
A developer would not use this constructor manually. A new `PaymentRequestEvent` object is constructed when a handler is invoked as a result of the {{domxref("ServiceWorkerGlobalScope.paymentrequest_event", "paymentrequest")}} event firing.
```js
self.addEventListener("paymentrequest", (e) => {
// ...
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [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/paymentrequestevent | data/mdn-content/files/en-us/web/api/paymentrequestevent/respondwith/index.md | ---
title: "PaymentRequestEvent: respondWith() method"
short-title: respondWith()
slug: Web/API/PaymentRequestEvent/respondWith
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.PaymentRequestEvent.respondWith
---
{{APIRef("Payment Handler API")}}{{SeeCompatTable}}
The **`respondWith()`** method of the {{domxref("PaymentRequestEvent")}} interface prevents the default event handling and allows you to provide a {{jsxref("Promise")}} for a {{domxref("PaymentResponse")}} object yourself.
## Syntax
```js-nolint
respondWith(promise)
```
### Parameters
- `promise`
- : A {{jsxref('Promise')}} that resolves with a `PaymentHandlerResponse` object.
### Return value
A `PaymentHandlerResponse` object. This contains the following properties:
- `methodName`
- : The payment method identifier for the payment method that the user selected to fulfill the transaction.
- `details`
- : A JSON-serializable object that provides a payment method-specific message used by the merchant to process the transaction and determine a successful fund transfer. See [7.1.2 details attribute](https://w3c.github.io/payment-handler/#details-attribute) for more details.
## Examples
```js
…
self.addEventListener('paymentrequest', async e => {
…
// Retain a promise for future resolution
// Polyfill for PromiseResolver at link below.
resolver = new PromiseResolver();
// Pass a promise that resolves when payment is done.
e.respondWith(resolver.promise);
// Open the checkout page.
try {
// Open the window and preserve the client
client = await e.openWindow(checkoutURL);
if (!client) {
// Reject if the window fails to open
throw 'Failed to open window';
}
} catch (err) {
// Reject the promise on failure
resolver.reject(err);
};
});
…
```
See [Open the payment handler window to display the web-based payment app frontend](https://web.dev/articles/orchestrating-payment-transactions#open-payment-handler-window) for more details about how this would be used.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [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/paymentrequestevent | data/mdn-content/files/en-us/web/api/paymentrequestevent/openwindow/index.md | ---
title: "PaymentRequestEvent: openWindow() method"
short-title: openWindow()
slug: Web/API/PaymentRequestEvent/openWindow
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.PaymentRequestEvent.openWindow
---
{{APIRef("Payment Handler API")}}{{SeeCompatTable}}
The **`openWindow()`** method of the {{domxref("PaymentRequestEvent")}} interface opens the specified URL in a new window, only if the given URL is on the same origin as the calling page. It returns a {{jsxref("Promise")}} that resolves with a reference to a {{domxref("WindowClient")}}.
## Syntax
```js-nolint
openWindow(url)
```
### Parameters
- `url`
- : The URL to open in the new window. It must be on the same origin as the calling
page.
### Return value
A {{jsxref("Promise")}} that resolves with a reference to a
{{domxref("WindowClient")}}.
## Examples
```js
…
self.addEventListener('paymentrequest', async e => {
…
// Retain a promise for future resolution
// Polyfill for PromiseResolver at link below.
resolver = new PromiseResolver();
// Pass a promise that resolves when payment is done.
e.respondWith(resolver.promise);
// Open the checkout page.
try {
// Open the window and preserve the client
client = await e.openWindow(checkoutURL);
if (!client) {
// Reject if the window fails to open
throw 'Failed to open window';
}
} catch (err) {
// Reject the promise on failure
resolver.reject(err);
};
});
…
```
See [Open the payment handler window to display the web-based payment app frontend](https://web.dev/articles/orchestrating-payment-transactions#open-payment-handler-window) for more details about how this would be used.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [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/performanceobserverentrylist/index.md | ---
title: PerformanceObserverEntryList
slug: Web/API/PerformanceObserverEntryList
page-type: web-api-interface
browser-compat: api.PerformanceObserverEntryList
---
{{APIRef("Performance API")}}
The **`PerformanceObserverEntryList`** interface is a list of {{domxref("PerformanceEntry","performance events", '', 'true')}} that were explicitly observed via the {{domxref("PerformanceObserver.observe","observe()")}} method.
## Instance methods
- {{domxref("PerformanceObserverEntryList.getEntries","PerformanceObserverEntryList.getEntries()")}}
- : Returns a list of all explicitly observed {{domxref("PerformanceEntry")}} objects.
- {{domxref("PerformanceObserverEntryList.getEntriesByType","PerformanceObserverEntryList.getEntriesByType()")}}
- : Returns a list of all explicitly observed {{domxref("PerformanceEntry")}} objects of the given entry type.
- {{domxref("PerformanceObserverEntryList.getEntriesByName","PerformanceObserverEntryList.getEntriesByName()")}}
- : Returns a list of all explicitly observed {{domxref("PerformanceEntry")}} objects based on the given name and entry type.
## Example
### Using PerformanceObserverEntryList
In the following example, `list` is the `PerformanceObserverEntryList` object. The {{domxref("PerformanceObserverEntryList.getEntries","getEntries()")}} method is called to get all explicitly observed {{domxref("PerformanceEntry")}} objects which are "measure" and "mark" in this case.
```js
function perfObserver(list, observer) {
list.getEntries().forEach((entry) => {
if (entry.entryType === "mark") {
console.log(`${entry.name}'s startTime: ${entry.startTime}`);
}
if (entry.entryType === "measure") {
console.log(`${entry.name}'s duration: ${entry.duration}`);
}
});
}
const observer = new PerformanceObserver(perfObserver);
observer.observe({ entryTypes: ["measure", "mark"] });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/performanceobserverentrylist | data/mdn-content/files/en-us/web/api/performanceobserverentrylist/getentries/index.md | ---
title: "PerformanceObserverEntryList: getEntries() method"
short-title: getEntries()
slug: Web/API/PerformanceObserverEntryList/getEntries
page-type: web-api-instance-method
browser-compat: api.PerformanceObserverEntryList.getEntries
---
{{APIRef("Performance API")}}
The **`getEntries()`** method of the {{domxref("PerformanceObserverEntryList")}} interface returns a list of explicitly observed {{domxref("PerformanceEntry","performance entry", '', 'true')}} objects. The list's members are determined by the set of {{domxref("PerformanceEntry.entryType","entry types", '', 'true')}} specified in the call to the {{domxref("PerformanceObserver.observe","observe()")}} method. The list is available in the observer's callback function (as the first parameter in the callback).
## Syntax
```js-nolint
getEntries()
```
### Return value
A list of explicitly observed {{domxref("PerformanceEntry")}} objects. The items will be in chronological order based on the entries' {{domxref("PerformanceEntry.startTime","startTime")}}. If no objects are found, an empty list is returned.
## Examples
### Working with getEntries, getEntriesByName and getEntriesByType
The following example shows the difference between the `getEntries()`, {{domxref("PerformanceObserverEntryList.getEntriesByName", "getEntriesByName()")}}, and {{domxref("PerformanceObserverEntryList.getEntriesByType", "getEntriesByType()")}} methods.
```js
const observer = new PerformanceObserver((list, obs) => {
// Log all entries
let perfEntries = list.getEntries();
perfEntries.forEach((entry) => {
console.log(`${entry.name}'s duration: ${entry.duration}`);
});
// Log entries named "debugging" with type "measure"
perfEntries = list.getEntriesByName("debugging", "measure");
perfEntries.forEach((entry) => {
console.log(`${entry.name}'s duration: ${entry.duration}`);
});
// Log entries with type "mark"
perfEntries = list.getEntriesByType("mark");
perfEntries.forEach((entry) => {
console.log(`${entry.name}'s startTime: ${entry.startTime}`);
});
});
// Subscribe to various performance event types
observer.observe({
entryTypes: ["mark", "measure", "navigation", "resource"],
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/performanceobserverentrylist | data/mdn-content/files/en-us/web/api/performanceobserverentrylist/getentriesbyname/index.md | ---
title: "PerformanceObserverEntryList: getEntriesByName() method"
short-title: getEntriesByName()
slug: Web/API/PerformanceObserverEntryList/getEntriesByName
page-type: web-api-instance-method
browser-compat: api.PerformanceObserverEntryList.getEntriesByName
---
{{APIRef("Performance API")}}
The **`getEntriesByName()`** method of the {{domxref("PerformanceObserverEntryList")}} interface returns a list of explicitly observed {{domxref("PerformanceEntry","performance entry", '', 'true')}} objects for a given {{domxref("PerformanceEntry.name","name")}} and {{domxref("PerformanceEntry.entryType","entry type")}}. The list's members are determined by the set of {{domxref("PerformanceEntry.entryType","entry types", '', 'entry')}} specified in the call to the {{domxref("PerformanceObserver.observe","observe()")}} method. The list is available in the observer's callback function (as the first parameter in the callback).
## Syntax
```js-nolint
getEntriesByName(name)
getEntriesByName(name, type)
```
### Parameters
- `name`
- : A string representing the name of the entry to retrieve.
- `type` {{optional_inline}}
- : A string representing the type of entry to retrieve such as `"mark"`. The valid entry types are listed in {{domxref("PerformanceEntry.entryType")}}.
### Return value
A list of explicitly _observed_ {{domxref("PerformanceEntry","performance entry", '', 'true')}} objects that have the specified `name` and `type`. If the `type` argument is not specified, only the `name` will be used to determine the entries to return. The items will be in chronological order based on the entries' {{domxref("PerformanceEntry.startTime","startTime")}}. If no objects meet the specified criteria, an empty list is returned.
## Examples
### Working with getEntries, getEntriesByName and getEntriesByType
The following example shows the difference between the {{domxref("PerformanceObserverEntryList.getEntries", "getEntries()")}}, `getEntriesByName()`, and {{domxref("PerformanceObserverEntryList.getEntriesByType", "getEntriesByType()")}} methods.
```js
const observer = new PerformanceObserver((list, obs) => {
// Log all entries
let perfEntries = list.getEntries();
perfEntries.forEach((entry) => {
console.log(`${entry.name}'s duration: ${entry.duration}`);
});
// Log entries named "debugging" with type "measure"
perfEntries = list.getEntriesByName("debugging", "measure");
perfEntries.forEach((entry) => {
console.log(`${entry.name}'s duration: ${entry.duration}`);
});
// Log entries with type "mark"
perfEntries = list.getEntriesByType("mark");
perfEntries.forEach((entry) => {
console.log(`${entry.name}'s startTime: ${entry.startTime}`);
});
});
// Subscribe to various performance event types
observer.observe({
entryTypes: ["mark", "measure", "navigation", "resource"],
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/performanceobserverentrylist | data/mdn-content/files/en-us/web/api/performanceobserverentrylist/getentriesbytype/index.md | ---
title: "PerformanceObserverEntryList: getEntriesByType() method"
short-title: getEntriesByType()
slug: Web/API/PerformanceObserverEntryList/getEntriesByType
page-type: web-api-instance-method
browser-compat: api.PerformanceObserverEntryList.getEntriesByType
---
{{APIRef("Performance API")}}
The **`getEntriesByType()`** method of the {{domxref("PerformanceObserverEntryList")}} returns a list of explicitly _observed_ {{domxref("PerformanceEntry","performance entry", '', 'true')}} objects for a given {{domxref("PerformanceEntry.entryType","performance entry type", '', 'true')}}. The list's members are determined by the set of {{domxref("PerformanceEntry.entryType","entry types", '', 'true')}} specified in the call to the {{domxref("PerformanceObserver.observe","observe()")}} method. The list is available in the observer's callback function (as the first parameter in the callback).
## Syntax
```js-nolint
getEntriesByType(type)
```
### Parameters
- `type`
- : The type of entry to retrieve such as `"mark"`. The valid entry types are listed in {{domxref("PerformanceEntry.entryType")}}.
### Return value
A list of explicitly _observed_ {{domxref("PerformanceEntry")}} objects that have the specified `type`. The items will be in chronological order based on the entries' {{domxref("PerformanceEntry.startTime","startTime")}}. If no objects have the specified `type`, or no argument is provided, an empty list is returned.
## Examples
### Working with getEntries, getEntriesByName and getEntriesByType
The following example shows the difference between the {{domxref("PerformanceObserverEntryList.getEntries", "getEntries()")}}, {{domxref("PerformanceObserverEntryList.getEntriesByName", "getEntriesByName()")}}, and `getEntriesByType()` methods.
```js
const observer = new PerformanceObserver((list, obs) => {
// Log all entries
let perfEntries = list.getEntries();
perfEntries.forEach((entry) => {
console.log(`${entry.name}'s duration: ${entry.duration}`);
});
// Log entries named "debugging" with type "measure"
perfEntries = list.getEntriesByName("debugging", "measure");
perfEntries.forEach((entry) => {
console.log(`${entry.name}'s duration: ${entry.duration}`);
});
// Log entries with type "mark"
perfEntries = list.getEntriesByType("mark");
perfEntries.forEach((entry) => {
console.log(`${entry.name}'s startTime: ${entry.startTime}`);
});
});
// Subscribe to various performance event types
observer.observe({
entryTypes: ["mark", "measure", "navigation", "resource"],
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgrenderingintent/index.md | ---
title: SVGRenderingIntent
slug: Web/API/SVGRenderingIntent
page-type: web-api-interface
status:
- deprecated
browser-compat: api.SVGRenderingIntent
---
{{APIRef("SVG")}}{{deprecated_header}}
The **`SVGRenderingIntent`** interface defines the enumerated list of possible values for {{SVGAttr("rendering-intent")}} attributes or descriptors.
{{InheritanceDiagram}}
> **Warning:** This interface was removed in the SVG 2 specification.
## Constants
<table class="no-markdown">
<tbody>
<tr>
<th>Name</th>
<th>Value</th>
<th>Description</th>
</tr>
<tr>
<td><code>RENDERING_INTENT_UNKNOWN</code></td>
<td>0</td>
<td>
The type is not one of predefined types. It is invalid to attempt to
define a new value of this type or to attempt to switch an existing
value to this type.
</td>
</tr>
<tr>
<td><code>RENDERING_INTENT_AUTO</code></td>
<td>1</td>
<td>Corresponds to the value <code>auto</code>.</td>
</tr>
<tr>
<td><code>RENDERING_INTENT_PERCEPTUAL</code></td>
<td>2</td>
<td>Corresponds to the value <code>perceptual</code>.</td>
</tr>
<tr>
<td><code>RENDERING_INTENT_RELATIVE_COLORIMETRIC</code></td>
<td>3</td>
<td>Corresponds to the value <code>relative-colorimetric</code>.</td>
</tr>
<tr>
<td><code>RENDERING_INTENT_SATURATION</code></td>
<td>4</td>
<td>Corresponds to the value <code>saturation</code>.</td>
</tr>
<tr>
<td><code>RENDERING_INTENT_ABSOLUTE_COLORIMETRIC</code></td>
<td>5</td>
<td>Corresponds to the value <code>absolute-colorimetric</code>.</td>
</tr>
</tbody>
</table>
## Instance properties
_This interface doesn't implement any specific properties._
## Instance methods
_This interface doesn't implement any specific methods._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{SVGAttr("rendering-intent")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/textdecoderstream/index.md | ---
title: TextDecoderStream
slug: Web/API/TextDecoderStream
page-type: web-api-interface
browser-compat: api.TextDecoderStream
---
{{APIRef("Encoding API")}}
The **`TextDecoderStream`** interface of the {{domxref('Encoding API','','',' ')}} converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings.
It is the streaming equivalent of {{domxref("TextDecoder")}}.
## Constructor
- {{domxref("TextDecoderStream.TextDecoderStream","TextDecoderStream()")}}
- : Creates a new `TextDecoderStream` object.
## Instance properties
- {{DOMxRef("TextDecoderStream.encoding")}} {{ReadOnlyInline}}
- : An encoding.
- {{DOMxRef("TextDecoderStream.fatal")}} {{ReadOnlyInline}}
- : A {{jsxref("boolean")}} indicating if the error mode is fatal.
- {{DOMxRef("TextDecoderStream.ignoreBOM")}} {{ReadOnlyInline}}
- : A {{jsxref("boolean")}} indicating whether the byte order mark is ignored.
- {{DOMxRef("TextDecoderStream.readable")}} {{ReadOnlyInline}}
- : Returns the {{domxref("ReadableStream")}} instance controlled by this object.
- {{DOMxRef("TextDecoderStream.writable")}} {{ReadOnlyInline}}
- : Returns the {{domxref("WritableStream")}} instance controlled by this object.
## Examples
- [Examples of streaming structured data and HTML](https://streams.spec.whatwg.org/demos/)
- [An example of fetch request streams which uses `TextDecoderStream`](https://glitch.com/~fetch-request-stream).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("TextEncoderStream")}}
- [Streams API Concepts](/en-US/docs/Web/API/Streams_API/Concepts)
- [Experimenting with the Streams API](https://deanhume.com/experimenting-with-the-streams-api/)
| 0 |
data/mdn-content/files/en-us/web/api/textdecoderstream | data/mdn-content/files/en-us/web/api/textdecoderstream/fatal/index.md | ---
title: "TextDecoderStream: fatal property"
short-title: fatal
slug: Web/API/TextDecoderStream/fatal
page-type: web-api-instance-property
browser-compat: api.TextDecoderStream.fatal
---
{{APIRef("Encoding API")}}
The **`fatal`** read-only property of the {{domxref("TextDecoderStream")}} interface is a {{jsxref("boolean")}} indicating if the error mode of the `TextDecoderStream` object is set to `fatal`.
If the property is `true` then a decoder will throw a {{jsxref("TypeError")}} if it encounters malformed data while decoding.
If `false` the decoder will substitute the invalid data with the replacement character `U+FFFD` (�).
The value of the property is set in the [`TextDecoderStream()` constructor](/en-US/docs/Web/API/TextDecoderStream/TextDecoderStream).
## Value
A {{jsxref("boolean")}} which will return `true` if the error mode is set to "fatal".
Otherwise it returns `false`, indicating that the error mode is "replacement".
## Examples
```js
stream = new TextDecoderStream();
console.log(stream.fatal); // returns false
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/textdecoderstream | data/mdn-content/files/en-us/web/api/textdecoderstream/readable/index.md | ---
title: "TextDecoderStream: readable property"
short-title: readable
slug: Web/API/TextDecoderStream/readable
page-type: web-api-instance-property
browser-compat: api.TextDecoderStream.readable
---
{{APIRef("Encoding API")}}
The **`readable`** read-only property of the {{domxref("TextDecoderStream")}} interface returns a {{domxref("ReadableStream")}}.
## Value
A {{domxref("ReadableStream")}}.
## Examples
This example shows how to return a {{domxref("ReadableStream")}} from a `TextDecoderStream`.
```js
stream = new TextDecoderStream();
console.log(stream.readable); //a ReadableStream
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/textdecoderstream | data/mdn-content/files/en-us/web/api/textdecoderstream/encoding/index.md | ---
title: "TextDecoderStream: encoding property"
short-title: encoding
slug: Web/API/TextDecoderStream/encoding
page-type: web-api-instance-property
browser-compat: api.TextDecoderStream.encoding
---
{{APIRef("Encoding API")}}
The **`encoding`** read-only property of the {{domxref("TextDecoderStream")}} interface returns a string containing the name of the encoding algorithm used by the specific decoder.
The encoding is set by the [constructor](/en-US/docs/Web/API/TextDecoderStream/TextDecoderStream) `label` parameter, and defaults to `utf-8`.
## Value
A string containing the lower-cased ASCII name of the encoding format.
The allowed values are the same as those listed in [`TextDecoder.encoding`](/en-US/docs/Web/API/TextDecoder/encoding) (the labels in [Encoding API Encodings](/en-US/docs/Web/API/Encoding_API/Encodings)).
## Examples
Returning the value of `encoding` from a `TextDecoderStream`.
```js
stream = new TextDecoderStream();
console.log(stream.encoding); // returns the default "utf-8"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/textdecoderstream | data/mdn-content/files/en-us/web/api/textdecoderstream/writable/index.md | ---
title: "TextDecoderStream: writable property"
short-title: writable
slug: Web/API/TextDecoderStream/writable
page-type: web-api-instance-property
browser-compat: api.TextDecoderStream.writable
---
{{APIRef("Encoding API")}}
The **`writable`** read-only property of the {{domxref("TextDecoderStream")}} interface returns a {{domxref("WritableStream")}}.
## Value
A {{domxref("WritableStream")}}.
## Examples
Returning a {{domxref("WritableStream")}} from a `TextDecoderStream`.
```js
stream = new TextDecoderStream();
console.log(stream.writable); // A WritableStream
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/textdecoderstream | data/mdn-content/files/en-us/web/api/textdecoderstream/textdecoderstream/index.md | ---
title: "TextDecoderStream: TextDecoderStream() constructor"
short-title: TextDecoderStream()
slug: Web/API/TextDecoderStream/TextDecoderStream
page-type: web-api-constructor
browser-compat: api.TextDecoderStream.TextDecoderStream
---
{{APIRef("Encoding API")}}
The **`TextDecoderStream()`** constructor creates a new {{domxref("TextDecoderStream")}} object which is used to convert a stream of text in a binary encoding into strings.
## Syntax
```js-nolint
new TextDecoderStream(label)
new TextDecoderStream(label, options)
```
### Parameters
- `label`
- : A string defaulting to `utf-8`.
This may be [any valid label](/en-US/docs/Web/API/Encoding_API/Encodings).
- `options` {{optional_inline}}
- : An object with the following properties:
- `fatal` {{optional_inline}}
- : A boolean value indicating if the {{DOMxRef("TextDecoder.decode()")}} method must throw a {{jsxref("TypeError")}} when decoding invalid data.
It defaults to `false`, which means that the decoder will substitute malformed data with a replacement character.
- `ignoreBOM` {{optional_inline}}
- : A boolean value indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) will be included in the output or skipped over.
It defaults to `false`, which means that the byte order mark will be skipped over when decoding and will not be included in the decoded text.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if the value of `label` is unknown, or is one of the values leading to a `'replacement'` decoding algorithm (`"iso-2022-cn"` or `"iso-2022-cn-ext"`).
## Examples
The following example demonstrates how to decode binary data retrieved from a {{domxref("fetch()")}} call.
The data will be interpreted as UTF-8, as no `label` has been passed.
```js
const response = await fetch("https://example.com");
const stream = response.body.pipeThrough(new TextDecoderStream());
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/textdecoderstream | data/mdn-content/files/en-us/web/api/textdecoderstream/ignorebom/index.md | ---
title: "TextDecoderStream: ignoreBOM property"
short-title: ignoreBOM
slug: Web/API/TextDecoderStream/ignoreBOM
page-type: web-api-instance-property
browser-compat: api.TextDecoderStream.ignoreBOM
---
{{APIRef("Encoding API")}}
The **`ignoreBOM`** read-only property of the {{domxref("TextDecoderStream")}} interface is a {{jsxref('Boolean')}} indicating whether the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) will be included in the output or skipped over.
## Value
`true` if the [byte order mark](https://www.w3.org/International/questions/qa-byte-order-mark) will be included in the decoded text; `false` if it will be skipped over when decoding and omitted.
## Examples
```js
stream = new TextDecoderStream();
console.log(stream.ignoreBOM); // returns false
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/usbouttransferresult/index.md | ---
title: USBOutTransferResult
slug: Web/API/USBOutTransferResult
page-type: web-api-interface
status:
- experimental
browser-compat: api.USBOutTransferResult
---
{{securecontext_header}}{{APIRef("WebUSB API")}}{{SeeCompatTable}}
The `USBOutTransferResult` interface of the [WebUSB API](/en-US/docs/Web/API/WebUSB_API) provides the result from a call to the `transferOut()` and `controlTransferOut()` methods of the `USBDevice` interface. It represents the result from requesting a transfer of data from the USB host to the USB device.
## Constructor
- {{domxref("USBOutTransferResult.USBOutTransferResult", "USBOutTransferResult()")}} {{Experimental_Inline}}
- : Creates a new `USBOutTransferResult` object with the provided `status` and `bytesWritten` fields.
## Instance properties
- {{domxref("USBOutTransferResult.bytesWritten")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the number of bytes from the transfer request that were sent to the device.
- {{domxref("USBOutTransferResult.status")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the status of the transfer request, one of:
- `"ok"` - The transfer was successful.
- `"stall"` - The device indicated an error by generating a stall condition on the endpoint. A stall on a bulk or interrupt endpoint must be cleared by calling `clearHalt()` before `transferOut()` can be called again.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/shadowroot/index.md | ---
title: ShadowRoot
slug: Web/API/ShadowRoot
page-type: web-api-interface
browser-compat: api.ShadowRoot
---
{{APIRef('Shadow DOM')}}
The **`ShadowRoot`** interface of the Shadow DOM API is the root node of a DOM subtree that is rendered separately from a document's main DOM tree.
You can retrieve a reference to an element's shadow root using its {{domxref("Element.shadowRoot")}} property, provided it was created using {{domxref("Element.attachShadow()")}} with the `mode` option set to `open`.
{{InheritanceDiagram}}
## Instance properties
- {{domxref("ShadowRoot.activeElement")}} {{ReadOnlyInline}}
- : Returns the {{domxref('Element')}} within the shadow tree that has focus.
- {{domxref("ShadowRoot.adoptedStyleSheets")}}
- : Add an array of constructed stylesheets to be used by the shadow DOM subtree.
These may be shared with other DOM subtrees that share the same parent {{domxref("Document")}} node, and the document itself.
- {{domxref("ShadowRoot.clonable")}} {{ReadOnlyInline}}
- : Returns a boolean that indicates whether the shadow root is clonable, which can be set via the {{domxref("Element.attachShadow()")}} `clonable` option.
- {{domxref("ShadowRoot.delegatesFocus")}} {{ReadOnlyInline}}
- : Returns a boolean that indicates whether `delegatesFocus` was set when the shadow was attached (see {{domxref("Element.attachShadow()")}}).
- {{DOMxRef("ShadowRoot.fullscreenElement")}} {{ReadOnlyInline}}
- : The element that's currently in full screen mode for this shadow tree.
- {{domxref("ShadowRoot.host")}} {{ReadOnlyInline}}
- : Returns a reference to the DOM element the `ShadowRoot` is attached to.
- {{domxref("ShadowRoot.innerHTML")}}
- : Sets or returns a reference to the DOM tree inside the `ShadowRoot`.
- {{domxref("ShadowRoot.mode")}} {{ReadOnlyInline}}
- : The mode of the `ShadowRoot`, either `open` or `closed`.
This defines whether or not the shadow root's internal features are accessible from JavaScript.
- {{DOMxRef("ShadowRoot.pictureInPictureElement")}} {{ReadOnlyInline}}
- : Returns the {{DOMxRef('Element')}} within the shadow tree that is currently being presented in picture-in-picture mode.
- {{DOMxRef("ShadowRoot.pointerLockElement")}} {{ReadOnlyInline}}
- : Returns the {{DOMxRef('Element')}} set as the target for mouse events while the pointer is locked.
`null` if lock is pending, pointer is unlocked, or if the target is in another tree.
- {{DOMxRef("ShadowRoot.slotAssignment")}} {{ReadOnlyInline}}
- : Returns a string containing the type of slot assignment, either `manual` or `named`.
- {{domxref("ShadowRoot.styleSheets")}} {{ReadOnlyInline}}
- : Returns a {{domxref('StyleSheetList')}} of {{domxref('CSSStyleSheet')}} objects for stylesheets explicitly linked into, or embedded in a shadow tree.
## Instance methods
- {{DOMxRef("ShadowRoot.getAnimations()")}}
- : Returns an array of all {{DOMxRef("Animation")}} objects currently in effect, whose target elements are descendants of the shadow tree.
- {{domxref("ShadowRoot.getSelection()")}} {{Non-standard_Inline}}
- : Returns a {{domxref('Selection')}} object representing the range of text selected by the user, or the current position of the caret.
- {{domxref("ShadowRoot.elementFromPoint()")}} {{Non-standard_Inline}}
- : Returns the topmost element at the specified coordinates.
- {{domxref("ShadowRoot.elementsFromPoint()")}} {{Non-standard_Inline}}
- : Returns an array of all elements at the specified coordinates.
## Events
The following events are available to `ShadowRoot` via event bubbling from {{domxref("HTMLSlotElement")}}:
- `HTMLSlotElement` {{domxref("HTMLSlotElement.slotchange_event", "slotchange")}} event
- : An event fired when the node(s) contained in that slot change.
## Examples
The following snippets are taken from our [life-cycle-callbacks](https://github.com/mdn/web-components-examples/tree/main/life-cycle-callbacks) example ([see it live also](https://mdn.github.io/web-components-examples/life-cycle-callbacks/)), which creates an element that displays a square of a size and color specified in the element's attributes.
Inside the `<custom-square>` element's class definition we include some life cycle callbacks that make a call to an external function, `updateStyle()`, which actually applies the size and color to the element. You'll see that we are passing it `this` (the custom element itself) as a parameter.
```js
connectedCallback() {
console.log('Custom square element added to page.');
updateStyle(this);
}
attributeChangedCallback(name, oldValue, newValue) {
console.log('Custom square element attributes changed.');
updateStyle(this);
}
```
In the `updateStyle()` function itself, we get a reference to the shadow DOM using {{domxref("Element.shadowRoot")}}.
From here we use standard DOM traversal techniques to find the {{htmlelement("style")}} element inside the shadow DOM and then update the CSS found inside it:
```js
function updateStyle(elem) {
const shadow = elem.shadowRoot;
const childNodes = shadow.childNodes;
for (const node of childNodes) {
if (node.nodeName === "STYLE") {
node.textContent = `
div {
width: ${elem.getAttribute("l")}px;
height: ${elem.getAttribute("l")}px;
background-color: ${elem.getAttribute("c")};
}
`;
}
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/shadowroot | data/mdn-content/files/en-us/web/api/shadowroot/mode/index.md | ---
title: "ShadowRoot: mode property"
short-title: mode
slug: Web/API/ShadowRoot/mode
page-type: web-api-instance-property
browser-compat: api.ShadowRoot.mode
---
{{APIRef("Shadow DOM")}}
The **`mode`** read-only property of the {{domxref("ShadowRoot")}}
specifies its mode — either `open` or `closed`. This defines
whether or not the shadow root's internal features are accessible from JavaScript.
When the `mode` of a shadow root is "`closed`", the shadow root's
implementation internals are inaccessible and unchangeable from JavaScript—in the same
way the implementation internals of, for example, the {{HTMLElement("video")}} element
are inaccessible and unchangeable from JavaScript.
## Value
A value defined in the
[`ShadowRootMode`](https://dom.spec.whatwg.org/#enumdef-shadowrootmode)
enum — either `open` or `closed`.
## Examples
```js
// We create a closed shadow root, that is not accessible
let element = document.createElement("div");
element.attachShadow({ mode: "closed" });
element.shadowRoot; // null as the shadow root is closed
// We create an open shadow root, that is accessible
let element2 = document.createElement("div");
element2.attachShadow({ mode: "open" });
console.log(`The shadow is ${element2.shadowRoot.mode}`); // logs "The shadow is open"
element2.shadowRoot.textContent("Opened shadow"); // The shadow is open, we can access it from outside
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/shadowroot | data/mdn-content/files/en-us/web/api/shadowroot/activeelement/index.md | ---
title: "ShadowRoot: activeElement property"
short-title: activeElement
slug: Web/API/ShadowRoot/activeElement
page-type: web-api-instance-property
browser-compat: api.ShadowRoot.activeElement
---
{{APIRef("Shadow DOM")}}
The **`activeElement`** read-only property of the
{{domxref("ShadowRoot")}} interface returns the element within the shadow tree that has focus.
## Value
The {{domxref('Element')}} which currently has focus, or `null` if there is no focused element.
## Examples
```js
let customElem = document.querySelector("my-shadow-dom-element");
let shadow = customElem.shadowRoot;
let focusedElem = shadow.activeElement;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Document.activeElement")}}
| 0 |
data/mdn-content/files/en-us/web/api/shadowroot | data/mdn-content/files/en-us/web/api/shadowroot/pointerlockelement/index.md | ---
title: "ShadowRoot: pointerLockElement property"
short-title: pointerLockElement
slug: Web/API/ShadowRoot/pointerLockElement
page-type: web-api-instance-property
browser-compat: api.ShadowRoot.pointerLockElement
---
{{APIRef("Pointer Lock API")}}
The **`pointerLockElement`** read-only property of the {{domxref("ShadowRoot")}} interface provides the element set as the target for mouse events while the pointer is locked.
It is `null` if lock is pending, pointer is unlocked, or the target is in another tree.
## Value
An {{domxref("Element")}} or `null`.
## Examples
```js
let customElem = document.querySelector("my-shadow-dom-element");
let shadow = customElem.shadowRoot;
let pleElem = shadow.pointerLockElement;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{ domxref("Document.exitPointerLock()") }}
- {{ domxref("Element.requestPointerLock()") }}
- [Pointer Lock](/en-US/docs/Web/API/Pointer_Lock_API)
| 0 |
data/mdn-content/files/en-us/web/api/shadowroot | data/mdn-content/files/en-us/web/api/shadowroot/clonable/index.md | ---
title: "ShadowRoot: clonable property"
short-title: clonable
slug: Web/API/ShadowRoot/clonable
page-type: web-api-instance-property
browser-compat: api.ShadowRoot.clonable
---
{{APIRef("Shadow DOM")}}
The **`clonable`** read-only property of the {{domxref("ShadowRoot")}} interface returns `true` if the shadow root is clonable, and `false` otherwise. It always returns `true` for shadow roots created via declarative shadow DOM. It can be set to `true` using the `clonable` option of the {{domxref("Element.attachShadow()")}} method.
## Examples
```js
const host = document.createElement("div");
const shadowRoot = host.attachShadow({
mode: "open",
clonable: true,
});
shadowRoot.clonable;
// true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/shadowroot | data/mdn-content/files/en-us/web/api/shadowroot/pictureinpictureelement/index.md | ---
title: "ShadowRoot: pictureInPictureElement property"
short-title: pictureInPictureElement
slug: Web/API/ShadowRoot/pictureInPictureElement
page-type: web-api-instance-property
browser-compat: api.ShadowRoot.pictureInPictureElement
---
{{APIRef("Shadow DOM")}}
The **`pictureInPictureElement`** read-only property of the
{{domxref("ShadowRoot")}} interface returns the {{domxref("Element")}} that is currently being
presented in picture-in-picture mode in this shadow tree, or `null` if
picture-in-picture mode is not currently in use.
## Value
A reference to the {{domxref("Element")}} object that's currently in
picture-in-picture mode, or, if picture-in-picture mode isn't currently in use by the
shadow tree, the returned value is `null`.
## Examples
```js
let customElem = document.querySelector("my-shadow-dom-element");
let shadow = customElem.shadowRoot;
let pipElem = shadow.pictureInPictureElement;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Document.pictureInPictureElement")}}
| 0 |
data/mdn-content/files/en-us/web/api/shadowroot | data/mdn-content/files/en-us/web/api/shadowroot/innerhtml/index.md | ---
title: "ShadowRoot: innerHTML property"
short-title: innerHTML
slug: Web/API/ShadowRoot/innerHTML
page-type: web-api-instance-property
browser-compat: api.ShadowRoot.innerHTML
---
{{APIRef("Shadow DOM")}}
The **`innerHTML`** property of the {{domxref("ShadowRoot")}}
interface sets or returns a reference to the DOM tree inside the
`ShadowRoot`.
## Value
A string.
## Examples
```js
let customElem = document.querySelector("my-shadow-dom-element");
let shadow = customElem.shadowRoot;
shadow.innerHTML = "<strong>This element should be more important!</strong>";
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/shadowroot | data/mdn-content/files/en-us/web/api/shadowroot/adoptedstylesheets/index.md | ---
title: "ShadowRoot: adoptedStyleSheets property"
short-title: adoptedStyleSheets
slug: Web/API/ShadowRoot/adoptedStyleSheets
page-type: web-api-instance-property
browser-compat: api.ShadowRoot.adoptedStyleSheets
---
{{APIRef("CSSOM")}}
The **`adoptedStyleSheets`** property of the {{domxref("ShadowRoot")}} interface sets an array of constructed stylesheets to be used by the shadow DOM subtree.
> **Note:** A constructed stylesheet is a stylesheet created programmatically using the [`CSSStyleSheet()` constructor](/en-US/docs/Web/API/CSSStyleSheet/CSSStyleSheet) (as compared to one created by a user-agent when importing a stylesheet from a script, imported using {{HTMLElement('style')}} and {{CSSXref('@import')}}, or linked to via {{HTMLElement('link')}}).
The same constructed stylesheet can be adopted by multiple {{domxref("ShadowRoot")}} instances, and by the parent document (using the {{domxref("Document.adoptedStyleSheets")}} property).
Changing an adopted stylesheet will affect all the adopting objects.
Stylesheets in the `adoptedStyleSheets` property are considered along with the shadow DOM's other stylesheets.
For the purpose of determining the final computed CSS of any element, they are considered to have been added _after_ the other stylesheets in the shadow DOM ([`ShadowRoot.styleSheets`](/en-US/docs/Web/API/ShadowRoot/styleSheets)).
Only stylesheets created using the [`CSSStyleSheet()` constructor](/en-US/docs/Web/API/CSSStyleSheet/CSSStyleSheet), and from within the same parent {{domxref("Document")}} as the shadow root, may be adopted.
## Value
The value is an array of {{domxref("CSSStyleSheet")}} instances that must have been created using the {{domxref("CSSStyleSheet.CSSStyleSheet()", "CSSStyleSheet()")}} constructor within the context of the shadow root's parent {{domxref("Document")}}.
If the array needs to be modified, use in-place mutations like `push()`. The {{domxref("CSSStyleSheet")}} instances themselves can also be modified, and these changes will apply wherever the stylesheet is adopted.
In an earlier version of the specification, the array was not modifiable, so the only way to add new stylesheets was to assign a new array to `adoptedStyleSheets`.
## Examples
### Adopting a stylesheet
The code below first shows a stylesheet being constructed, and then {{domxref("CSSStyleSheet.replaceSync()")}} is called to add a rule to the sheet.
```js
// Create an empty "constructed" stylesheet
const sheet = new CSSStyleSheet();
// Apply a rule to the sheet
sheet.replaceSync("a { color: red; }");
```
We then create a {{domxref("ShadowRoot")}} and pass the sheet object to `adoptedStyleSheets` inside an array.
```js
// Create an element in the document and then create a shadow root:
const node = document.createElement("div");
const shadow = node.attachShadow({ mode: "open" });
// Adopt the sheet into the shadow DOM
shadow.adoptedStyleSheets = [sheet];
```
We can still modify the stylesheets after they have been added to the array.
Below we append a new rule to the same sheet using {{domxref("CSSStyleSheet.insertRule()")}}.
```js
sheet.insertRule("* { background-color: blue; }");
// The document will now have blue background.
```
### Append a new stylesheet
New stylesheets can be _appended_ to the document or shadow root by using `adoptedStyleSheets.push()`:
```js
const extraSheet = new CSSStyleSheet();
extraSheet.replaceSync("p { color: green; }");
// Concat the new sheet.
shadow.adoptedStyleSheets.push(extraSheet);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Constructable Stylesheets](https://web.dev/articles/constructable-stylesheets) (web.dev)
- [Using the Shadow DOM](/en-US/docs/Web/API/Web_components/Using_shadow_DOM)
- [`CSSStyleSheet()` constructor](/en-US/docs/Web/API/CSSStyleSheet/CSSStyleSheet)
- {{domxref("CSSStyleSheet.replaceSync()")}}
- {{domxref("CSSStyleSheet.replace()")}}
- {{domxref("CSSStyleSheet.insertRule()")}}
- {{domxref("CSSStyleSheet.deleteRule()")}}
| 0 |
data/mdn-content/files/en-us/web/api/shadowroot | data/mdn-content/files/en-us/web/api/shadowroot/delegatesfocus/index.md | ---
title: "ShadowRoot: delegatesFocus property"
short-title: delegatesFocus
slug: Web/API/ShadowRoot/delegatesFocus
page-type: web-api-instance-property
browser-compat: api.ShadowRoot.delegatesFocus
---
{{APIRef("Shadow DOM")}}
The **`delegatesFocus`** read-only property of the {{domxref("ShadowRoot")}} interface returns `true` if the shadow root delegates focus, and `false` otherwise.
If `true`, when a non-focusable part of the shadow DOM is clicked, or `.focus()` is called on the host element, the first focusable part is given focus, and the shadow host is given any available `:focus` styling.
Focus is of particular importance for keyboard users (including those using screen readers). `delegatesFocus` default behavior is to focus the first focusable element — which may be undesirable if that element is not meant to be part of the tabbing order (for example, an element with `tabindex="-1"`), or if a more 'important' focusable element should receive initial focus (for instance, the first text field rather than the 'close' button which precedes it). In such cases, the `autofocus` attribute can be specified on the element which should receive initial focus. Use the `autofocus` attribute with caution as it can introduce accessibility issues, such as bypassing important content which may go unnoticed due to focus being set to an element later in the DOM order.
The property value is set using the `delegatesFocus` property of the object passed to {{domxref("Element.attachShadow()")}}).
## Examples
```js
let customElem = document.querySelector("my-shadow-dom-element");
let shadow = customElem.shadowRoot;
// ...
// Does it delegate focus?
let hostElem = shadow.delegatesFocus;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/shadowroot | data/mdn-content/files/en-us/web/api/shadowroot/host/index.md | ---
title: "ShadowRoot: host property"
short-title: host
slug: Web/API/ShadowRoot/host
page-type: web-api-instance-property
browser-compat: api.ShadowRoot.host
---
{{APIRef("Shadow DOM")}}
The **`host`** read-only property of
the {{domxref("ShadowRoot")}} returns a reference to the DOM element the
`ShadowRoot` is attached to.
## Value
A DOM {{domxref('Element')}}.
## Examples
```js
let customElem = document.querySelector("my-shadow-dom-element");
let shadow = customElem.shadowRoot;
// ...
// return the original host element some time later
let hostElem = shadow.host;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`part`](/en-US/docs/Web/HTML/Global_attributes#part) and [`exportparts`](/en-US/docs/Web/HTML/Global_attributes#exportparts) HTML attributes
- {{HTMLelement("template")}} and {{HTMLElement("slot")}} HTML elements
- {{CSSXref(":host")}}, {{CSSXref(":host_function", ":host()")}}, and {{CSSXref(":host-context", ":host-context()")}} CSS pseudo-classes
- {{CSSXref("::part")}} and {{CSSXref("::slotted")}} CSS pseudo-elements
| 0 |
data/mdn-content/files/en-us/web/api/shadowroot | data/mdn-content/files/en-us/web/api/shadowroot/slotassignment/index.md | ---
title: "ShadowRoot: slotAssignment property"
short-title: slotAssignment
slug: Web/API/ShadowRoot/slotAssignment
page-type: web-api-instance-property
browser-compat: api.ShadowRoot.slotAssignment
---
{{APIRef("Shadow DOM")}}
The read-only **`slotAssignment`** property of the {{domxref("ShadowRoot")}} interface returns the _slot assignment mode_ for the shadow DOM tree. Nodes are either automatically assigned (`named`) or manually assigned (`manual`). The value of this property defined using the `slotAssignment` option when calling {{domxref("Element.attachShadow()")}}.
## Value
A string that can be one of:
- `named`
- : Elements are automatically assigned to {{HTMLElement("slot")}} elements within this shadow root. Any descendants of the host with a `slot` attribute which matches the `name` attribute of a `<slot>` within this shadow root will be assigned to that slot. Any top-level children of the host with no `slot` attribute will be assigned to a `<slot>` with no `name` attribute (the "default slot") if one is present.
- `manual`
- : Elements are not automatically assigned to {{HTMLElement("slot")}} elements. Instead, they must be manually assigned with {{domxref("HTMLSlotElement.assign()")}}.
## Examples
In the example below, the `assign()` method is used to display the correct tab in a tabbed application. The function is called and passed the panel to show, which is then assigned to the slot. We test if the `slotAssignment` is `named` to prevent an exception to be raised when {{domxref("HTMLSlotElement.assign()")}} is called.
```js
function UpdateDisplayTab(elem, tabIdx) {
const shadow = elem.shadowRoot;
// This test is usually not needed, but can be useful when debugging
if (shadow.slotAssignment === "named") {
console.error(
"Trying to manually assign a slot on an automatically-assigned (named) slot",
);
}
const slot = shadow.querySelector("slot");
const panels = elem.querySelectorAll("tab-panel");
if (panels.length && tabIdx && tabIdx <= panels.length) {
slot.assign(panels[tabIdx - 1]);
} else {
slot.assign();
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Element.attachShadow()")}}
- {{domxref("HTMLSlotElement.assign()")}}
| 0 |
data/mdn-content/files/en-us/web/api/shadowroot | data/mdn-content/files/en-us/web/api/shadowroot/getanimations/index.md | ---
title: "ShadowRoot: getAnimations() method"
short-title: getAnimations()
slug: Web/API/ShadowRoot/getAnimations
page-type: web-api-instance-method
browser-compat: api.ShadowRoot.getAnimations
---
{{APIRef("Web Animations")}}
The **`getAnimations()`** method of the {{domxref("ShadowRoot")}} interface
returns an array of all {{domxref("Animation")}} objects currently in effect whose
target elements are descendants of the shadow tree. This array includes [CSS Animations](/en-US/docs/Web/CSS/CSS_animations), [CSS Transitions](/en-US/docs/Web/CSS/CSS_transitions), and [Web Animations](/en-US/docs/Web/API/Web_Animations_API).
## Syntax
```js-nolint
getAnimations()
```
### Parameters
None.
### Return value
An {{jsxref("Array")}} of {{domxref("Animation")}} objects, each representing one
animation currently associated with elements which are descendants of the
{{domxref("ShadowRoot")}} on which it's called.
## Examples
The following code snippet will slow down all animations in a shadow tree by halving their
{{domxref("Animation.playbackRate")}}.
```js
let customElem = document.querySelector("my-shadow-dom-element");
let shadow = customElem.shadowRoot;
shadow.getAnimations().forEach((animation) => {
animation.playbackRate *= 0.5;
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
- [CSS Animations](/en-US/docs/Web/CSS/CSS_animations)
- [CSS Transitions](/en-US/docs/Web/CSS/CSS_transitions)
- {{domxref("Element.getAnimations()")}} - Fetch only the animations on a single
{{domxref("Element")}} and its descendants.
- {{domxref("Animation")}}
| 0 |
data/mdn-content/files/en-us/web/api/shadowroot | data/mdn-content/files/en-us/web/api/shadowroot/stylesheets/index.md | ---
title: "ShadowRoot: styleSheets property"
short-title: styleSheets
slug: Web/API/ShadowRoot/styleSheets
page-type: web-api-instance-property
browser-compat: api.ShadowRoot.styleSheets
---
{{APIRef("CSSOM")}}
The **`styleSheets`** read-only property of the {{domxref("ShadowRoot")}} interface
returns a {{domxref('StyleSheetList')}} of {{domxref('CSSStyleSheet')}} objects, for stylesheets explicitly linked into or embedded in a shadow tree.
## Value
A {{domxref('StyleSheetList')}} of {{domxref('CSSStyleSheet')}} objects.
## Examples
```js
let customElem = document.querySelector("my-shadow-dom-element");
let shadow = customElem.shadowRoot;
let styleSheets = shadow.styleSheets;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/shadowroot | data/mdn-content/files/en-us/web/api/shadowroot/fullscreenelement/index.md | ---
title: "ShadowRoot: fullscreenElement property"
short-title: fullscreenElement
slug: Web/API/ShadowRoot/fullscreenElement
page-type: web-api-instance-property
browser-compat: api.ShadowRoot.fullscreenElement
---
{{APIRef("Shadow DOM")}}
The **`fullscreenElement`** read-only property of the
{{domxref("ShadowRoot")}} interface returns the element within the shadow tree that is currently displayed in full screen.
## Value
The {{domxref('Element')}} which is currently is displayed in full screen mode,
or `null` if there is no full screen element.
## Examples
```js
let customElem = document.querySelector("my-shadow-dom-element");
let shadow = customElem.shadowRoot;
let fullscreenElem = shadow.fullscreenElement;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Document.fullscreenElement")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/hmacimportparams/index.md | ---
title: HmacImportParams
slug: Web/API/HmacImportParams
page-type: web-api-interface
spec-urls: https://w3c.github.io/webcrypto/#dfn-HmacImportParams
---
{{ APIRef("Web Crypto API") }}
The **`HmacImportParams`** dictionary of the [Web Crypto API](/en-US/docs/Web/API/Web_Crypto_API) represents the object that should be passed as the `algorithm` parameter into {{domxref("SubtleCrypto.importKey()")}} or {{domxref("SubtleCrypto.unwrapKey()")}}, when generating a key for the [HMAC](/en-US/docs/Web/API/SubtleCrypto/sign#hmac) algorithm.
## Instance properties
- `name`
- : A string. This should be set to `HMAC`.
- `hash`
- : A string representing the name of the [digest function](/en-US/docs/Web/API/SubtleCrypto/digest#supported_algorithms) to use. The can take a value of `SHA-256`, `SHA-384`, or `SHA-512`.
> **Warning:** Although you can technically pass `SHA-1` here, this is strongly discouraged as it is considered vulnerable.
- `length` {{optional_inline}}
- : A `Number` representing the length in bits of the key. If this is omitted the length of the key is equal to the length of the digest generated by the digest function you have chosen. Unless you have a good reason to use a different length, omit this property and use the default.
## Examples
See the examples for {{domxref("SubtleCrypto.importKey()")}}.
## Specifications
{{Specifications}}
## Browser compatibility
Browsers that support the "HMAC" algorithm for the {{domxref("SubtleCrypto.importKey()")}}, {{domxref("SubtleCrypto.unwrapKey()")}} methods will support this type.
## See also
- {{domxref("SubtleCrypto.importKey()")}}.
- {{domxref("SubtleCrypto.unwrapKey()")}}.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/gpushadermodule/index.md | ---
title: GPUShaderModule
slug: Web/API/GPUShaderModule
page-type: web-api-interface
status:
- experimental
browser-compat: api.GPUShaderModule
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`GPUShaderModule`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} represents an internal shader module object, a container for [WGSL](https://gpuweb.github.io/gpuweb/wgsl/) shader code that can be submitted to the GPU for execution by a pipeline.
A `GPUShaderModule` object instance is created using {{domxref("GPUDevice.createShaderModule()")}}.
{{InheritanceDiagram}}
## Instance properties
- {{domxref("GPUShaderModule.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.
## Instance methods
- {{domxref("GPUShaderModule.getCompilationInfo", "getCompilationInfo()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that fulfills with a {{domxref("GPUCompilationInfo")}} object containing messages generated during the `GPUShaderModule`'s compilation.
## Examples
In our [basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/), our shader module is created using the following code:
```js
const shaders = `
struct VertexOut {
@builtin(position) position : vec4f,
@location(0) color : vec4f
}
@vertex
fn vertex_main(@location(0) position: vec4f,
@location(1) color: vec4f) -> VertexOut
{
var output : VertexOut;
output.position = position;
output.color = color;
return output;
}
@fragment
fn fragment_main(fragData: VertexOut) -> @location(0) vec4f
{
return fragData.color;
}
`;
async function init() {
if (!navigator.gpu) {
throw Error("WebGPU not supported.");
}
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) {
throw Error("Couldn't request WebGPU adapter.");
}
let device = await adapter.requestDevice();
// ...
// later on
const shaderModule = device.createShaderModule({
code: shaders,
});
// ...
}
```
## 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/gpushadermodule | data/mdn-content/files/en-us/web/api/gpushadermodule/getcompilationinfo/index.md | ---
title: "GPUShaderModule: getCompilationInfo() method"
short-title: getCompilationInfo()
slug: Web/API/GPUShaderModule/getCompilationInfo
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPUShaderModule.getCompilationInfo
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`getCompilationInfo()`** method of the
{{domxref("GPUShaderModule")}} interface returns a {{jsxref("Promise")}} that fulfills with a {{domxref("GPUCompilationInfo")}} object containing messages generated during the `GPUShaderModule`'s compilation.
## Syntax
```js-nolint
getCompilationInfo()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that fulfills with a {{domxref("GPUCompilationInfo")}} object.
{{domxref("GPUCompilationInfo")}} contains a `messages` property, which is an array of {{domxref("GPUCompilationMessage")}} objects, each one containing the details of an individual compilation message.
## Examples
In the example below, we have deliberately left a parenthesis out of a function declaration in our shader code:
```js
const shaders = `
struct VertexOut {
@builtin(position) position : vec4f,
@location(0) color : vec4f
}
@vertex
fn vertex_main(@location(0) position: vec4f,
@location(1) color: vec4f -> VertexOut
{
var output : VertexOut;
output.position = position;
output.color = color;
return output;
}
@fragment
fn fragment_main(fragData: VertexOut) -> @location(0) vec4f
{
return fragData.color;
}
`;
```
When we compile the shader module, we use `getCompilationInfo()` to grab some information about the resulting error:
```js
async function init() {
// ...
const shaderModule = device.createShaderModule({
code: shaders,
});
const shaderInfo = await shaderModule.getCompilationInfo();
const firstMessage = shaderInfo.messages[0];
console.log(firstMessage.lineNum); // 9
console.log(firstMessage.message); // "expected ')' for function declaration"
console.log(firstMessage.type); // "error"
// ...
}
```
## 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/gpushadermodule | data/mdn-content/files/en-us/web/api/gpushadermodule/label/index.md | ---
title: "GPUShaderModule: label property"
short-title: label
slug: Web/API/GPUShaderModule/label
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GPUShaderModule.label
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`label`** property of the
{{domxref("GPUShaderModule")}} 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.createShaderModule()")}} call, or you can get and set it directly on the `GPUShaderModule` 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 `GPUShaderModule.label`:
```js
// ...
const shaderModule = device.createShaderModule({
code: shaders,
});
shaderModule.label = "myshader";
console.log(shaderModule.label); // "myshader"
```
Setting a label via the originating {{domxref("GPUDevice.createShaderModule()")}} call, and then getting it via `GPUShaderModule.label`:
```js
// ...
const shaderModule = device.createShaderModule({
code: shaders,
label: "myshader",
});
console.log(shaderModule.label); // "myshader"
```
## 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/setinterval/index.md | ---
title: setInterval() global function
short-title: setInterval()
slug: Web/API/setInterval
page-type: web-api-global-function
browser-compat: api.setInterval
---
{{APIRef("HTML DOM")}}{{AvailableInWorkers}}
The **`setInterval()`** method, offered on the {{domxref("Window")}} and {{domxref("WorkerGlobalScope")}} interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.
This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling {{domxref("clearInterval", "clearInterval()")}}.
## Syntax
```js-nolint
setInterval(code)
setInterval(code, delay)
setInterval(func)
setInterval(func, delay)
setInterval(func, delay, arg1)
setInterval(func, delay, arg1, arg2)
setInterval(func, delay, arg1, arg2, /* …, */ argN)
```
### Parameters
- `func`
- : A {{jsxref("function")}} to be executed every `delay` milliseconds. The first execution happens after `delay` milliseconds.
- `code`
- : An optional syntax allows you to include a string instead of a function, which is compiled and executed every `delay` milliseconds.
This syntax is _not recommended_ for the same reasons that make using {{jsxref("Global_Objects/eval", "eval()")}} a security risk.
- `delay` {{optional_inline}}
- : The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. Defaults to 0 if not specified.
See [Delay restrictions](#delay_restrictions) below for details on the permitted range of `delay` values.
- `arg1`, …,`argN` {{optional_inline}}
- : Additional arguments which are passed through to the function specified by _func_ once the timer expires.
### Return value
The returned `intervalID` is a numeric, non-zero value which identifies the timer created by the call to `setInterval()`; this value can be passed to {{domxref("clearInterval()")}} to cancel the interval.
It may be helpful to be aware that `setInterval()` and {{domxref("setTimeout()")}} share the same pool of IDs, and that `clearInterval()` and {{domxref("clearTimeout", "clearTimeout()")}} can technically be used interchangeably.
For clarity, however, you should try to always match them to avoid confusion when maintaining your code.
> **Note:** The `delay` argument is converted to a signed 32-bit integer.
> This effectively limits `delay` to 2147483647 ms, since it's specified as a signed integer in the IDL.
## Examples
### Example 1: Basic syntax
The following example demonstrates `setInterval()`'s basic syntax.
```js
const intervalID = setInterval(myCallback, 500, "Parameter 1", "Parameter 2");
function myCallback(a, b) {
// Your code here
// Parameters are purely optional.
console.log(a);
console.log(b);
}
```
### Example 2: Alternating two colors
The following example calls the `flashtext()` function once a second until
the Stop button is pressed.
#### HTML
```html
<div id="my_box">
<h3>Hello World</h3>
</div>
<button id="start">Start</button>
<button id="stop">Stop</button>
```
#### CSS
```css
.go {
color: green;
}
.stop {
color: red;
}
```
#### JavaScript
```js
// variable to store our intervalID
let nIntervId;
function changeColor() {
// check if an interval has already been set up
if (!nIntervId) {
nIntervId = setInterval(flashText, 1000);
}
}
function flashText() {
const oElem = document.getElementById("my_box");
oElem.className = oElem.className === "go" ? "stop" : "go";
}
function stopTextColor() {
clearInterval(nIntervId);
// release our intervalID from the variable
nIntervId = null;
}
document.getElementById("start").addEventListener("click", changeColor);
document.getElementById("stop").addEventListener("click", stopTextColor);
```
#### Result
{{EmbedLiveSample("Example_2:_Alternating_two_colors")}}
See also: [`clearInterval()`](/en-US/docs/Web/API/clearInterval).
## The "this" problem
When you pass a method to `setInterval()` or any other function, it is invoked with the wrong [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this) value.
This problem is explained in detail in the [JavaScript reference](/en-US/docs/Web/JavaScript/Reference/Operators/this#callbacks).
### Explanation
Code executed by `setInterval()` runs in a separate execution context than
the function from which it was called. As a consequence, the [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this)
keyword for the called function is set to the `window` (or
`global`) object, it is not the same as the `this` value for the
function that called `setTimeout`. See the following example (which uses
`setTimeout()` instead of `setInterval()` – the problem, in fact,
is the same for both timers):
```js
myArray = ["zero", "one", "two"];
myArray.myMethod = function (sProperty) {
alert(arguments.length > 0 ? this[sProperty] : this);
};
myArray.myMethod(); // prints "zero,one,two"
myArray.myMethod(1); // prints "one"
setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second
setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1,5 seconds
// Passing the 'this' object with .call won't work
// because this will change the value of this inside setTimeout itself
// while we want to change the value of this inside myArray.myMethod.
// In fact, it will be an error because setTimeout code expects this to be the window object:
setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
setTimeout.call(myArray, myArray.myMethod, 2500, 2); // same error
```
As you can see there are no ways to pass the `this` object to the callback
function in the legacy JavaScript.
### A possible solution
All modern JavaScript runtimes (in browsers and elsewhere) support [arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), with lexical `this` — allowing us to write `setInterval(() => this.myMethod())` if we're inside the `myArray` method.
If you need to support IE, use the [`Function.prototype.bind()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) method, which lets you specify the value that should be used as `this` for all calls to a given function. That lets you easily bypass problems where it's unclear what `this` will be, depending on the context from which your function was called.
## Usage notes
The `setInterval()` function is commonly used to set a delay for functions
that are executed again and again, such as animations. You can cancel the interval using
{{domxref("clearInterval()")}}.
If you wish to have your function called _once_ after the specified delay, use
{{domxref("setTimeout()")}}.
### Delay restrictions
It's possible for intervals to be nested; that is, the callback for
`setInterval()` can in turn call `setInterval()` to start another
interval running, even though the first one is still going. To mitigate the potential
impact this can have on performance, once intervals are nested beyond five levels deep,
the browser will automatically enforce a 4 ms minimum value for the interval. Attempts
to specify a value less than 4 ms in deeply-nested calls to `setInterval()`
will be pinned to 4 ms.
Browsers may enforce even more stringent minimum values for the interval under some
circumstances, although these should not be common. Note also that the actual amount of
time that elapses between calls to the callback may be longer than the given
`delay`; see
[Reasons for delays longer than specified](/en-US/docs/Web/API/setTimeout#reasons_for_delays_longer_than_specified) for examples.
### Ensure that execution duration is shorter than interval frequency
If there is a possibility that your logic could take longer to execute than the
interval time, it is recommended that you recursively call a named function using
{{domxref("setTimeout()")}}. For example, if
using `setInterval()` to poll a remote server every 5 seconds, network
latency, an unresponsive server, and a host of other issues could prevent the request
from completing in its allotted time. As such, you may find yourself with queued up XHR
requests that won't necessarily return in order.
In these cases, a recursive `setTimeout()` pattern is preferred:
```js
(function loop() {
setTimeout(() => {
// Your logic here
loop();
}, delay);
})();
```
In the above snippet, a named function `loop()` is declared and is
immediately executed. `loop()` is recursively called inside
`setTimeout()` after the logic has completed executing. While this pattern
does not guarantee execution on a fixed interval, it does guarantee that the previous
interval has completed before recursing.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `setInterval` which allows passing arguments to the callback in `core-js`](https://github.com/zloirock/core-js#settimeout-and-setinterval)
- {{domxref("setTimeout()")}}
- {{domxref("clearTimeout()")}}
- {{domxref("clearInterval()")}}
- {{domxref("window.requestAnimationFrame()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/service_worker_api/index.md | ---
title: Service Worker API
slug: Web/API/Service_Worker_API
page-type: web-api-overview
spec-urls: https://w3c.github.io/ServiceWorker/
---
{{DefaultAPISidebar("Service Workers API")}}
Service workers essentially act as proxy servers that sit between web applications, the browser, and the network (when available). They are intended, among other things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. They will also allow access to push notifications and background sync APIs.
## Service worker concepts and usage
A service worker is an event-driven [worker](/en-US/docs/Web/API/Worker) registered against an origin and a path. It takes the form of a JavaScript file that can control the web-page/site that it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available).
A service worker is run in a worker context: it therefore has no DOM access, and runs on a different thread to the main JavaScript that powers your app, so it is non-blocking. It is designed to be fully async; as a consequence, APIs such as synchronous [XHR](/en-US/docs/Web/API/XMLHttpRequest) and [Web Storage](/en-US/docs/Web/API/Web_Storage_API) can't be used inside a service worker.
Service workers can't import JavaScript module dynamically, and [`import()`](/en-US/docs/Web/JavaScript/Reference/Operators/import#browser_compatibility) will throw if it is called in a service worker global scope.
Static import using the [`import`](/en-US/docs/Web/JavaScript/Reference/Statements/import) statement is allowed.
Service workers only run over HTTPS, for security reasons. Most significantly, HTTP connections are susceptible to malicious code injection by {{Glossary("MitM", "man in the middle")}} attacks, and such attacks could be worse if allowed access to these powerful APIs. In Firefox, service worker APIs are also hidden and cannot be used when the user is in [private browsing mode](https://support.mozilla.org/en-US/kb/private-browsing-use-firefox-without-history).
> **Note:** On Firefox, for testing you can run service workers over HTTP (insecurely); simply check the **Enable Service Workers over HTTP (when toolbox is open)** option in the Firefox Devtools options/gear menu.
> **Note:** Unlike previous attempts in this area such as [AppCache](https://alistapart.com/article/application-cache-is-a-douchebag/), service workers don't make assumptions about what you are trying to do, but then break when those assumptions are not exactly right. Instead, service workers give you much more granular control.
> **Note:** Service workers make heavy use of [promises](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), as generally they will wait for responses to come through, after which they will respond with a success or failure action. The promises architecture is ideal for this.
### Registration
A service worker is first registered using the {{DOMxRef("ServiceWorkerContainer.register()")}} method. If successful, your service worker will be downloaded to the client and attempt installation/activation (see below) for URLs accessed by the user inside the whole origin, or inside a subset specified by you.
### Download, install and activate
At this point, your service worker will observe the following lifecycle:
1. Download
2. Install
3. Activate
The service worker is immediately downloaded when a user first accesses a service worker–controlled site/page.
After that, it is updated when:
- A navigation to an in-scope page occurs.
- An event is fired on the service worker and it hasn't been downloaded in the last 24 hours.
Installation is attempted when the downloaded file is found to be new — either different to an existing service worker (byte-wise compared), or the first service worker encountered for this page/site.
If this is the first time a service worker has been made available, installation is attempted, then after a successful installation, it is activated.
If there is an existing service worker available, the new version is installed in the background, but not yet activated — at this point it is called the _worker in waiting_. It is only activated when there are no longer any pages loaded that are still using the old service worker. As soon as there are no more pages to be loaded, the new service worker activates (becoming the _active worker_). Activation can happen sooner using {{DOMxRef("ServiceWorkerGlobalScope.skipWaiting()")}} and existing pages can be claimed by the active worker using {{DOMxRef("Clients.claim()")}}.
You can listen for the {{domxref("ServiceWorkerGlobalScope/install_event", "install")}} event; a standard action is to prepare your service worker for usage when this fires, for example by creating a cache using the built in storage API, and placing assets inside it that you'll want for running your app offline.
There is also an {{domxref("ServiceWorkerGlobalScope/activate_event", "activate")}} event. The point where this event fires is generally a good time to clean up old caches and other things associated with the previous version of your service worker.
Your service worker can respond to requests using the {{DOMxRef("FetchEvent")}} event. You can modify the response to these requests in any way you want, using the {{DOMxRef("FetchEvent.respondWith()")}} method.
> **Note:** Because `install`/`activate` events could take a while to complete, the service worker spec provides a {{domxref("ExtendableEvent.waitUntil", "waitUntil()")}} method. Once it is called on `install` or `activate` events with a promise, functional events such as `fetch` and `push` will wait until the promise is successfully resolved.
For a complete tutorial to show how to build up your first basic example, read [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers).
## Other use case ideas
Service workers are also intended to be used for such things as:
- Background data synchronization.
- Responding to resource requests from other origins.
- Receiving centralized updates to expensive-to-calculate data such as geolocation or gyroscope, so multiple pages can make use of one set of data.
- Client-side compiling and dependency management of CoffeeScript, less, CJS/AMD modules, etc. for development purposes.
- Hooks for background services.
- Custom templating based on certain URL patterns.
- Performance enhancements, for example pre-fetching resources that the user is likely to need in the near future, such as the next few pictures in a photo album.
- API mocking.
In the future, service workers will be able to do a number of other useful things for the web platform that will bring it closer towards native app viability. Interestingly, other specifications can and will start to make use of the service worker context, for example:
- [Background synchronization](https://github.com/WICG/background-sync): Start up a service worker even when no users are at the site, so caches can be updated, etc.
- [Reacting to push messages](/en-US/docs/Web/API/Push_API): Start up a service worker to send users a message to tell them new content is available.
- Reacting to a particular time & date.
- Entering a geo-fence.
## Interfaces
- {{DOMxRef("Cache")}}
- : Represents the storage for {{DOMxRef("Request")}} / {{DOMxRef("Response")}} object pairs that are cached as part of the {{DOMxRef("ServiceWorker")}} life cycle.
- {{DOMxRef("CacheStorage")}}
- : Represents the storage for {{DOMxRef("Cache")}} objects. It provides a master directory of all the named caches that a {{DOMxRef("ServiceWorker")}} can access, and maintains a mapping of string names to corresponding {{DOMxRef("Cache")}} objects.
- {{DOMxRef("Client")}}
- : Represents the scope of a service worker client. A service worker client is either a document in a browser context or a {{DOMxRef("SharedWorker")}}, which is controlled by an active worker.
- {{DOMxRef("Clients")}}
- : Represents a container for a list of {{DOMxRef("Client")}} objects; the main way to access the active service worker clients at the current origin.
- {{DOMxRef("ExtendableEvent")}}
- : Extends the lifetime of the `install` and `activate` events dispatched on the {{DOMxRef("ServiceWorkerGlobalScope")}}, as part of the service worker lifecycle. This ensures that any functional events (like {{DOMxRef("FetchEvent")}}) are not dispatched to the {{DOMxRef("ServiceWorker")}}, until it upgrades database schemas, and deletes outdated cache entries, etc.
- {{DOMxRef("ExtendableMessageEvent")}}
- : The event object of a {{domxref("ServiceWorkerGlobalScope/message_event", "message")}} event fired on a service worker (when a channel message is received on the {{DOMxRef("ServiceWorkerGlobalScope")}} from another context) — extends the lifetime of such events.
- {{DOMxRef("FetchEvent")}}
- : The parameter passed into the {{DOMxRef("ServiceWorkerGlobalScope.fetch_event", "onfetch")}} handler, `FetchEvent` represents a fetch action that is dispatched on the {{DOMxRef("ServiceWorkerGlobalScope")}} of a {{DOMxRef("ServiceWorker")}}. It contains information about the request and resulting response, and provides the {{DOMxRef("FetchEvent.respondWith", "FetchEvent.respondWith()")}} method, which allows us to provide an arbitrary response back to the controlled page.
- {{DOMxRef("InstallEvent")}} {{Deprecated_Inline}} {{Non-standard_Inline}}
- : The parameter passed into the {{DOMxRef("ServiceWorkerGlobalScope.install_event", "oninstall")}} handler, the `InstallEvent` interface represents an install action that is dispatched on the {{DOMxRef("ServiceWorkerGlobalScope")}} of a {{DOMxRef("ServiceWorker")}}. As a child of {{DOMxRef("ExtendableEvent")}}, it ensures that functional events such as {{DOMxRef("FetchEvent")}} are not dispatched during installation.
- {{DOMxRef("NavigationPreloadManager")}}
- : Provides methods for managing the preloading of resources with a service worker.
- {{DOMxRef("ServiceWorker")}}
- : Represents a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same `ServiceWorker` object.
- {{DOMxRef("ServiceWorkerContainer")}}
- : Provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister, and update service workers, and access the state of service workers and their registrations.
- {{DOMxRef("ServiceWorkerGlobalScope")}}
- : Represents the global execution context of a service worker.
- {{DOMxRef("ServiceWorkerRegistration")}}
- : Represents a service worker registration.
- {{DOMxRef("WindowClient")}}
- : Represents the scope of a service worker client that is a document in a browser context, controlled by an active worker. This is a special type of {{DOMxRef("Client")}} object, with some additional methods and properties available.
### Extensions to other interfaces
- {{DOMxRef("caches")}}
- : Returns the {{domxref("CacheStorage")}} object associated with the current context.
- {{DOMxRef("Navigator.serviceWorker")}}
- : Returns a {{DOMxRef("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{DOMxRef("ServiceWorker")}} objects for the [associated document](https://html.spec.whatwg.org/multipage/browsers.html#concept-document-window).
- {{DOMxRef("WorkerNavigator.serviceWorker")}}
- : Returns a {{DOMxRef("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{DOMxRef("ServiceWorker")}} objects for the [associated document](https://html.spec.whatwg.org/multipage/browsers.html#concept-document-window).
## Specifications
{{Specifications}}
## See also
- [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers)
- [Service Worker Lifecycle](https://web.dev/articles/service-worker-lifecycle)
- [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker)
- Web APIs that are related to the Service Worker API:
- {{domxref("Background Fetch API", "", "", "nocode")}}
- {{domxref("Background Synchronization API", "", "", "nocode")}}
- {{domxref("Content Index API", "", "", "nocode")}}
- {{domxref("Cookie Store API", "", "", "nocode")}}
- {{domxref("Notifications API", "", "", "nocode")}}
- {{domxref("Payment Handler API", "", "", "nocode")}}
- {{domxref("Push API", "", "", "nocode")}}
- {{domxref("Web Periodic Background Synchronization API", "", "", "nocode")}}
| 0 |
data/mdn-content/files/en-us/web/api/service_worker_api | data/mdn-content/files/en-us/web/api/service_worker_api/using_service_workers/sw-lifecycle.svg | <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
width="1130"
height="1518"
viewBox="-10.5 -51 1232.555 1655.7686"
version="1.1"
id="svg434"
sodipodi:docname="sw-lifecycle.svg"
inkscape:version="1.2.1 (9c6d41e410, 2022-07-14)"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:xhtml="http://www.w3.org/1999/xhtml">
<defs
id="defs438" />
<sodipodi:namedview
id="namedview436"
pagecolor="#ffffff"
bordercolor="#000000"
borderopacity="0.25"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
showgrid="false"
inkscape:zoom="1.1264822"
inkscape:cx="549.05439"
inkscape:cy="908.58071"
inkscape:window-width="3200"
inkscape:window-height="1771"
inkscape:window-x="-9"
inkscape:window-y="-9"
inkscape:window-maximized="1"
inkscape:current-layer="svg434"
showguides="true">
<sodipodi:guide
position="262.40557,1039.9399"
orientation="1,0"
id="guide1320"
inkscape:locked="false" />
</sodipodi:namedview>
<g
font-family="Helvetica"
pointer-events="none"
text-anchor="middle"
font-size="14px"
id="g6">
<text
x="1005.5"
y="361.5"
id="text2">Service worker fetched</text>
<text
x="1005.5"
y="378.5"
id="text4">and registered</text>
</g>
<path
d="M 961,344 V 224 h 60.46 l 26.14,30.48 V 344 Z m 4.9,-5.69 h 76.8 V 260.2 h -24.51 V 229.72 H 965.9 Z"
pointer-events="none"
id="path8" />
<path
d="m 978.11,332.5 v -55 h 52.38 v 55 z"
pointer-events="none"
id="path10" />
<path
d="m 978.11,332.5 v -2.48 h 52.38 v 2.48 z"
fill-opacity="0.3"
pointer-events="none"
id="path12" />
<path
d="m 1004.36,311.42 c -4.32,0 -7.71,-3.44 -7.71,-7.65 0,-4.54 3.78,-7.71 7.48,-7.71 4.95,0 7.81,4.07 7.81,7.58 0,4.51 -3.57,7.78 -7.58,7.78 z m 0.16,5.99 c 7,0 13.42,-5.9 13.42,-13.85 0,-7.17 -5.85,-13.54 -13.86,-13.54 -6.57,0 -13.42,5.47 -13.42,13.81 0,7.18 5.73,13.58 13.86,13.58 z m -13.13,5.39 -6.03,-6.08 2.45,-2.48 c -1.19,-1.93 -2.1,-4.02 -2.57,-6.21 h -3.47 v -8.55 l 3.47,-0.02 c 0.46,-2.2 1.42,-4.38 2.57,-6.22 l -2.45,-2.44 6.03,-6.06 2.47,2.46 c 2.03,-1.27 4.1,-2.11 6.18,-2.57 v -3.49 h 8.52 v 3.51 c 2.48,0.55 4.5,1.51 6.18,2.57 l 2.47,-2.47 6.04,6.03 -2.45,2.46 c 1.35,2.15 2.12,4.32 2.54,6.22 h 3.47 v 8.59 h -3.47 c -0.57,2.49 -1.49,4.51 -2.57,6.2 l 2.47,2.47 -6.01,6.06 -2.47,-2.47 c -1.76,1.08 -3.69,2.02 -6.17,2.56 l -0.02,3.51 h -8.53 v -3.48 c -2.31,-0.53 -4.37,-1.42 -6.18,-2.59 z"
fill="#ffffff"
pointer-events="none"
id="path14" />
<switch
transform="translate(-0.5,-0.5)"
id="switch18">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:58px;height:1px;padding-top:254px;margin-left:962px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:19px;font-family:Courier New;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">v1</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="991"
y="260"
font-family="'Courier New'"
font-size="19px"
text-anchor="middle"
id="text16">v1</text>
</switch>
<path
d="m 241,14.4 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 L 338.5,22.4 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 H 253.25 C 246.63,109.96 241.39,104.16 241,96.95 Z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 H 314 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 L 283.98,83.5 Z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z"
fill="#b3b3b3"
pointer-events="none"
id="path20" />
<path
d="m 371,14.4 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 L 468.5,22.4 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 H 383.25 C 376.63,109.96 371.39,104.16 371,96.95 Z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 H 444 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 L 413.98,83.5 Z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z"
pointer-events="none"
id="path22" />
<path
d="M 445.35,120.5 421,96.13 l 9.74,-9.7 12.48,12.52 C 449.14,93 455.24,87.03 463.04,80.94 470.95,74.8 479.39,70.5 483.5,70.7 c -7.8,6.56 -15.57,14.73 -22.42,23.68 -7.22,9.22 -12.41,18.17 -15.73,26.12 z"
fill="#2d9c5e"
pointer-events="none"
id="path24" />
<path
d="m 501,14.4 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 L 598.5,22.4 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 H 513.25 C 506.63,109.96 501.39,104.16 501,96.95 Z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 H 574 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 L 543.98,83.5 Z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z"
pointer-events="none"
id="path26" />
<path
d="M 575.35,120.5 551,96.13 l 9.74,-9.7 12.48,12.52 C 579.14,93 585.24,87.03 593.04,80.94 600.95,74.8 609.39,70.5 613.5,70.7 c -7.8,6.56 -15.57,14.73 -22.42,23.68 -7.22,9.22 -12.41,18.17 -15.73,26.12 z"
fill="#2d9c5e"
pointer-events="none"
id="path28" />
<path
d="m 371,129 v 5 q 0,5 10,5 h 95 q 10,0 10,5 v 2.5 -5 q 0,-2.5 10,-2.5 h 95 q 10,0 10,-5 v -5"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path30" />
<switch
transform="translate(-0.5,-0.5)"
id="switch34">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:202px;height:1px;padding-top:164px;margin-left:385px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:14px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">Pages loaded in the browser (client)</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="486"
y="168"
font-family="Helvetica"
font-size="14px"
text-anchor="middle"
id="text32">Pages loaded in the browser (client)</text>
</switch>
<path
d="m 241,242.9 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 l 20.11,21.89 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 h -74.02 c -6.62,-0.54 -11.86,-6.34 -12.25,-13.55 z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 H 314 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 L 283.98,312 Z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z"
fill="#b3b3b3"
pointer-events="none"
id="path36" />
<path
d="m 371,242.9 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 l 20.11,21.89 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 h -74.02 c -6.62,-0.54 -11.86,-6.34 -12.25,-13.55 z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 H 444 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 L 413.98,312 Z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z"
pointer-events="none"
id="path38" />
<path
d="M 445.35,349 421,324.63 l 9.74,-9.7 12.48,12.52 c 5.92,-5.95 12.02,-11.92 19.82,-18.01 7.91,-6.14 16.35,-10.44 20.46,-10.24 -7.8,6.56 -15.57,14.73 -22.42,23.68 -7.22,9.22 -12.41,18.17 -15.73,26.12 z"
fill="#2d9c5e"
pointer-events="none"
id="path40" />
<path
d="m 501,242.9 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 l 20.11,21.89 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 h -74.02 c -6.62,-0.54 -11.86,-6.34 -12.25,-13.55 z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 H 574 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 L 543.98,312 Z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z"
pointer-events="none"
id="path42" />
<path
d="M 575.35,349 551,324.63 l 9.74,-9.7 12.48,12.52 c 5.92,-5.95 12.02,-11.92 19.82,-18.01 7.91,-6.14 16.35,-10.44 20.46,-10.24 -7.8,6.56 -15.57,14.73 -22.42,23.68 -7.22,9.22 -12.41,18.17 -15.73,26.12 z"
fill="#2d9c5e"
pointer-events="none"
id="path44" />
<path
d="m 241,359 v 5 q 0,5 10,5 h 160 q 10,0 10,5 v 2.5 -5 q 0,-2.5 10,-2.5 h 160 q 10,0 10,-5 v -5"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path46" />
<switch
transform="translate(-0.5,-0.5)"
id="switch50">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:202px;height:1px;padding-top:394px;margin-left:325px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:14px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">Scope of pages for the service worker</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="426"
y="398"
font-family="Helvetica"
font-size="14px"
text-anchor="middle"
id="text48">Scope of pages for the service worker</text>
</switch>
<path
d="M 598.5,284 H 954.63"
fill="none"
stroke="#000000"
stroke-miterlimit="10"
pointer-events="none"
id="path52" />
<path
d="m 959.88,284 -7,3.5 1.75,-3.5 -1.75,-3.5 z"
stroke="#000000"
stroke-miterlimit="10"
pointer-events="none"
id="path54" />
<switch
transform="translate(-0.5,-0.5)"
id="switch60">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:1px;height:1px;padding-top:259px;margin-left:782px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0); background-color: rgb(255 255 255);">
<xhtml:div
style="display:inline-block;font-size:14px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;background-color:#fff;white-space:nowrap">
<xhtml:font
face="Courier New">register(workerURL,{options = scope})</xhtml:font>
</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="782"
y="263"
font-family="Helvetica"
font-size="14px"
text-anchor="middle"
id="text58"><tspan
style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:'Courier New';-inkscape-font-specification:'Courier New'"
id="tspan56">register(workerURL,{options = scope})</tspan></text>
</switch>
<path
d="m 426.01,409 q 0.05,10 232.52,10 Q 891,419 891,269"
fill="none"
stroke="#000000"
stroke-miterlimit="10"
stroke-dasharray="3, 3"
pointer-events="none"
id="path62" />
<switch
transform="translate(-0.5,-0.5)"
id="switch70">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:188px;height:1px;padding-top:49px;margin-left:2px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:14px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">
<xhtml:font
style="font-size:19px">0. Initial situation, no service worker<xhtml:br />
</xhtml:font>
</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="96"
y="53"
font-family="Helvetica"
font-size="14"
text-anchor="middle"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:14px;font-family:Helvetica;-inkscape-font-specification:'Helvetica, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-anchor:middle;fill:#000000"
id="text68"><tspan
sodipodi:role="line"
id="tspan1292"
x="96"
y="53">0. Initial situation:</tspan><tspan
sodipodi:role="line"
id="tspan1294"
x="96"
y="70.5">no service worker</tspan></text>
</switch>
<switch
transform="translate(-0.5,-0.5)"
id="switch80">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:188px;height:1px;padding-top:284px;margin-left:2px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:14px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">
<xhtml:div>
<xhtml:font
style="font-size:19px">1. Registration of the</xhtml:font>
</xhtml:div>
<xhtml:div>
<xhtml:font
style="font-size:19px">first version of a service worker<xhtml:br />
</xhtml:font>
</xhtml:div>
</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="96"
y="288"
font-family="Helvetica"
font-size="14"
text-anchor="middle"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:14px;font-family:Helvetica;-inkscape-font-specification:'Helvetica, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-anchor:middle;fill:#000000"
id="text78"><tspan
sodipodi:role="line"
id="tspan1310"
x="96"
y="288">1. Registration of the</tspan><tspan
sodipodi:role="line"
id="tspan1312"
x="96"
y="305.5">first version of a</tspan><tspan
sodipodi:role="line"
id="tspan1314"
x="96"
y="323">service worker</tspan></text>
</switch>
<g
font-family="Helvetica"
pointer-events="none"
text-anchor="middle"
font-size="14px"
id="g86">
<text
x="725.5"
y="636.5"
id="text82">Service worker fetched</text>
<text
x="725.5"
y="653.5"
id="text84">and registered</text>
</g>
<path
d="M 681,619 V 499 h 60.46 l 26.14,30.48 V 619 Z m 4.9,-5.69 h 76.8 V 535.2 H 738.19 V 504.72 H 685.9 Z"
pointer-events="none"
id="path88" />
<path
d="m 698.11,607.5 v -55 h 52.38 v 55 z"
pointer-events="none"
id="path90" />
<path
d="m 698.11,607.5 v -2.48 h 52.38 v 2.48 z"
fill-opacity="0.3"
pointer-events="none"
id="path92" />
<path
d="m 724.36,586.42 c -4.32,0 -7.71,-3.44 -7.71,-7.65 0,-4.54 3.78,-7.71 7.48,-7.71 4.95,0 7.81,4.07 7.81,7.58 0,4.51 -3.57,7.78 -7.58,7.78 z m 0.16,5.99 c 7,0 13.42,-5.9 13.42,-13.85 0,-7.17 -5.85,-13.54 -13.86,-13.54 -6.57,0 -13.42,5.47 -13.42,13.81 0,7.18 5.73,13.58 13.86,13.58 z m -13.13,5.39 -6.03,-6.08 2.45,-2.48 c -1.19,-1.93 -2.1,-4.02 -2.57,-6.21 h -3.47 v -8.55 l 3.47,-0.02 c 0.46,-2.2 1.42,-4.38 2.57,-6.22 l -2.45,-2.44 6.03,-6.06 2.47,2.46 c 2.03,-1.27 4.1,-2.11 6.18,-2.57 v -3.49 h 8.52 v 3.51 c 2.48,0.55 4.5,1.51 6.18,2.57 l 2.47,-2.47 6.04,6.03 -2.45,2.46 c 1.35,2.15 2.12,4.32 2.54,6.22 h 3.47 v 8.59 h -3.47 c -0.57,2.49 -1.49,4.51 -2.57,6.2 l 2.47,2.47 -6.01,6.06 -2.47,-2.47 c -1.76,1.08 -3.69,2.02 -6.17,2.56 l -0.02,3.51 h -8.53 v -3.48 c -2.31,-0.53 -4.37,-1.42 -6.18,-2.59 z"
fill="#ffffff"
pointer-events="none"
id="path94" />
<switch
transform="translate(-0.5,-0.5)"
id="switch98">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:58px;height:1px;padding-top:524px;margin-left:682px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:19px;font-family:Courier New;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">v1</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="711"
y="530"
font-family="'Courier New'"
font-size="19px"
text-anchor="middle"
id="text96">v1</text>
</switch>
<path
d="m 241,517.9 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 l 20.11,21.89 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 h -74.02 c -6.62,-0.54 -11.86,-6.34 -12.25,-13.55 z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 H 314 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 L 283.98,587 Z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z M 371,517.9 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 l 20.11,21.89 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 h -74.02 c -6.62,-0.54 -11.86,-6.34 -12.25,-13.55 z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 H 444 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 L 413.98,587 Z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z"
pointer-events="none"
id="path100" />
<path
d="M 445.35,624 421,599.63 l 9.74,-9.7 12.48,12.52 c 5.92,-5.95 12.02,-11.92 19.82,-18.01 7.91,-6.14 16.35,-10.44 20.46,-10.24 -7.8,6.56 -15.57,14.73 -22.42,23.68 -7.22,9.22 -12.41,18.17 -15.73,26.12 z"
fill="#2d9c5e"
pointer-events="none"
id="path102" />
<path
d="m 501,517.9 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 l 20.11,21.89 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 h -74.02 c -6.62,-0.54 -11.86,-6.34 -12.25,-13.55 z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 H 574 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 L 543.98,587 Z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z"
fill="#b3b3b3"
pointer-events="none"
id="path104" />
<path
d="M 325.35,624 301,599.63 l 9.74,-9.7 12.48,12.52 c 5.92,-5.95 12.02,-11.92 19.82,-18.01 7.91,-6.14 16.35,-10.44 20.46,-10.24 -7.8,6.56 -15.57,14.73 -22.42,23.68 -7.22,9.22 -12.41,18.17 -15.73,26.12 z"
fill="#2d9c5e"
pointer-events="none"
id="path106" />
<switch
transform="translate(-0.5,-0.5)"
id="switch110">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:188px;height:1px;padding-top:559px;margin-left:2px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:14px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">
<xhtml:font
style="font-size:19px">2. Installation<xhtml:br />
</xhtml:font>
</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="96"
y="563"
font-family="Helvetica"
font-size="14px"
text-anchor="middle"
id="text108">2. Installation</text>
</switch>
<path
d="M 901,504.12 773.68,543.66"
fill="none"
stroke="#000000"
stroke-miterlimit="10"
pointer-events="none"
id="path112" />
<path
d="m 768.67,545.22 5.64,-5.42 -0.63,3.86 2.71,2.83 z"
stroke="#000000"
stroke-miterlimit="10"
pointer-events="none"
id="path114" />
<path
d="m 901,529 11,-12.57 -9.35,-8.79 9.35,-7.54 -9.35,-11.31 17.05,-19.79 14.3,16.02 -13.2,8.8 7.7,8.79 -11.55,7.54 7.15,6.91 z"
fill="#ffd966"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="6"
pointer-events="none"
id="path116" />
<switch
transform="translate(-0.5,-0.5)"
id="switch122">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe flex-start;justify-content:unsafe center;width:1px;height:1px;padding-top:536px;margin-left:918px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:19px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:nowrap">i<xhtml:font
face="Courier New">nstall</xhtml:font>
event</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="918"
y="555"
font-family="Helvetica"
font-size="19px"
text-anchor="middle"
id="text120"
style="word-spacing:3px"><tspan
style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:'Courier New';-inkscape-font-specification:'Courier New'"
id="tspan118">install</tspan> event</text>
</switch>
<path
d="m 937.5,621.5 97.99,-56.89"
fill="none"
stroke="#000000"
stroke-miterlimit="10"
pointer-events="none"
id="path124" />
<path
d="m 1040.03,561.98 -4.29,6.54 -0.25,-3.91 -3.27,-2.15 z"
stroke="#000000"
stroke-miterlimit="10"
pointer-events="none"
id="path126" />
<ellipse
cx="922.22998"
cy="620.53003"
rx="15.271"
ry="15.461"
pointer-events="none"
id="ellipse128" />
<path
d="m 926.11,643.11 -5.82,5.89 v -3.93 c -8.82,-0.33 -16.58,-6 -19.68,-14.36 -3.11,-8.36 -0.96,-17.8 5.46,-23.94 6.42,-6.13 15.84,-7.77 23.92,-4.15 -7.17,-2.98 -15.39,-1.45 -21.05,3.9 -5.66,5.36 -7.73,13.56 -5.29,21 2.44,7.44 8.94,12.76 16.64,13.63 v -3.93 z"
pointer-events="none"
id="path130" />
<ellipse
cx="922.32001"
cy="607.42999"
rx="1.483"
ry="1.257"
fill="#ffffff"
pointer-events="none"
id="ellipse132" />
<ellipse
cx="909.46997"
cy="621.27002"
rx="1.546"
ry="1.472"
fill="#ffffff"
pointer-events="none"
id="ellipse134" />
<ellipse
cx="922.67999"
cy="634.03003"
rx="1.668"
ry="1.35"
fill="#ffffff"
pointer-events="none"
id="ellipse136" />
<ellipse
cx="935.44"
cy="621.20001"
rx="1.454"
ry="1.35"
fill="#ffffff"
pointer-events="none"
id="ellipse138" />
<path
d="m 919.56,622 v -9.32 a 2.822,2.822 0 0 1 2.67,-1.94 c 1.21,0 2.28,0.78 2.67,1.94 v 6.38 l 5.09,5.15 c 0.74,1.14 0.61,2.65 -0.32,3.64 a 2.89,2.89 0 0 1 -3.56,0.54 z"
fill="#ffffff"
pointer-events="none"
id="path140" />
<switch
transform="translate(-0.5,-0.5)"
id="switch144">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe flex-start;justify-content:unsafe center;width:1px;height:1px;padding-top:656px;margin-left:918px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:19px;font-family:Courier New;color:#000;line-height:1.2;pointer-events:none;white-space:nowrap">event.waitUntil()</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="918"
y="675"
font-family="'Courier New'"
font-size="19px"
text-anchor="middle"
id="text142">event.waitUntil()</text>
</switch>
<path
d="m 767.6,574.85 125.52,45.96"
fill="none"
stroke="#000000"
stroke-miterlimit="10"
pointer-events="none"
id="path146" />
<path
d="m 898.05,622.62 -7.78,0.88 2.85,-2.69 -0.44,-3.89 z"
stroke="#000000"
stroke-miterlimit="10"
pointer-events="none"
id="path148" />
<path
d="m 1041,524 c 0,10 60,10 60,0"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path150" />
<path
d="m 1041,529 c 0,10 60,10 60,0"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path152" />
<path
d="m 1041,534 c 0,10 60,10 60,0"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path154" />
<path
d="m 1041,524 c 0,-13.33 60,-13.33 60,0 v 40 c 0,13.33 -60,13.33 -60,0 z"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path156" />
<switch
transform="translate(-0.5,-0.5)"
id="switch160">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:202px;height:1px;padding-top:614px;margin-left:970px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:14px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">Setting up caches, offline assets, etc.</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="1071"
y="618"
font-family="Helvetica"
font-size="14px"
text-anchor="middle"
id="text158">Setting up caches, offline assets</text>
</switch>
<switch
transform="translate(-0.5,-0.5)"
id="switch164">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:58px;height:1px;padding-top:554px;margin-left:1042px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:19px;font-family:Courier New;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">v1</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="1071"
y="560"
font-family="'Courier New'"
font-size="19px"
text-anchor="middle"
id="text162">v1</text>
</switch>
<g
font-family="Helvetica"
pointer-events="none"
text-anchor="middle"
font-size="14px"
id="g170">
<text
x="725.5"
y="849.5"
id="text166">Service worker installed</text>
<text
x="725.5"
y="866.5"
id="text168">but not controlling</text>
</g>
<path
d="M 681,829 V 709 h 60.46 l 26.14,30.48 V 829 Z m 4.9,-5.69 h 76.8 V 745.2 H 738.19 V 714.72 H 685.9 Z"
pointer-events="none"
id="path172" />
<path
d="m 698.11,817.5 v -55 h 52.38 v 55 z"
pointer-events="none"
id="path174" />
<path
d="m 698.11,817.5 v -2.48 h 52.38 v 2.48 z"
fill-opacity="0.3"
pointer-events="none"
id="path176" />
<path
d="m 724.36,796.42 c -4.32,0 -7.71,-3.44 -7.71,-7.65 0,-4.54 3.78,-7.71 7.48,-7.71 4.95,0 7.81,4.07 7.81,7.58 0,4.51 -3.57,7.78 -7.58,7.78 z m 0.16,5.99 c 7,0 13.42,-5.9 13.42,-13.85 0,-7.17 -5.85,-13.54 -13.86,-13.54 -6.57,0 -13.42,5.47 -13.42,13.81 0,7.18 5.73,13.58 13.86,13.58 z m -13.13,5.39 -6.03,-6.08 2.45,-2.48 c -1.19,-1.93 -2.1,-4.02 -2.57,-6.21 h -3.47 v -8.55 l 3.47,-0.02 c 0.46,-2.2 1.42,-4.38 2.57,-6.22 l -2.45,-2.44 6.03,-6.06 2.47,2.46 c 2.03,-1.27 4.1,-2.11 6.18,-2.57 v -3.49 h 8.52 v 3.51 c 2.48,0.55 4.5,1.51 6.18,2.57 l 2.47,-2.47 6.04,6.03 -2.45,2.46 c 1.35,2.15 2.12,4.32 2.54,6.22 h 3.47 v 8.59 h -3.47 c -0.57,2.49 -1.49,4.51 -2.57,6.2 l 2.47,2.47 -6.01,6.06 -2.47,-2.47 c -1.76,1.08 -3.69,2.02 -6.17,2.56 l -0.02,3.51 h -8.53 v -3.48 c -2.31,-0.53 -4.37,-1.42 -6.18,-2.59 z"
fill="#ffffff"
pointer-events="none"
id="path178" />
<switch
transform="translate(-0.5,-0.5)"
id="switch182">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:58px;height:1px;padding-top:734px;margin-left:682px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:19px;font-family:Courier New;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">v1</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="711"
y="740"
font-family="'Courier New'"
font-size="19px"
text-anchor="middle"
id="text180">v1</text>
</switch>
<path
d="m 241,727.9 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 l 20.11,21.89 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 h -74.02 c -6.62,-0.54 -11.86,-6.34 -12.25,-13.55 z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 H 314 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 L 283.98,797 Z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z M 371,727.9 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 l 20.11,21.89 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 h -74.02 c -6.62,-0.54 -11.86,-6.34 -12.25,-13.55 z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 H 444 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 L 413.98,797 Z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z M 501,727.9 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 l 20.11,21.89 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 h -74.02 c -6.62,-0.54 -11.86,-6.34 -12.25,-13.55 z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 H 574 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 L 543.98,797 Z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z"
fill="#b3b3b3"
pointer-events="none"
id="path184" />
<switch
transform="translate(-0.5,-0.5)"
id="switch192">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:188px;height:1px;padding-top:769px;margin-left:2px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:14px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">
<xhtml:font
style="font-size:19px">3. Waiting for clients to be closed<xhtml:br />
</xhtml:font>
</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="96"
y="773"
font-family="Helvetica"
font-size="14"
text-anchor="middle"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:14px;font-family:Helvetica;-inkscape-font-specification:'Helvetica, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-anchor:middle;fill:#000000"
id="text190"><tspan
sodipodi:role="line"
id="tspan1306"
x="96"
y="773">3. Waiting for clients</tspan><tspan
sodipodi:role="line"
id="tspan1308"
x="96"
y="790.5">to be closed</tspan></text>
</switch>
<g
font-family="Helvetica"
pointer-events="none"
text-anchor="middle"
font-size="14px"
id="g198">
<text
x="725.5"
y="1059.5"
id="text194">Service worker installed</text>
<text
x="725.5"
y="1076.5"
id="text196">but not controlling</text>
</g>
<path
d="M 681,1039 V 919 h 60.46 l 26.14,30.48 V 1039 Z m 4.9,-5.69 h 76.8 V 955.2 H 738.19 V 924.72 H 685.9 Z"
pointer-events="none"
id="path200" />
<path
d="m 698.11,1027.5 v -55 h 52.38 v 55 z"
pointer-events="none"
id="path202" />
<path
d="m 698.11,1027.5 v -2.48 h 52.38 v 2.48 z"
fill-opacity="0.3"
pointer-events="none"
id="path204" />
<path
d="m 724.36,1006.42 c -4.32,0 -7.71,-3.44 -7.71,-7.65 0,-4.54 3.78,-7.71 7.48,-7.71 4.95,0 7.81,4.07 7.81,7.58 0,4.51 -3.57,7.78 -7.58,7.78 z m 0.16,5.99 c 7,0 13.42,-5.9 13.42,-13.85 0,-7.17 -5.85,-13.54 -13.86,-13.54 -6.57,0 -13.42,5.47 -13.42,13.81 0,7.18 5.73,13.58 13.86,13.58 z m -13.13,5.39 -6.03,-6.08 2.45,-2.48 c -1.19,-1.93 -2.1,-4.02 -2.57,-6.21 h -3.47 v -8.55 l 3.47,-0.02 c 0.46,-2.2 1.42,-4.38 2.57,-6.22 l -2.45,-2.44 6.03,-6.06 2.47,2.46 c 2.03,-1.27 4.1,-2.11 6.18,-2.57 v -3.49 h 8.52 v 3.51 c 2.48,0.55 4.5,1.51 6.18,2.57 l 2.47,-2.47 6.04,6.03 -2.45,2.46 c 1.35,2.15 2.12,4.32 2.54,6.22 h 3.47 v 8.59 h -3.47 c -0.57,2.49 -1.49,4.51 -2.57,6.2 l 2.47,2.47 -6.01,6.06 -2.47,-2.47 c -1.76,1.08 -3.69,2.02 -6.17,2.56 l -0.02,3.51 h -8.53 v -3.48 c -2.31,-0.53 -4.37,-1.42 -6.18,-2.59 z"
fill="#ffffff"
pointer-events="none"
id="path206" />
<switch
transform="translate(-0.5,-0.5)"
id="switch210">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:58px;height:1px;padding-top:944px;margin-left:682px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:19px;font-family:Courier New;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">v1</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="711"
y="950"
font-family="'Courier New'"
font-size="19px"
text-anchor="middle"
id="text208">v1</text>
</switch>
<path
d="m 241,937.9 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 l 20.11,21.89 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 h -74.02 c -6.62,-0.54 -11.86,-6.34 -12.25,-13.55 z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 H 314 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 L 283.98,1007 Z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z M 371,937.9 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 l 20.11,21.89 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 h -74.02 c -6.62,-0.54 -11.86,-6.34 -12.25,-13.55 z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 H 444 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 L 413.98,1007 Z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z M 501,937.9 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 l 20.11,21.89 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 h -74.02 c -6.62,-0.54 -11.86,-6.34 -12.25,-13.55 z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 H 574 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 L 543.98,1007 Z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z"
fill="#b3b3b3"
pointer-events="none"
id="path212" />
<switch
transform="translate(-0.5,-0.5)"
id="switch216">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:188px;height:1px;padding-top:979px;margin-left:2px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:14px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">
<xhtml:font
style="font-size:19px">4. Activation<xhtml:br />
</xhtml:font>
</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="96"
y="983"
font-family="Helvetica"
font-size="14px"
text-anchor="middle"
id="text214">4. Activation</text>
</switch>
<path
d="M 901,937.84 773.8,967.47"
fill="none"
stroke="#000000"
stroke-miterlimit="10"
pointer-events="none"
id="path218" />
<path
d="m 768.69,968.66 6.02,-5 -0.91,3.81 2.5,3.01 z"
stroke="#000000"
stroke-miterlimit="10"
pointer-events="none"
id="path220" />
<path
d="m 901,964 11,-12.57 -9.35,-8.79 9.35,-7.54 -9.35,-11.31 17.05,-19.79 14.3,16.02 -13.2,8.8 7.7,8.79 -11.55,7.54 7.15,6.91 z"
fill="#ffd966"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="6"
pointer-events="none"
id="path222" />
<switch
transform="translate(-0.5,-0.5)"
id="switch228">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe flex-start;justify-content:unsafe center;width:1px;height:1px;padding-top:971px;margin-left:918px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:19px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:nowrap"><xhtml:font
face="Courier New">activate</xhtml:font>
event</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="918"
y="990"
font-family="Helvetica"
font-size="19px"
text-anchor="middle"
id="text226"
style="word-spacing:6px"><tspan
style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:'Courier New';-inkscape-font-specification:'Courier New'"
id="tspan224">activate</tspan> event</text>
</switch>
<switch
transform="translate(-0.5,-0.5)"
id="switch236">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:202px;height:1px;padding-top:1024px;margin-left:817px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:14px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">Finishing setup, cleaning old resources for previous versions</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="918"
y="1028"
font-family="Helvetica"
font-size="14"
text-anchor="middle"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:14px;font-family:Helvetica;-inkscape-font-specification:'Helvetica, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-anchor:middle;fill:#000000"
id="text234"><tspan
sodipodi:role="line"
id="tspan1322"
x="918"
y="1028">Finishing setup, cleaning</tspan><tspan
sodipodi:role="line"
id="tspan1324"
x="918"
y="1045.5">old resources for previous versions</tspan></text>
</switch>
<g
font-family="Helvetica"
pointer-events="none"
text-anchor="middle"
font-size="14px"
id="g244">
<text
x="855.5"
y="1264.5"
id="text238">Service worker</text>
<text
x="855.5"
y="1281.5"
id="text240">controlling documents</text>
<text
x="855.5"
y="1298.5"
id="text242">in its scope</text>
</g>
<path
d="m 811,1234 v -120 h 60.46 l 26.14,30.48 V 1234 Z m 4.9,-5.69 h 76.8 v -78.11 h -24.51 v -30.48 H 815.9 Z"
pointer-events="none"
id="path246" />
<path
d="m 828.11,1222.5 v -55 h 52.38 v 55 z"
pointer-events="none"
id="path248" />
<path
d="m 828.11,1222.5 v -2.48 h 52.38 v 2.48 z"
fill-opacity="0.3"
pointer-events="none"
id="path250" />
<path
d="m 854.36,1201.42 c -4.32,0 -7.71,-3.44 -7.71,-7.65 0,-4.54 3.78,-7.71 7.48,-7.71 4.95,0 7.81,4.07 7.81,7.58 0,4.51 -3.57,7.78 -7.58,7.78 z m 0.16,5.99 c 7,0 13.42,-5.9 13.42,-13.85 0,-7.17 -5.85,-13.54 -13.86,-13.54 -6.57,0 -13.42,5.47 -13.42,13.81 0,7.18 5.73,13.58 13.86,13.58 z m -13.13,5.39 -6.03,-6.08 2.45,-2.48 c -1.19,-1.93 -2.1,-4.02 -2.57,-6.21 h -3.47 v -8.55 l 3.47,-0.02 c 0.46,-2.2 1.42,-4.38 2.57,-6.22 l -2.45,-2.44 6.03,-6.06 2.47,2.46 c 2.03,-1.27 4.1,-2.11 6.18,-2.57 v -3.49 h 8.52 v 3.51 c 2.48,0.55 4.5,1.51 6.18,2.57 l 2.47,-2.47 6.04,6.03 -2.45,2.46 c 1.35,2.15 2.12,4.32 2.54,6.22 h 3.47 v 8.59 h -3.47 c -0.57,2.49 -1.49,4.51 -2.57,6.2 l 2.47,2.47 -6.01,6.06 -2.47,-2.47 c -1.76,1.08 -3.69,2.02 -6.17,2.56 l -0.02,3.51 h -8.53 v -3.48 c -2.31,-0.53 -4.37,-1.42 -6.18,-2.59 z"
fill="#ffffff"
pointer-events="none"
id="path252" />
<switch
transform="translate(-0.5,-0.5)"
id="switch256">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:58px;height:1px;padding-top:1139px;margin-left:812px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:19px;font-family:Courier New;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">v1</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="841"
y="1145"
font-family="'Courier New'"
font-size="19px"
text-anchor="middle"
id="text254">v1</text>
</switch>
<path
d="m 241,1132.9 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 l 20.11,21.89 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 h -74.02 c -6.62,-0.54 -11.86,-6.34 -12.25,-13.55 z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 H 314 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 L 283.98,1202 Z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z M 371,1132.9 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 l 20.11,21.89 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 h -74.02 c -6.62,-0.54 -11.86,-6.34 -12.25,-13.55 z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 H 444 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 L 413.98,1202 Z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z"
fill="#b3b3b3"
pointer-events="none"
id="path258" />
<path
d="m 501,1132.9 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 l 20.11,21.89 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 h -74.02 c -6.62,-0.54 -11.86,-6.34 -12.25,-13.55 z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 H 574 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 L 543.98,1202 Z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z"
pointer-events="none"
id="path260" />
<path
d="m 575.35,1239 -24.35,-24.37 9.74,-9.7 12.48,12.52 c 5.92,-5.95 12.02,-11.92 19.82,-18.01 7.91,-6.14 16.35,-10.44 20.46,-10.24 -7.8,6.56 -15.57,14.73 -22.42,23.68 -7.22,9.22 -12.41,18.17 -15.73,26.12 z"
fill="#2d9c5e"
pointer-events="none"
id="path262" />
<switch
transform="translate(-0.5,-0.5)"
id="switch266">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:188px;height:1px;padding-top:1174px;margin-left:2px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:14px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">
<xhtml:font
style="font-size:19px">5. Activated<xhtml:br />
</xhtml:font>
</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="96"
y="1178"
font-family="Helvetica"
font-size="14px"
text-anchor="middle"
id="text264">5. Activated</text>
</switch>
<path
d="m 731.58,1175.2 73.05,-0.71"
fill="none"
stroke="#000000"
stroke-miterlimit="10"
pointer-events="none"
id="path268" />
<path
d="m 809.88,1174.43 -6.96,3.57 1.71,-3.51 -1.78,-3.49 z"
stroke="#000000"
stroke-miterlimit="10"
pointer-events="none"
id="path270" />
<path
d="m 709.5,1189 11,-12.57 -9.35,-8.79 9.35,-7.54 -9.35,-11.31 17.05,-19.79 14.3,16.02 -13.2,8.8 7.7,8.79 -11.55,7.54 7.15,6.91 z"
fill="#ffd966"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="6"
pointer-events="none"
id="path272" />
<switch
transform="translate(-0.5,-0.5)"
id="switch282">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe flex-start;justify-content:unsafe center;width:1px;height:1px;padding-top:1196px;margin-left:726px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:14px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:nowrap">
<xhtml:div
style="font-size:14px">
<xhtml:font
style="font-size:14px">functional events</xhtml:font>
</xhtml:div>
<xhtml:div
style="font-size:14px">
<xhtml:font
style="font-size:14px">(e.g.<xhtml:font
style="font-size:14px"
face="Courier New">fetch</xhtml:font>
)<xhtml:br
style="font-size:14px" />
</xhtml:font>
</xhtml:div>
</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="726"
y="1210"
font-family="Helvetica"
font-size="14"
text-anchor="middle"
style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:14px;font-family:Helvetica;-inkscape-font-specification:'Helvetica, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-anchor:middle;fill:#000000"
id="text280"><tspan
x="726"
y="1210"
id="tspan274">functional events</tspan><tspan
x="726"
y="1227.5"
id="tspan278">(e.g. <tspan
style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:'Courier New';-inkscape-font-specification:'Courier New'"
id="tspan276">fetch</tspan>)</tspan></text>
</switch>
<path
d="m 1041,749 c 0,10 60,10 60,0"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path284" />
<path
d="m 1041,754 c 0,10 60,10 60,0"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path286" />
<path
d="m 1041,759 c 0,10 60,10 60,0"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path288" />
<path
d="m 1041,749 c 0,-13.33 60,-13.33 60,0 v 40 c 0,13.33 -60,13.33 -60,0 z"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path290" />
<switch
transform="translate(-0.5,-0.5)"
id="switch294">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:58px;height:1px;padding-top:816px;margin-left:1042px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:19px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">
<xhtml:font
style="font-size:14px">Cache</xhtml:font>
</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="1071"
y="821"
font-family="Helvetica"
font-size="19px"
text-anchor="middle"
id="text292">Cache</text>
</switch>
<switch
transform="translate(-0.5,-0.5)"
id="switch298">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:58px;height:1px;padding-top:779px;margin-left:1042px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:19px;font-family:Courier New;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">v1</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="1071"
y="785"
font-family="'Courier New'"
font-size="19px"
text-anchor="middle"
id="text296">v1</text>
</switch>
<path
d="m 1041,974 c 0,10 60,10 60,0"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path300" />
<path
d="m 1041,979 c 0,10 60,10 60,0"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path302" />
<path
d="m 1041,984 c 0,10 60,10 60,0"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path304" />
<path
d="m 1041,974 c 0,-13.33 60,-13.33 60,0 v 40 c 0,13.33 -60,13.33 -60,0 z"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path306" />
<switch
transform="translate(-0.5,-0.5)"
id="switch310">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:58px;height:1px;padding-top:1004px;margin-left:1042px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:19px;font-family:Courier New;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">v1</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="1071"
y="1010"
font-family="'Courier New'"
font-size="19px"
text-anchor="middle"
id="text308">v1</text>
</switch>
<path
d="m 1041,1154 c 0,10 60,10 60,0"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path312" />
<path
d="m 1041,1159 c 0,10 60,10 60,0"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path314" />
<path
d="m 1041,1164 c 0,10 60,10 60,0"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path316" />
<path
d="m 1041,1154 c 0,-13.33 60,-13.33 60,0 v 40 c 0,13.33 -60,13.33 -60,0 z"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path318" />
<switch
transform="translate(-0.5,-0.5)"
id="switch322">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:58px;height:1px;padding-top:1184px;margin-left:1042px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:19px;font-family:Courier New;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">v1</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="1071"
y="1190"
font-family="'Courier New'"
font-size="19px"
text-anchor="middle"
id="text320">v1</text>
</switch>
<path
d="m 598.5,1173.64 109.09,-0.79"
fill="none"
stroke="#000000"
stroke-miterlimit="10"
pointer-events="none"
id="path324" />
<path
d="m 712.84,1172.81 -6.98,3.55 1.73,-3.51 -1.78,-3.49 z"
stroke="#000000"
stroke-miterlimit="10"
pointer-events="none"
id="path326" />
<path
d="M 897.6,1165.46 Q 981,1149 1034.78,1160.65"
fill="none"
stroke="#000000"
stroke-miterlimit="10"
pointer-events="none"
id="path328" />
<path
d="m 1039.91,1161.76 -7.59,1.94 2.46,-3.05 -0.97,-3.79 z"
stroke="#000000"
stroke-miterlimit="10"
pointer-events="none"
id="path330" />
<path
d="M 903.77,1186.67 Q 991,1209 1041,1184"
fill="none"
stroke="#000000"
stroke-miterlimit="10"
pointer-events="none"
id="path332" />
<path
d="m 898.68,1185.36 7.65,-1.65 -2.56,2.96 0.83,3.82 z"
stroke="#000000"
stroke-miterlimit="10"
pointer-events="none"
id="path334" />
<switch
transform="translate(-0.5,-0.5)"
id="switch340">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:1px;height:1px;padding-top:1174px;margin-left:981px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0); background-color: rgb(255 255 255);">
<xhtml:div
style="display:inline-block;font-size:19px;font-family:Courier New;color:#000;line-height:1.2;pointer-events:none;background-color:#fff;white-space:nowrap">
<xhtml:font
style="font-size:15px"
face="Helvetica">Using cache</xhtml:font>
</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="981"
y="1180"
font-family="Courier New"
font-size="19"
text-anchor="middle"
style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:18.6667px;font-family:Helvetica;-inkscape-font-specification:'Helvetica, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-anchor:middle;fill:#000000"
id="text338"><tspan
style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:13.3333px;font-family:Helvetica;-inkscape-font-specification:'Helvetica, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal"
id="tspan336">Using cache</tspan></text>
</switch>
<text
x="824.3877"
y="1475.693"
font-family="Helvetica"
pointer-events="none"
text-anchor="middle"
font-size="14px"
id="text342">Previous version</text>
<path
d="m 779.88772,1451.193 v -120 h 60.46 l 26.14,30.48 v 89.52 z m 4.9,-5.69 h 76.8 v -78.11 h -24.51 v -30.48 h -52.29 z"
fill="#b3b3b3"
pointer-events="none"
id="path344" />
<path
d="m 796.99772,1439.693 v -55 h 52.38 v 55 z"
fill="#b3b3b3"
pointer-events="none"
id="path346" />
<path
d="m 796.99772,1439.693 v -2.48 h 52.38 v 2.48 z"
fill-opacity="0.3"
pointer-events="none"
id="path348" />
<path
d="m 823.24772,1418.613 c -4.32,0 -7.71,-3.44 -7.71,-7.65 0,-4.54 3.78,-7.71 7.48,-7.71 4.95,0 7.81,4.07 7.81,7.58 0,4.51 -3.57,7.78 -7.58,7.78 z m 0.16,5.99 c 7,0 13.42,-5.9 13.42,-13.85 0,-7.17 -5.85,-13.54 -13.86,-13.54 -6.57,0 -13.42,5.47 -13.42,13.81 0,7.18 5.73,13.58 13.86,13.58 z m -13.13,5.39 -6.03,-6.08 2.45,-2.48 c -1.19,-1.93 -2.1,-4.02 -2.57,-6.21 h -3.47 v -8.55 l 3.47,-0.02 c 0.46,-2.2 1.42,-4.38 2.57,-6.22 l -2.45,-2.44 6.03,-6.06 2.47,2.46 c 2.03,-1.27 4.1,-2.11 6.18,-2.57 v -3.49 h 8.52 v 3.51 c 2.48,0.55 4.5,1.51 6.18,2.57 l 2.47,-2.47 6.04,6.03 -2.45,2.46 c 1.35,2.15 2.12,4.32 2.54,6.22 h 3.47 v 8.59 h -3.47 c -0.57,2.49 -1.49,4.51 -2.57,6.2 l 2.47,2.47 -6.01,6.06 -2.47,-2.47 c -1.76,1.08 -3.69,2.02 -6.17,2.56 l -0.02,3.51 h -8.53 v -3.48 c -2.31,-0.53 -4.37,-1.42 -6.18,-2.59 z"
fill="#ffffff"
pointer-events="none"
id="path350" />
<switch
transform="translate(-1.6122807,21.692983)"
id="switch354">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:58px;height:1px;padding-top:1334px;margin-left:782px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: #B3B3B3;">
<xhtml:div
style="display:inline-block;font-size:19px;font-family:Courier New;color:#b3b3b3;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">v1</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="811"
y="1340"
fill="#b3b3b3"
font-family="'Courier New'"
font-size="19px"
text-anchor="middle"
id="text352">v1</text>
</switch>
<path
d="m 239.88772,1370.093 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 l 20.11,21.89 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 h -74.02 c -6.62,-0.54 -11.86,-6.34 -12.25,-13.55 z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 h -16.43 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 l -13.78,51.21 z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z m 68.44,-35.33 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 l 20.11,21.89 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 h -74.02 c -6.62,-0.54 -11.86,-6.34 -12.25,-13.55 z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 h -16.43 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 l -13.78,51.21 z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z"
fill="#b3b3b3"
pointer-events="none"
id="path356" />
<path
d="m 499.88772,1370.093 c 0.27,-7.76 6.14,-13.89 13.27,-13.89 h 64.12 l 20.11,21.89 v 74.55 c -0.31,6.84 -5.01,12.5 -11.23,13.55 h -74.02 c -6.62,-0.54 -11.86,-6.34 -12.25,-13.55 z m 8.17,82.32 c 0.31,2.35 1.75,4.34 3.78,5.23 h 72.79 c 2.49,-0.69 4.33,-3 4.59,-5.78 l 0.1,-68.66 h -16.43 v -18 h -60.03 c -2.34,0.48 -4.21,2.38 -4.8,4.89 z m 25.01,-22.44 -18.38,-13 v -4.89 l 18.38,-13.55 v 7 l -13.37,8.89 13.37,8.33 z m 4.29,9.22 13.78,-51.21 h 5.51 l -13.78,51.21 z m 24.09,-33.77 v -7.22 l 18.28,13.33 v 5 l -18.28,12.89 v -6.89 l 13.38,-8.33 z"
pointer-events="none"
id="path358" />
<path
d="m 574.23772,1476.193 -24.35,-24.37 9.74,-9.7 12.48,12.52 c 5.92,-5.95 12.02,-11.92 19.82,-18.01 7.91,-6.14 16.35,-10.44 20.46,-10.24 -7.8,6.56 -15.57,14.73 -22.42,23.68 -7.22,9.22 -12.41,18.17 -15.73,26.12 z"
fill="#2d9c5e"
pointer-events="none"
id="path360" />
<switch
transform="translate(-1.6122807,21.692983)"
id="switch364">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:188px;height:1px;padding-top:1389px;margin-left:2px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:14px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">
<xhtml:font
style="font-size:19px">6. Replacement<xhtml:br />
</xhtml:font>
</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="96"
y="1393"
font-family="Helvetica"
font-size="14px"
text-anchor="middle"
id="text362">6. Replacement</text>
</switch>
<path
d="m 1069.8877,1341.193 c 0,10 60,10 60,0"
fill="none"
stroke="#b3b3b3"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path366" />
<path
d="m 1069.8877,1346.193 c 0,10 60,10 60,0"
fill="none"
stroke="#b3b3b3"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path368" />
<path
d="m 1069.8877,1351.193 c 0,10 60,10 60,0"
fill="none"
stroke="#b3b3b3"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path370" />
<path
d="m 1069.8877,1341.193 c 0,-13.33 60,-13.33 60,0 v 40 c 0,13.33 -60,13.33 -60,0 z"
fill="none"
stroke="#b3b3b3"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path372" />
<g
font-family="Helvetica"
pointer-events="none"
text-anchor="middle"
font-size="14px"
id="g380"
transform="translate(-1.1122807,22.192983)">
<text
x="1111"
y="1396.5"
id="text374">Old cache:</text>
<text
x="1111"
y="1413.5"
id="text378">purged during v2 <tspan
style="font-style:normal;font-variant:normal;font-weight:700;font-stretch:normal;font-family:Helvetica;-inkscape-font-specification:'Helvetica Bold'"
id="tspan376">activation</tspan></text>
</g>
<switch
transform="translate(-1.6122807,21.692983)"
id="switch384">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:58px;height:1px;padding-top:1349px;margin-left:1072px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: #B3B3B3;">
<xhtml:div
style="display:inline-block;font-size:19px;font-family:Courier New;color:#b3b3b3;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">v1</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="1101"
y="1355"
fill="#b3b3b3"
font-family="'Courier New'"
font-size="19px"
text-anchor="middle"
id="text382">v1</text>
</switch>
<g
font-family="Helvetica"
pointer-events="none"
text-anchor="middle"
font-size="14px"
id="g394"
transform="translate(-1.1122807,22.192983)">
<text
x="725.5"
y="1496.5"
id="text386">New version:</text>
<text
x="725.5"
y="1513.5"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:14px;font-family:Helvetica;-inkscape-font-specification:'Helvetica, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal"
id="text392"><tspan
sodipodi:role="line"
id="tspan1316"
x="725.5"
y="1513.5">will control pages</tspan><tspan
sodipodi:role="line"
id="tspan1318"
x="725.5"
y="1531">once installed and activated</tspan></text>
</g>
<path
d="m 679.88772,1481.193 v -120 h 60.46 l 26.14,30.48 v 89.52 z m 4.9,-5.69 h 76.8 v -78.11 h -24.51 v -30.48 h -52.29 z"
pointer-events="none"
id="path396" />
<path
d="m 696.99772,1469.693 v -55 h 52.38 v 55 z"
pointer-events="none"
id="path398" />
<path
d="m 696.99772,1469.693 v -2.48 h 52.38 v 2.48 z"
fill-opacity="0.3"
pointer-events="none"
id="path400" />
<path
d="m 723.24772,1448.613 c -4.32,0 -7.71,-3.44 -7.71,-7.65 0,-4.54 3.78,-7.71 7.48,-7.71 4.95,0 7.81,4.07 7.81,7.58 0,4.51 -3.57,7.78 -7.58,7.78 z m 0.16,5.99 c 7,0 13.42,-5.9 13.42,-13.85 0,-7.17 -5.85,-13.54 -13.86,-13.54 -6.57,0 -13.42,5.47 -13.42,13.81 0,7.18 5.73,13.58 13.86,13.58 z m -13.13,5.39 -6.03,-6.08 2.45,-2.48 c -1.19,-1.93 -2.1,-4.02 -2.57,-6.21 h -3.47 v -8.55 l 3.47,-0.02 c 0.46,-2.2 1.42,-4.38 2.57,-6.22 l -2.45,-2.44 6.03,-6.06 2.47,2.46 c 2.03,-1.27 4.1,-2.11 6.18,-2.57 v -3.49 h 8.52 v 3.51 c 2.48,0.55 4.5,1.51 6.18,2.57 l 2.47,-2.47 6.04,6.03 -2.45,2.46 c 1.35,2.15 2.12,4.32 2.54,6.22 h 3.47 v 8.59 h -3.47 c -0.57,2.49 -1.49,4.51 -2.57,6.2 l 2.47,2.47 -6.01,6.06 -2.47,-2.47 c -1.76,1.08 -3.69,2.02 -6.17,2.56 l -0.02,3.51 h -8.53 v -3.48 c -2.31,-0.53 -4.37,-1.42 -6.18,-2.59 z"
fill="#ffffff"
pointer-events="none"
id="path402" />
<switch
transform="translate(-1.6122807,21.692983)"
id="switch406">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:58px;height:1px;padding-top:1364px;margin-left:682px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:19px;font-family:Courier New;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">v2</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="711"
y="1370"
font-family="'Courier New'"
font-size="19px"
text-anchor="middle"
id="text404">v2</text>
</switch>
<path
d="m 949.88772,1426.193 c 0,10 59.99998,10 59.99998,0"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path408" />
<path
d="m 949.88772,1431.193 c 0,10 59.99998,10 59.99998,0"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path410" />
<path
d="m 949.88772,1436.193 c 0,10 59.99998,10 59.99998,0"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path412" />
<path
d="m 949.88772,1426.193 c 0,-13.33 59.99998,-13.33 59.99998,0 v 40 c 0,13.33 -59.99998,13.33 -59.99998,0 z"
fill="none"
stroke="#000000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path414" />
<g
font-family="Helvetica"
pointer-events="none"
text-anchor="middle"
font-size="14px"
id="g422"
transform="translate(-1.1122807,22.192983)">
<text
x="980.5"
y="1481.5"
id="text416">New cache:</text>
<text
x="980.5"
y="1498.5"
id="text420">populated during <tspan
style="font-style:normal;font-variant:normal;font-weight:700;font-stretch:normal;font-family:Helvetica;-inkscape-font-specification:'Helvetica Bold'"
id="tspan418">installation</tspan></text>
</g>
<switch
transform="translate(-1.6122807,21.692983)"
id="switch426">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:58px;height:1px;padding-top:1434px;margin-left:952px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:19px;font-family:Courier New;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">v2</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="981"
y="1440"
font-family="'Courier New'"
font-size="19px"
text-anchor="middle"
id="text424">v2</text>
</switch>
</svg>
| 0 |
data/mdn-content/files/en-us/web/api/service_worker_api | data/mdn-content/files/en-us/web/api/service_worker_api/using_service_workers/index.md | ---
title: Using Service Workers
slug: Web/API/Service_Worker_API/Using_Service_Workers
page-type: guide
---
{{DefaultAPISidebar("Service Workers API")}}
This article provides information on getting started with service workers, including basic architecture, registering a service worker, the installation and activation process for a new service worker, updating your service worker, cache control and custom responses, all in the context of a simple app with offline functionality.
## The premise of service workers
One overriding problem that web users have suffered with for years is loss of connectivity. The best web app in the world will provide a terrible user experience if you can't download it. There have been various attempts to create technologies to solve this problem, and some of the issues have been solved. But the overriding problem is that there wasn't a good overall control mechanism for asset caching and custom network requests.
Service workers fix these issues. Using a service worker you can set an app up to use cached assets first, thus providing a default experience even when offline, before then getting more data from the network (commonly known as "offline first"). This is already available with native apps, which is one of the main reasons native apps are often chosen over web apps.
A service worker functions like a proxy server, allowing you to modify requests and responses replacing them with items from its own cache.
## Setting up to play with service workers
Service workers are enabled by default in all modern browsers. To run code using service workers, you'll need to serve your code via HTTPS — Service workers are restricted to running across HTTPS for security reasons. A server supporting HTTPS is necessary. To host experiments, you can use a service such as GitHub, Netlify, Vercel, etc. In order to facilitate local development, `localhost` is considered a secure origin by browsers as well.
## Basic architecture
With service workers, the following steps are generally observed for basic setup:
1. The service worker code is fetched and then registered using [`serviceWorkerContainer.register()`](/en-US/docs/Web/API/ServiceWorkerContainer/register). If successful, the service worker is executed in a [`ServiceWorkerGlobalScope`](/en-US/docs/Web/API/ServiceWorkerGlobalScope); this is basically a special kind of worker context, running off the main script execution thread, with no DOM access. The service worker is now ready to process events.
2. Installation takes place. An `install` event is always the first one sent to a service worker (this can be used to start the process of populating an IndexedDB, and caching site assets). During this step, the application is preparing to make everything available for use offline.
3. When the `install` handler completes, the service worker is considered installed. At this point a previous version of the service worker may be active and controlling open pages. Because we don't want two different versions of the same service worker running at the same time, the new version is not yet active.
4. Once all pages controlled by the old version of the service worker have closed, it's safe to retire the old version, and the newly installed service worker receives an `activate` event. The primary use of `activate` is to clean up resources used in previous versions of the service worker. The new service worker can call [`skipWaiting()`](/en-US/docs/Web/API/ServiceWorkerGlobalScope/skipWaiting) to ask to be activated immediately without waiting for open pages to be closed. The new service worker will then receive `activate` immediately, and will take over any open pages.
5. After activation, the service worker will now control pages, but only those that were opened after the `register()` is successful. In other words, documents will have to be reloaded to actually be controlled, because a document starts life with or without a service worker and maintains that for its lifetime. To override this default behavior and adopt open pages, a service worker can call [`clients.claim()`](/en-US/docs/Web/API/Clients/claim).
6. Whenever a new version of a service worker is fetched, this cycle happens again and the remains of the previous version are cleaned during the new version's activation.

Here is a summary of the available service worker events:
- [`install`](/en-US/docs/Web/API/ServiceWorkerGlobalScope/install_event)
- [`activate`](/en-US/docs/Web/API/ServiceWorkerGlobalScope/activate_event)
- [`message`](/en-US/docs/Web/API/ServiceWorkerGlobalScope/message_event)
- Functional events
- [`fetch`](/en-US/docs/Web/API/ServiceWorkerGlobalScope/fetch_event)
- [`sync`](/en-US/docs/Web/API/ServiceWorkerGlobalScope/sync_event)
- [`push`](/en-US/docs/Web/API/ServiceWorkerGlobalScope/push_event)
## Demo
To demonstrate just the very basics of registering and installing a service worker, we have created a demo called [simple service worker](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker), which is a simple Star Wars Lego image gallery. It uses a promise-powered function to read image data from a JSON object and load the images using [`fetch()`](/en-US/docs/Web/API/Fetch_API/Using_Fetch), before displaying the images in a line down the page. We've kept things static for now. It also registers, installs, and activates a service worker.

You can see the [source code on GitHub](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker), and the [simple service worker running live](https://bncb2v.csb.app/).
### Registering your worker
The first block of code in our app's JavaScript file — `app.js` — is as follows. This is our entry point into using service workers.
```js
const registerServiceWorker = async () => {
if ("serviceWorker" in navigator) {
try {
const registration = await navigator.serviceWorker.register("/sw.js", {
scope: "/",
});
if (registration.installing) {
console.log("Service worker installing");
} else if (registration.waiting) {
console.log("Service worker installed");
} else if (registration.active) {
console.log("Service worker active");
}
} catch (error) {
console.error(`Registration failed with ${error}`);
}
}
};
// …
registerServiceWorker();
```
1. The `if`-block performs a feature detection test to make sure service workers are supported before trying to register one.
2. Next, we use the [`ServiceWorkerContainer.register()`](/en-US/docs/Web/API/ServiceWorkerContainer/register) function to register the service worker for this site. The service worker code is in a JavaScript file residing inside our app (note this is the file's URL relative to the origin, not the JS file that references it.)
3. The `scope` parameter is optional, and can be used to specify the subset of your content that you want the service worker to control. In this case, we have specified `'/'`, which means all content under the app's origin. If you leave it out, it will default to this value anyway, but we specified it here for illustration purposes.
This registers a service worker, which runs in a worker context, and therefore has no DOM access.
A single service worker can control many pages. Each time a page within your scope is loaded, the service worker is installed against that page and operates on it. Bear in mind therefore that you need to be careful with global variables in the service worker script: each page doesn't get its own unique worker.
> **Note:** One great thing about service workers is that if you use feature detection like we've shown above, browsers that don't support service workers can just use your app online in the normal expected fashion.
#### Why is my service worker failing to register?
This could be for the following reasons:
- You are not running your application through HTTPS.
- The path to your service worker file is not written correctly — it needs to be written relative to the origin, not your app's root directory. In our example, the worker is at `https://bncb2v.csb.app/sw.js`, and the app's root is `https://bncb2v.csb.app/`. But the path needs to be written as `/sw.js`.
- It is also not allowed to point to a service worker of a different origin than that of your app.
- The service worker will only catch requests from clients under the service worker's scope.
- The max scope for a service worker is the location of the worker (in other words if the script `sw.js` is located in `/js/sw.js`, it can only control URLs under `/js/` by default). A list of max scopes for that worker can be specified with the [`Service-Worker-Allowed`](/en-US/docs/Web/HTTP/Header/Service-Worker-Allowed) header.
- In Firefox, Service Worker APIs are hidden and cannot be used when the user is in [private browsing mode](https://bugzil.la/1320796), or when history is disabled, or if cookies are cleared when Firefox is closed.
- In Chrome, registration fails when the "Block all cookies (not recommended)" option is enabled.
### Install and activate: populating your cache
After your service worker is registered, the browser will attempt to install then activate the service worker for your page/site.
The `install` event is fired when an installation is successfully completed. The `install` event is generally used to populate your browser's offline caching capabilities with the assets you need to run your app offline. To do this, we use Service Worker's storage API — [`cache`](/en-US/docs/Web/API/Cache) — a global object on the service worker that allows us to store assets delivered by responses, and keyed by their requests. This API works in a similar way to the browser's standard cache, but it is specific to your domain. The contents of the cache are kept until you clear them.
Here's how our service worker handles the `install` event:
```js
const addResourcesToCache = async (resources) => {
const cache = await caches.open("v1");
await cache.addAll(resources);
};
self.addEventListener("install", (event) => {
event.waitUntil(
addResourcesToCache([
"/",
"/index.html",
"/style.css",
"/app.js",
"/image-list.js",
"/star-wars-logo.jpg",
"/gallery/bountyHunters.jpg",
"/gallery/myLittleVader.jpg",
"/gallery/snowTroopers.jpg",
]),
);
});
```
1. Here we add an `install` event listener to the service worker (hence `self`), and then chain a [`ExtendableEvent.waitUntil()`](/en-US/docs/Web/API/ExtendableEvent/waitUntil) method onto the event — this ensures that the service worker will not install until the code inside `waitUntil()` has successfully occurred.
2. Inside `addResourcesToCache()` we use the [`caches.open()`](/en-US/docs/Web/API/CacheStorage/open) method to create a new cache called `v1`, which will be version 1 of our site resources cache. Then we call a function `addAll()` on the created cache, which for its parameter takes an array of URLs to all the resources you want to cache. The URLs are relative to the worker's {{domxref("WorkerGlobalScope.location", "location", "", 1)}}.
3. If the promise is rejected, the installation fails, and the worker won't do anything. This is OK, as you can fix your code and then try again the next time registration occurs.
4. After a successful installation, the service worker activates. This doesn't have much of a distinct use the first time your service worker is installed/activated, but it means more when the service worker is updated (see the [Updating your service worker](#updating_your_service_worker) section later on.)
> **Note:** [The Web Storage API (`localStorage`)](/en-US/docs/Web/API/Web_Storage_API) works in a similar way to service worker cache, but it is synchronous, so not allowed in service workers.
> **Note:** [IndexedDB](/en-US/docs/Web/API/IndexedDB_API) can be used inside a service worker for data storage if you require it.
### Custom responses to requests
Now you've got your site assets cached, you need to tell service workers to do something with the cached content. This is done with the `fetch` event.
1. A `fetch` event fires every time any resource controlled by a service worker is fetched, which includes the documents inside the specified scope, and any resources referenced in those documents (for example if `index.html` makes a cross-origin request to embed an image, that still goes through its service worker.)
2. You can attach a `fetch` event listener to the service worker, then call the `respondWith()` method on the event to hijack our HTTP responses and update them with your own content.
```js
self.addEventListener("fetch", (event) => {
event.respondWith(/* custom content goes here */);
});
```
3. We could start by responding with the resource whose URL matches that of the network request, in each case:
```js
self.addEventListener("fetch", (event) => {
event.respondWith(caches.match(event.request));
});
```
`caches.match(event.request)` allows us to match each resource requested from the network with the equivalent resource available in the cache, if there is a matching one available. The matching is done via URL and various headers, just like with normal HTTP requests.

## Recovering failed requests
So `caches.match(event.request)` is great when there is a match in the service worker cache, but what about cases when there isn't a match? If we didn't provide any kind of failure handling, our promise would resolve with `undefined` and we wouldn't get anything returned.
After testing the response from the cache, we can fall back on a regular network request:
```js
const cacheFirst = async (request) => {
const responseFromCache = await caches.match(request);
if (responseFromCache) {
return responseFromCache;
}
return fetch(request);
};
self.addEventListener("fetch", (event) => {
event.respondWith(cacheFirst(event.request));
});
```
If the resources aren't in the cache, they are requested from the network.
Using a more elaborate strategy, we could not only request the resource from the network, but also save it into the cache so that later requests for that resource could be retrieved offline too. This would mean that if extra images were added to the Star Wars gallery, our app could automatically grab them and cache them. The following snippet implements such a strategy:
```js
const putInCache = async (request, response) => {
const cache = await caches.open("v1");
await cache.put(request, response);
};
const cacheFirst = async (request) => {
const responseFromCache = await caches.match(request);
if (responseFromCache) {
return responseFromCache;
}
const responseFromNetwork = await fetch(request);
putInCache(request, responseFromNetwork.clone());
return responseFromNetwork;
};
self.addEventListener("fetch", (event) => {
event.respondWith(cacheFirst(event.request));
});
```
If the request URL is not available in the cache, we request the resource from the network request with `await fetch(request)`. After that, we put a clone of the response into the cache. The `putInCache()` function uses `caches.open('v1')` and `cache.put()` to add the resource to the cache. The original response is returned to the browser to be given to the page that called it.
Cloning the response is necessary because request and response streams can only be read once. In order to return the response to the browser and put it in the cache we have to clone it. So the original gets returned to the browser and the clone gets sent to the cache. They are each read once.
What might look a bit weird is that the promise returned by `putInCache()` is not awaited. But the reason is that we don't want to wait until the response clone has been added to the cache before returning a response.
The only trouble we have now is that if the request doesn't match anything in the cache, and the network is not available, our request will still fail. Let's provide a default fallback so that whatever happens, the user will at least get something:
```js
const putInCache = async (request, response) => {
const cache = await caches.open("v1");
await cache.put(request, response);
};
const cacheFirst = async ({ request, fallbackUrl }) => {
// First try to get the resource from the cache
const responseFromCache = await caches.match(request);
if (responseFromCache) {
return responseFromCache;
}
// Next try to get the resource from the network
try {
const responseFromNetwork = await fetch(request);
// response may be used only once
// we need to save clone to put one copy in cache
// and serve second one
putInCache(request, responseFromNetwork.clone());
return responseFromNetwork;
} catch (error) {
const fallbackResponse = await caches.match(fallbackUrl);
if (fallbackResponse) {
return fallbackResponse;
}
// when even the fallback response is not available,
// there is nothing we can do, but we must always
// return a Response object
return new Response("Network error happened", {
status: 408,
headers: { "Content-Type": "text/plain" },
});
}
};
self.addEventListener("fetch", (event) => {
event.respondWith(
cacheFirst({
request: event.request,
fallbackUrl: "/gallery/myLittleVader.jpg",
}),
);
});
```
We have opted for this fallback image because the only updates that are likely to fail are new images, as everything else is depended on for installation in the `install` event listener we saw earlier.
## Service Worker navigation preload
If enabled, the [navigation preload](/en-US/docs/Web/API/NavigationPreloadManager) feature starts downloading resources as soon as the fetch request is made, and in parallel with service worker activation. This ensures that download starts immediately on navigation to a page, rather than having to wait until the service worker is activated. That delay happens relatively rarely, but is unavoidable when it does happen, and may be significant.
First the feature must be enabled during service worker activation, using [`registration.navigationPreload.enable()`](/en-US/docs/Web/API/NavigationPreloadManager/enable):
```js
self.addEventListener("activate", (event) => {
event.waitUntil(self.registration?.navigationPreload.enable());
});
```
Then use [`event.preloadResponse`](/en-US/docs/Web/API/FetchEvent/preloadResponse) to wait for the preloaded resource to finish downloading in the `fetch` event handler.
Continuing the example from the previous sections, we insert the code to wait for the preloaded resource after the cache check, and before fetching from the network if that doesn't succeed.
The new process is:
1. Check cache
2. Wait on `event.preloadResponse`, which is passed as `preloadResponsePromise` to the `cacheFirst()` function. Cache the result if it returns.
3. If neither of these are defined then we go to the network.
```js
const addResourcesToCache = async (resources) => {
const cache = await caches.open("v1");
await cache.addAll(resources);
};
const putInCache = async (request, response) => {
const cache = await caches.open("v1");
await cache.put(request, response);
};
const cacheFirst = async ({ request, preloadResponsePromise, fallbackUrl }) => {
// First try to get the resource from the cache
const responseFromCache = await caches.match(request);
if (responseFromCache) {
return responseFromCache;
}
// Next try to use (and cache) the preloaded response, if it's there
const preloadResponse = await preloadResponsePromise;
if (preloadResponse) {
console.info("using preload response", preloadResponse);
putInCache(request, preloadResponse.clone());
return preloadResponse;
}
// Next try to get the resource from the network
try {
const responseFromNetwork = await fetch(request);
// response may be used only once
// we need to save clone to put one copy in cache
// and serve second one
putInCache(request, responseFromNetwork.clone());
return responseFromNetwork;
} catch (error) {
const fallbackResponse = await caches.match(fallbackUrl);
if (fallbackResponse) {
return fallbackResponse;
}
// when even the fallback response is not available,
// there is nothing we can do, but we must always
// return a Response object
return new Response("Network error happened", {
status: 408,
headers: { "Content-Type": "text/plain" },
});
}
};
// Enable navigation preload
const enableNavigationPreload = async () => {
if (self.registration.navigationPreload) {
await self.registration.navigationPreload.enable();
}
};
self.addEventListener("activate", (event) => {
event.waitUntil(enableNavigationPreload());
});
self.addEventListener("install", (event) => {
event.waitUntil(
addResourcesToCache([
"/",
"/index.html",
"/style.css",
"/app.js",
"/image-list.js",
"/star-wars-logo.jpg",
"/gallery/bountyHunters.jpg",
"/gallery/myLittleVader.jpg",
"/gallery/snowTroopers.jpg",
]),
);
});
self.addEventListener("fetch", (event) => {
event.respondWith(
cacheFirst({
request: event.request,
preloadResponsePromise: event.preloadResponse,
fallbackUrl: "/gallery/myLittleVader.jpg",
}),
);
});
```
Note that in this example we download and cache the same data for the resource whether it is downloaded "normally" or preloaded. You can instead choose to download and cache a different resource on preload. For more information see [`NavigationPreloadManager` > Custom responses](/en-US/docs/Web/API/NavigationPreloadManager#custom_responses).
## Updating your service worker
If your service worker has previously been installed, but then a new version of the worker is available on refresh or page load, the new version is installed in the background, but not yet activated. It is only activated when there are no longer any pages loaded that are still using the old service worker. As soon as there are no more such pages still loaded, the new service worker activates.
> **Note:** It is possible to bypass this by using [`Clients.claim()`](/en-US/docs/Web/API/Clients/claim).
You'll want to update your `install` event listener in the new service worker to something like this (notice the new version number):
```js
const addResourcesToCache = async (resources) => {
const cache = await caches.open("v2");
await cache.addAll(resources);
};
self.addEventListener("install", (event) => {
event.waitUntil(
addResourcesToCache([
"/",
"/index.html",
"/style.css",
"/app.js",
"/image-list.js",
// …
// include other new resources for the new version…
]),
);
});
```
While the service worker is being installed, the previous version is still responsible for fetches. The new version is installing in the background. We are calling the new cache `v2`, so the previous `v1` cache isn't disturbed.
When no pages are using the previous version, the new worker activates and becomes responsible for fetches.
### Deleting old caches
As we saw in the last section, when you update a service worker to a new version, you'll create a new cache in its `install` event handler. While there are open pages that are controlled by the previous version of the worker, you need to keep both caches, because the previous version needs its version of the cache. You can use the `activate` event to remove data from the previous caches.
Promises passed into `waitUntil()` will block other events until completion, so you can rest assured that your clean-up operation will have completed by the time you get your first `fetch` event on the new service worker.
```js
const deleteCache = async (key) => {
await caches.delete(key);
};
const deleteOldCaches = async () => {
const cacheKeepList = ["v2"];
const keyList = await caches.keys();
const cachesToDelete = keyList.filter((key) => !cacheKeepList.includes(key));
await Promise.all(cachesToDelete.map(deleteCache));
};
self.addEventListener("activate", (event) => {
event.waitUntil(deleteOldCaches());
});
```
## Developer tools
- [Chrome](https://www.chromium.org/blink/serviceworker/service-worker-faq/)
- [Firefox](https://firefox-source-docs.mozilla.org/devtools-user/application/service_workers/index.html)
- The "Forget about this site" button, available in [Firefox's toolbar customization options](https://support.mozilla.org/en-US/kb/customize-firefox-controls-buttons-and-toolbars), can be used to clear service workers and their caches.
- [Edge](https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/service-workers/)
## See also
- [Promises](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
- [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
| 0 |
data/mdn-content/files/en-us/web/api/service_worker_api | data/mdn-content/files/en-us/web/api/service_worker_api/using_service_workers/sw-fetch.svg | <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
width="877.845"
height="929.109"
viewBox="-25 -40 992.065 1050"
version="1.1"
id="svg140"
sodipodi:docname="sw-fetch.svg"
inkscape:version="1.2.1 (9c6d41e410, 2022-07-14)"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:xhtml="http://www.w3.org/1999/xhtml">
<defs
id="defs144" />
<sodipodi:namedview
id="namedview142"
pagecolor="#ffffff"
bordercolor="#000000"
borderopacity="0.25"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
showgrid="false"
inkscape:zoom="0.92023648"
inkscape:cx="439.56093"
inkscape:cy="466.72786"
inkscape:window-width="2400"
inkscape:window-height="1321"
inkscape:window-x="3191"
inkscape:window-y="438"
inkscape:window-maximized="1"
inkscape:current-layer="svg140" />
<path
d="M320.105 18.4c.27-7.76 6.14-13.89 13.27-13.89h64.12l20.11 21.89v74.55c-.31 6.84-5.01 12.5-11.23 13.55h-74.02c-6.62-.54-11.86-6.34-12.25-13.55zm8.17 82.32c.31 2.35 1.75 4.34 3.78 5.23h72.79c2.49-.69 4.33-3 4.59-5.78l.1-68.66h-16.43v-18h-60.03c-2.34.48-4.21 2.38-4.8 4.89zm25.01-22.44-18.38-13v-4.89l18.38-13.55v7l-13.37 8.89 13.37 8.33zm4.29 9.22 13.78-51.21h5.51l-13.78 51.21zm24.09-33.77v-7.22l18.28 13.33v5l-18.28 12.89v-6.89l13.38-8.33z"
pointer-events="none"
id="path2" />
<path
d="M210.105 18.4c.27-7.76 6.14-13.89 13.27-13.89h64.12l20.11 21.89v74.55c-.31 6.84-5.01 12.5-11.23 13.55h-74.02c-6.62-.54-11.86-6.34-12.25-13.55zm8.17 82.32c.31 2.35 1.75 4.34 3.78 5.23h72.79c2.49-.69 4.33-3 4.59-5.78l.1-68.66h-16.43v-18h-60.03c-2.34.48-4.21 2.38-4.8 4.89zm25.01-22.44-18.38-13v-4.89l18.38-13.55v7l-13.37 8.89 13.37 8.33zm4.29 9.22 13.78-51.21h5.51l-13.78 51.21zm24.09-33.77v-7.22l18.28 13.33v5l-18.28 12.89v-6.89l13.38-8.33zM100.105 18.4c.27-7.76 6.14-13.89 13.27-13.89h64.12l20.11 21.89v74.55c-.31 6.84-5.01 12.5-11.23 13.55h-74.02c-6.62-.54-11.86-6.34-12.25-13.55zm8.17 82.32c.31 2.35 1.75 4.34 3.78 5.23h72.79c2.49-.69 4.33-3 4.59-5.78l.1-68.66h-16.43v-18h-60.03c-2.34.48-4.21 2.38-4.8 4.89zm25.01-22.44-18.38-13v-4.89l18.38-13.55v7l-13.37 8.89 13.37 8.33zm4.29 9.22 13.78-51.21h5.51l-13.78 51.21zm24.09-33.77v-7.22l18.28 13.33v5l-18.28 12.89v-6.89l13.38-8.33z"
fill="#b3b3b3"
pointer-events="none"
id="path4" />
<path
d="M540.105 119.5V-.5h60.46l26.14 30.48v89.52zm4.9-5.69h76.8V35.7h-24.51V5.22h-52.29z"
pointer-events="none"
id="path6" />
<path
d="M557.097 105.89V52.012h50.3v53.88z"
pointer-events="none"
style="stroke-width:1.69348"
id="path8" />
<path
d="M557.097 105.89v-2.428h50.3v2.429z"
fill-opacity=".3"
pointer-events="none"
style="stroke-width:1.69348"
id="path10" />
<path
d="M582.314 85.245c-4.158 0-7.411-3.37-7.411-7.509 0-4.447 3.621-7.543 7.176-7.543 4.762 0 7.511 3.986 7.511 7.424 0 4.413-3.437 7.628-7.276 7.628zm.15 5.867c6.724 0 12.877-5.781 12.877-13.58 0-7.014-5.616-13.257-13.312-13.257-6.305 0-12.877 5.354-12.877 13.53 0 7.03 5.5 13.307 13.313 13.307zM569.84 96.38l-5.784-5.952 2.364-2.429c-1.157-1.881-2.029-3.934-2.482-6.072h-3.32v-8.381l3.32-.017c.453-2.156 1.375-4.294 2.482-6.09l-2.364-2.394 5.784-5.936 2.381 2.412c1.962-1.248 3.94-2.07 5.936-2.514v-3.438h8.182v3.438c2.38.547 4.309 1.488 5.935 2.514l2.381-2.412 5.801 5.901-2.364 2.43a20.009 20.009 0 0 1 2.448 6.089h3.32v8.398h-3.32c-.553 2.446-1.442 4.43-2.481 6.09l2.38 2.411-5.784 5.952-2.364-2.428c-1.677 1.06-3.538 1.967-5.919 2.514l-.016 3.438h-8.2v-3.421a18.443 18.815 0 0 1-5.935-2.531z"
fill="#fff"
pointer-events="none"
style="stroke-width:1.69348"
id="path12" />
<path
d="m631.045 136-20.94-20.96 8.37-8.34 10.74 10.77c5.09-5.12 10.33-10.26 17.05-15.49 6.8-5.28 14.05-8.98 17.59-8.81-6.7 5.65-13.39 12.67-19.28 20.37-6.21 7.92-10.68 15.62-13.53 22.46z"
fill="#2d9c5e"
pointer-events="none"
id="path14" />
<path
d="M100.105 136v5q0 5 10 5h140q10 0 10 5v2.5-5q0-2.5 10-2.5h140q10 0 10-5v-5"
fill="none"
stroke="#000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path16" />
<switch
transform="translate(-42.395 -1.5)"
id="switch20">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:288px;height:1px;padding-top:189px;margin-left:158px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:18px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">Pages in the service worker scope</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="302"
y="194"
font-family="Helvetica"
font-size="18"
text-anchor="middle"
id="text18">Pages in the service worker scope</text>
</switch>
<switch
transform="translate(-42.395 -1.5)"
id="switch24">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:198px;height:1px;padding-top:189px;margin-left:526px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:18px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">Service worker installed and activated</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="625"
y="194"
font-family="Helvetica"
font-size="18"
text-anchor="middle"
id="text22">Service worker installed and activated</text>
</switch>
<switch
transform="translate(-42.395 -1.5)"
id="switch28">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:1px;height:1px;padding-top:64px;margin-left:52px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:24px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;font-weight:700;white-space:nowrap">1.</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="52"
y="71"
font-family="Helvetica"
font-size="24"
text-anchor="middle"
font-weight="bold"
id="text26">1.</text>
</switch>
<switch
transform="translate(-42.395 -1.5)"
id="switch32">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:1px;height:1px;padding-top:844px;margin-left:52px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:24px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;font-weight:700;white-space:nowrap">4.</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="52"
y="851"
font-family="Helvetica"
font-size="24"
text-anchor="middle"
font-weight="bold"
id="text30">4.</text>
</switch>
<path
d="M120.105 791.9c.27-7.76 6.14-13.89 13.27-13.89h64.12l20.11 21.89v74.55c-.31 6.84-5.01 12.5-11.23 13.55h-74.02c-6.62-.54-11.86-6.34-12.25-13.55zm8.17 82.32c.31 2.35 1.75 4.34 3.78 5.23h72.79c2.49-.69 4.33-3 4.59-5.78l.1-68.66h-16.43v-18h-60.03c-2.34.48-4.21 2.38-4.8 4.89zm25.01-22.44-18.38-13v-4.89l18.38-13.55v7l-13.37 8.89 13.37 8.33zm4.29 9.22 13.78-51.21h5.51L163.085 861zm24.09-33.77v-7.22l18.28 13.33v5l-18.28 12.89v-6.89l13.38-8.33zM540.105 893V773h60.46l26.14 30.48V893zm4.9-5.69h76.8V809.2h-24.51v-30.48h-52.29z"
pointer-events="none"
id="path34" />
<switch
transform="translate(-36.64 -15.31)"
id="switch42">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:198px;height:1px;padding-top:949px;margin-left:526px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:18px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">The service worker sends back the custom response.</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="619.181"
y="947.172"
font-family="Helvetica"
font-size="18"
text-anchor="middle"
id="text40"><tspan
x="619.181"
y="947.172"
id="tspan36">The service worker sends</tspan><tspan
x="619.181"
y="969.672"
id="tspan38">back the custom response.</tspan></text>
</switch>
<path
d="M540.105 833h-312.4"
fill="none"
stroke="#000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path44" />
<path
d="m220.955 833 9-4.5-2.25 4.5 2.25 4.5z"
stroke="#000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path46" />
<switch
transform="translate(-42.395 -1.5)"
id="switch50">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:1px;height:1px;padding-top:794px;margin-left:422px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0); background-color: rgb(255 255 255);">
<xhtml:div
style="display:inline-block;font-size:18px;font-family:Courier New;color:#000;line-height:1.2;pointer-events:none;background-color:#fff;white-space:nowrap">
<xhtml:b>event.respondWith()</xhtml:b>
</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="422"
y="799"
font-family="'Courier New'"
font-size="18"
text-anchor="middle"
id="text48">event.respondWith()</text>
</switch>
<switch
transform="translate(-42.395 -1.5)"
id="switch54">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:1px;height:1px;padding-top:336px;margin-left:52px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:24px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;font-weight:700;white-space:nowrap">2.</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="52"
y="343"
font-family="Helvetica"
font-size="24"
text-anchor="middle"
font-weight="bold"
id="text52">2.</text>
</switch>
<path
d="M120.105 279.9c.27-7.76 6.14-13.89 13.27-13.89h64.12l20.11 21.89v74.55c-.31 6.84-5.01 12.5-11.23 13.55h-74.02c-6.62-.54-11.86-6.34-12.25-13.55zm8.17 82.32c.31 2.35 1.75 4.34 3.78 5.23h72.79c2.49-.69 4.33-3 4.59-5.78l.1-68.66h-16.43v-18h-60.03c-2.34.48-4.21 2.38-4.8 4.89zm25.01-22.44-18.38-13v-4.89l18.38-13.55v7l-13.37 8.89 13.37 8.33zm4.29 9.22 13.78-51.21h5.51L163.085 349zm24.09-33.77v-7.22l18.28 13.33v5l-18.28 12.89v-6.89l13.38-8.33zM540.105 381V261h60.46l26.14 30.48V381zm4.9-5.69h76.8V297.2h-24.51v-30.48h-52.29z"
pointer-events="none"
id="path56" />
<path
d="M569.445 291.93c-2.48 0-4.42-1.97-4.42-4.39 0-2.6 2.16-4.41 4.28-4.41 2.84 0 4.48 2.33 4.48 4.34 0 2.58-2.05 4.46-4.34 4.46zm.09 3.43c4.01 0 7.68-3.38 7.68-7.94 0-4.1-3.35-7.75-7.94-7.75-3.76 0-7.68 3.13-7.68 7.91 0 4.11 3.28 7.78 7.94 7.78zm-7.53 3.08-3.45-3.48 1.41-1.42c-.69-1.1-1.21-2.3-1.48-3.55h-1.98v-4.9l1.98-.01c.27-1.26.82-2.51 1.48-3.56l-1.41-1.4 3.45-3.47 1.42 1.41c1.17-.73 2.35-1.21 3.54-1.47v-2.01h4.88v2.01c1.42.32 2.57.87 3.54 1.47l1.42-1.41 3.46 3.45-1.41 1.42c.77 1.23 1.21 2.47 1.46 3.56h1.98v4.91h-1.98c-.33 1.43-.86 2.59-1.48 3.56l1.42 1.41-3.45 3.48-1.41-1.42c-1 .62-2.11 1.15-3.53 1.47l-.01 2.01h-4.89v-2a11 11 0 0 1-3.54-1.48z"
fill="#fff"
pointer-events="none"
id="path58" />
<switch
transform="translate(-42.395 -1.5)"
id="switch70">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:288px;height:1px;padding-top:407px;margin-left:67px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:18px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">The page requests a resource (possibly located at another origin)</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="211"
y="412"
font-family="Helvetica"
font-size="18"
text-anchor="middle"
style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:18px;font-family:Helvetica;-inkscape-font-specification:'Helvetica, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;text-anchor:middle;fill:#000"
id="text68"><tspan
x="211"
y="412"
id="tspan62"><tspan
id="tspan60">The page requests a resource</tspan></tspan><tspan
x="211"
y="434.5"
id="tspan66"><tspan
id="tspan64">(possibly located at another origin)</tspan></tspan></text>
</switch>
<path
d="M217.605 321h312.4"
fill="none"
stroke="#000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path72" />
<path
d="m536.755 321-9 4.5 2.25-4.5-2.25-4.5z"
stroke="#000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path74" />
<switch
transform="translate(-42.395 -1.5)"
id="switch80">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:1px;height:1px;padding-top:282px;margin-left:422px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0); background-color: rgb(255 255 255);">
<xhtml:div
style="display:inline-block;font-size:18px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;background-color:#fff;white-space:nowrap">
<xhtml:b><xhtml:font
face="Courier New">fetch</xhtml:font>
event</xhtml:b>
</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="422"
y="287"
font-family="Helvetica"
font-size="18"
text-anchor="middle"
id="text78"><tspan
style="font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-family:'Courier New';-inkscape-font-specification:'Courier New'"
id="tspan76">fetch</tspan> event</text>
</switch>
<switch
transform="translate(-42.395 -1.5)"
id="switch84">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:288px;height:1px;padding-top:414px;margin-left:481px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:18px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">The service worker intercepts the request</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="625"
y="419"
font-family="Helvetica"
font-size="18"
text-anchor="middle"
id="text82">The service worker intercepts the request</text>
</switch>
<switch
transform="translate(-42.395 -1.5)"
id="switch88">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:1px;height:1px;padding-top:584px;margin-left:51px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:24px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;font-weight:700;white-space:nowrap">3.</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="51"
y="591"
font-family="Helvetica"
font-size="24"
text-anchor="middle"
font-weight="bold"
id="text86">3.</text>
</switch>
<path
d="M119.105 531.9c.27-7.76 6.14-13.89 13.27-13.89h64.12l20.11 21.89v74.55c-.31 6.84-5.01 12.5-11.23 13.55h-74.02c-6.62-.54-11.86-6.34-12.25-13.55zm8.17 82.32c.31 2.35 1.75 4.34 3.78 5.23h72.79c2.49-.69 4.33-3 4.59-5.78l.1-68.66h-16.43v-18h-60.03c-2.34.48-4.21 2.38-4.8 4.89zm25.01-22.44-18.38-13v-4.89l18.38-13.55v7l-13.37 8.89 13.37 8.33zm4.29 9.22 13.78-51.21h5.51L162.085 601zm24.09-33.77v-7.22l18.28 13.33v5l-18.28 12.89v-6.89l13.38-8.33zM539.105 633V513h60.46l26.14 30.48V633zm4.9-5.69h76.8V549.2h-24.51v-30.48h-52.29z"
pointer-events="none"
id="path90" />
<switch
transform="translate(-45.848 -36.026)"
id="switch98">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe center;justify-content:unsafe center;width:288px;height:1px;padding-top:703px;margin-left:480px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:18px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:normal;overflow-wrap:normal">The service worker fetches a custom response from possibly different sources</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="624"
y="708"
font-family="Helvetica"
font-size="18"
text-anchor="middle"
style="font-size:18px;font-family:Helvetica;text-anchor:middle;fill:#000"
id="text96"><tspan
x="624"
y="708"
id="tspan92">The service worker fetches a custom</tspan><tspan
x="624"
y="730.5"
id="tspan94">response from possibly different sources</tspan></text>
</switch>
<path
d="M749.105 573h-113.3"
fill="none"
stroke="#000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path100" />
<path
d="m629.055 573 9-4.5-2.25 4.5 2.25 4.5zm161.68-30c-5.99-1.18-10.48-6.23-10.97-12.38-.66-3.96.49-8 3.11-11.01 2.63-3.01 6.45-4.67 10.42-4.52 2.33-4.34 7.32-6.45 12.02-5.1-.36-7.52 4.72-14.2 12.01-15.78 6.48-1.21 12.89 2.44 15.22 8.66 4.89-2.89 11.07-2.2 15.22 1.7 4.15 3.55 6.1 9.08 5.12 14.48 4.28 2.19 6.86 6.74 6.57 11.57.19 6.16-4.22 11.48-10.25 12.38zm58.47-1.29c5.22-1.08 8.96-5.71 8.97-11.09.28-4.69-2.33-9.06-6.57-11 .97-5.27-.85-10.67-4.8-14.24a11.92 11.92 0 0 0-14.74-.89c-2.17-6.6-8.75-10.46-15.3-8.98-6.74 2.27-11.03 8.95-10.33 16.1-4.72-1.97-10.13.13-12.34 4.77-3.1-.48-6.25.46-8.73 2.61-2.47 2.15-4.06 5.32-4.4 8.8-.7 6.49 3.49 12.49 9.77 14z"
stroke="#000"
stroke-width="3"
stroke-miterlimit="10"
pointer-events="none"
id="path102" />
<switch
transform="translate(-42.395 -1.5)"
id="switch106">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe flex-start;justify-content:unsafe center;width:1px;height:1px;padding-top:551px;margin-left:861px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:18px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:nowrap">
<xhtml:div>Internet</xhtml:div>
</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="861"
y="569"
font-family="Helvetica"
font-size="18"
text-anchor="middle"
id="text104">Internet</text>
</switch>
<path
d="M749.105 592.65c0-5.33 10.86-9.65 24.25-9.65s24.25 4.32 24.25 9.65v50.69c0 5.33-10.86 9.66-24.25 9.66s-24.25-4.33-24.25-9.66z"
fill="none"
stroke="#000"
stroke-width="5"
stroke-miterlimit="10"
pointer-events="none"
id="path108" />
<path
d="M749.105 592.65c0 5.33 10.86 9.66 24.25 9.66s24.25-4.33 24.25-9.66m-48.5 15.93c0 5.34 10.86 9.66 24.25 9.66s24.25-4.32 24.25-9.66m-48.5 18.11c0 5.33 10.86 9.65 24.25 9.65s24.25-4.32 24.25-9.65"
fill="none"
stroke="#000"
stroke-width="5"
stroke-miterlimit="10"
pointer-events="none"
id="path110" />
<switch
transform="translate(-42.395 -1.5)"
id="switch114">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe flex-start;justify-content:unsafe center;width:1px;height:1px;padding-top:661px;margin-left:815px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0); background-color: #ffffff;">
<xhtml:div
style="display:inline-block;font-size:18px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;background-color:#fff;white-space:nowrap">
<xhtml:div>Storage</xhtml:div>
</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="815"
y="679"
font-family="Helvetica"
font-size="18"
text-anchor="middle"
id="text112">Storage</text>
</switch>
<path
d="M857.085 583.01c-.79.01-1.43.66-1.42 1.45v6.8h-9.59c-1.95 0-3.57 1.61-3.57 3.55v9.91h-6.87a1.44 1.44 0 0 0-1.28.71c-.27.45-.27 1.01 0 1.46.26.45.75.72 1.28.7h6.87v5.09h-6.87a1.44 1.44 0 0 0 0 2.88h6.87v5.09h-6.87a1.42 1.42 0 0 0-1.28.71c-.27.45-.27 1 0 1.45.26.45.75.72 1.28.71h6.87v5.09h-6.87a1.435 1.435 0 1 0 0 2.87h6.87v9.24c0 1.95 1.62 3.55 3.57 3.55h9.59v7.2c0 .51.28.99.72 1.25.45.25 1 .25 1.45 0 .44-.26.72-.74.72-1.25v-7.2h5.12v7.2c0 .51.27.99.72 1.25.45.25 1 .25 1.44 0 .45-.26.72-.74.72-1.25v-7.2h5.13v7.2c0 .51.27.99.72 1.25.44.25.99.25 1.44 0 .45-.26.72-.74.72-1.25v-7.2h5.12v7.2c0 .51.28.99.73 1.25.44.25.99.25 1.44 0 .44-.26.72-.74.72-1.25v-7.2h9.64c1.95 0 3.56-1.6 3.56-3.55v-9.24h6.8a1.435 1.435 0 1 0 0-2.87h-6.8v-5.09h6.8c.53.01 1.02-.26 1.28-.71.27-.45.27-1 0-1.45a1.42 1.42 0 0 0-1.28-.71h-6.8v-5.09h6.8a1.44 1.44 0 0 0 0-2.88h-6.8v-5.09h6.8c.53.02 1.02-.25 1.28-.7.27-.45.27-1.01 0-1.46a1.44 1.44 0 0 0-1.28-.71h-6.8v-9.91c0-1.94-1.61-3.55-3.56-3.55h-9.64v-6.8a1.433 1.433 0 0 0-1.47-1.45c-.79.01-1.43.66-1.42 1.45v6.8h-5.12v-6.8c.01-.39-.15-.76-.42-1.03a1.41 1.41 0 0 0-1.04-.42c-.8.01-1.43.66-1.42 1.45v6.8h-5.13v-6.8c.01-.39-.14-.76-.42-1.03-.27-.28-.65-.43-1.04-.42-.8.01-1.43.66-1.42 1.45v6.8h-5.12v-6.8c0-.39-.15-.76-.43-1.03-.27-.28-.65-.43-1.04-.42zm-11.01 11.12h46.14c.4 0 .68.28.68.68v45.91c0 .4-.28.68-.68.68h-46.14c-.41 0-.68-.28-.68-.68v-45.91c0-.4.27-.68.68-.68zm29.69 3.11c-.8 0-1.45.64-1.45 1.44 0 .79.65 1.43 1.45 1.43h10.6v10.68c-.01.53.26 1.01.71 1.28.45.26 1.01.26 1.46 0 .46-.27.73-.75.71-1.28v-12.11c0-.38-.15-.75-.42-1.02s-.64-.42-1.02-.42zm-25.51.06c-.8 0-1.44.64-1.44 1.44v11.99c0 .52.27.99.72 1.25.44.26.99.26 1.44 0 .45-.26.72-.73.72-1.25v-10.56h10.72c.53.02 1.02-.25 1.28-.7.27-.45.27-1.01 0-1.46a1.44 1.44 0 0 0-1.28-.71zm.03 25.84c-.79.01-1.43.66-1.42 1.46v12.11c0 .8.65 1.44 1.45 1.44h12.04a1.435 1.435 0 1 0 0-2.87h-10.6V624.6c0-.39-.15-.76-.42-1.04-.28-.27-.66-.43-1.05-.42zm37.56.06c-.8.01-1.43.66-1.42 1.46v10.56h-10.72a1.435 1.435 0 1 0 0 2.87h12.16c.38 0 .75-.15 1.02-.42s.42-.63.42-1.02v-11.99c.01-.39-.14-.77-.42-1.04-.27-.27-.65-.43-1.04-.42z"
stroke="#000"
stroke-width="2"
stroke-miterlimit="10"
pointer-events="none"
id="path116" />
<switch
transform="translate(-42.395 -1.5)"
id="switch120">
<foreignObject
style="overflow:visible;text-align:left"
pointer-events="none"
width="100%"
height="100%"
requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
<xhtml:div
style="display:flex;align-items:unsafe flex-start;justify-content:unsafe center;width:1px;height:1px;padding-top:661px;margin-left:911px">
<xhtml:div
style="box-sizing:border-box;font-size:0;text-align:center"
data-drawio-colors="color: rgb(0 0 0);">
<xhtml:div
style="display:inline-block;font-size:18px;font-family:Helvetica;color:#000;line-height:1.2;pointer-events:none;white-space:nowrap">
<xhtml:div>Logic</xhtml:div>
</xhtml:div>
</xhtml:div>
</xhtml:div>
</foreignObject>
<text
x="911"
y="679"
font-family="Helvetica"
font-size="18"
text-anchor="middle"
id="text118">Logic</text>
</switch>
<path
d="M557.803 369.38v-53.879h50.3v53.88z"
pointer-events="none"
style="stroke-width:1.69348"
id="path122" />
<path
d="M557.803 369.38v-2.428h50.3v2.429z"
fill-opacity=".3"
pointer-events="none"
style="stroke-width:1.69348"
id="path124" />
<path
d="M583.02 348.735c-4.159 0-7.411-3.37-7.411-7.509 0-4.447 3.621-7.543 7.176-7.543 4.762 0 7.511 3.986 7.511 7.424 0 4.413-3.437 7.628-7.276 7.628zm.15 5.867c6.724 0 12.877-5.781 12.877-13.58 0-7.014-5.617-13.257-13.312-13.257-6.305 0-12.877 5.354-12.877 13.53 0 7.03 5.5 13.307 13.312 13.307zm-12.625 5.268-5.784-5.952 2.364-2.429c-1.157-1.881-2.029-3.934-2.482-6.072h-3.32v-8.381l3.32-.017c.453-2.155 1.375-4.294 2.482-6.09l-2.364-2.394 5.784-5.935 2.381 2.411c1.962-1.248 3.94-2.07 5.935-2.514v-3.438h8.183v3.438c2.38.547 4.309 1.488 5.935 2.514l2.38-2.411 5.802 5.9-2.364 2.43a20.009 20.009 0 0 1 2.448 6.089h3.32v8.398h-3.32c-.553 2.446-1.442 4.43-2.482 6.09l2.381 2.411-5.784 5.952-2.364-2.428c-1.677 1.06-3.538 1.967-5.919 2.514l-.017 3.438h-8.198v-3.42a18.443 18.815 0 0 1-5.936-2.532z"
fill="#fff"
pointer-events="none"
style="stroke-width:1.69348"
id="path126" />
<path
d="M557.396 619.52v-53.88h50.3v53.88z"
pointer-events="none"
style="stroke-width:1.69348"
id="path128" />
<path
d="M557.396 619.52v-2.43h50.3v2.43z"
fill-opacity=".3"
pointer-events="none"
style="stroke-width:1.69348"
id="path130" />
<path
d="M582.614 598.874c-4.159 0-7.411-3.37-7.411-7.509 0-4.447 3.621-7.543 7.176-7.543 4.762 0 7.511 3.985 7.511 7.424 0 4.413-3.437 7.628-7.276 7.628zm.15 5.867c6.724 0 12.877-5.781 12.877-13.581 0-7.013-5.617-13.256-13.313-13.256-6.304 0-12.876 5.354-12.876 13.53 0 7.03 5.5 13.307 13.312 13.307zm-12.625 5.268-5.784-5.952 2.364-2.429c-1.157-1.881-2.03-3.934-2.482-6.072h-3.32v-8.381l3.32-.017c.453-2.156 1.375-4.294 2.482-6.09l-2.364-2.394 5.784-5.936 2.381 2.412c1.962-1.249 3.94-2.07 5.935-2.514v-3.438h8.183v3.438c2.38.547 4.309 1.488 5.935 2.514l2.38-2.412 5.802 5.901-2.364 2.43a20.009 20.009 0 0 1 2.448 6.089h3.32v8.398h-3.32c-.553 2.446-1.442 4.43-2.482 6.09l2.381 2.41-5.784 5.953-2.364-2.429c-1.677 1.06-3.538 1.967-5.919 2.515l-.017 3.438h-8.199v-3.421a18.443 18.815 0 0 1-5.935-2.532z"
fill="#fff"
pointer-events="none"
style="stroke-width:1.69348"
id="path132" />
<path
d="M558.209 876.561v-53.88h50.3v53.88z"
pointer-events="none"
style="stroke-width:1.69348"
id="path134" />
<path
d="M558.209 876.561v-2.428h50.3v2.428z"
fill-opacity=".3"
pointer-events="none"
style="stroke-width:1.69348"
id="path136" />
<path
d="M583.426 855.916c-4.158 0-7.411-3.37-7.411-7.509 0-4.447 3.621-7.543 7.176-7.543 4.762 0 7.511 3.985 7.511 7.424 0 4.413-3.437 7.628-7.276 7.628zm.15 5.867c6.724 0 12.877-5.781 12.877-13.581 0-7.013-5.616-13.256-13.312-13.256-6.305 0-12.877 5.354-12.877 13.53 0 7.03 5.5 13.307 13.313 13.307zm-12.625 5.268-5.784-5.952 2.364-2.429c-1.157-1.881-2.029-3.934-2.482-6.072h-3.32v-8.381l3.32-.017c.453-2.156 1.375-4.294 2.482-6.09l-2.364-2.394 5.784-5.936 2.381 2.412c1.962-1.249 3.94-2.07 5.936-2.514v-3.438h8.182v3.438c2.38.547 4.309 1.488 5.935 2.514l2.38-2.412 5.802 5.901-2.364 2.43a20.009 20.009 0 0 1 2.448 6.089h3.32v8.398h-3.32c-.553 2.446-1.442 4.43-2.481 6.09l2.38 2.41-5.784 5.953-2.364-2.429c-1.677 1.06-3.538 1.967-5.919 2.515l-.017 3.438h-8.198v-3.421a18.443 18.815 0 0 1-5.936-2.532z"
fill="#fff"
pointer-events="none"
style="stroke-width:1.69348"
id="path138" />
<path
d="m 366.50314,354.42598 11.39691,-13.02355 -9.68737,-9.10717 9.68737,-7.81206 -9.68737,-11.71809 17.66521,-20.50408 14.81597,16.59804 -13.67628,9.11753 7.97783,9.10717 -11.96675,7.81206 7.40799,7.15933 z"
fill="#ffd966"
stroke="#000000"
stroke-width="3.10825"
stroke-miterlimit="6"
pointer-events="none"
id="path116-7" />
</svg>
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/mediakeysession/index.md | ---
title: MediaKeySession
slug: Web/API/MediaKeySession
page-type: web-api-interface
browser-compat: api.MediaKeySession
---
{{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}}
The **`MediaKeySession`** interface of the [Encrypted Media Extensions API](/en-US/docs/Web/API/Encrypted_Media_Extensions_API) represents a context for message exchange with a content decryption module (CDM).
{{InheritanceDiagram}}
## Instance properties
- {{domxref("MediaKeySession.closed")}} {{ReadOnlyInline}}
- : Returns a {{jsxref("Promise")}} signaling when a `MediaKeySession` closes. This promise can only be fulfilled and is never rejected. Closing a session means that licenses and keys associated with it are no longer valid for decrypting media data.
- {{domxref("MediaKeySession.expiration")}} {{ReadOnlyInline}}
- : The time after which the keys in the current session can no longer be used to decrypt media data, or `NaN` if no such time exists. This value is determined by the CDM and measured in milliseconds since January 1, 1970, UTC. This value may change during a session lifetime, such as when an action triggers the start of a window.
- {{domxref("MediaKeySession.keyStatuses")}} {{ReadOnlyInline}}
- : Contains a reference to a read-only {{domxref("MediaKeyStatusMap")}} of the current session's keys and their statuses.
- {{domxref("MediaKeySession.sessionId")}} {{ReadOnlyInline}}
- : Contains a unique string generated by the CDM for the current media object and its associated keys or licenses.
### Events
- {{domxref("MediaKeySession.keystatuseschange_event", "keystatuseschange")}}
- : Fires when there has been a change in the keys in a session or their statuses.
- {{domxref("MediaKeySession.message_event", "message")}}
- : Fires when the content decryption module has generated a message for the session.
## Instance methods
- {{domxref("MediaKeySession.close()")}}
- : Returns a {{jsxref("Promise")}} after notifying the current media session is no longer needed and that the CDM should release any resources associated with this object and close it.
- {{domxref("MediaKeySession.generateRequest()")}}
- : Returns a {{jsxref("Promise")}} after generating a media request based on initialization data.
- {{domxref("MediaKeySession.load()")}}
- : Returns a {{jsxref("Promise")}} that resolves to a boolean value after loading data for a specified session object.
- {{domxref("MediaKeySession.remove()")}}
- : Returns a {{jsxref("Promise")}} after removing any session data associated with the current object.
- {{domxref("MediaKeySession.update()")}}
- : Returns a {{jsxref("Promise")}} after loading messages and licenses to the CDM.
## Examples
```js
// TBD
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediakeysession | data/mdn-content/files/en-us/web/api/mediakeysession/closed/index.md | ---
title: "MediaKeySession: closed property"
short-title: closed
slug: Web/API/MediaKeySession/closed
page-type: web-api-instance-property
browser-compat: api.MediaKeySession.closed
---
{{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}}
The `MediaKeySession.closed` read-only property returns a
{{jsxref('Promise')}} signaling when a {{domxref('MediaKeySession')}} closes. This
promise can only be fulfilled and is never rejected. Closing a session means that
licenses and keys associated with it are no longer valid for decrypting media data.
## Value
A {{jsxref("Promise")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediakeysession | data/mdn-content/files/en-us/web/api/mediakeysession/remove/index.md | ---
title: "MediaKeySession: remove() method"
short-title: remove()
slug: Web/API/MediaKeySession/remove
page-type: web-api-instance-method
browser-compat: api.MediaKeySession.remove
---
{{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}}
The `MediaKeySession.remove()` method returns a {{jsxref('Promise')}} after removing any session data associated with the current object.
## Syntax
```js-nolint
remove()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Return value
A {{jsxref('Promise')}} that resolves to a boolean indicating whether the load succeeded or failed.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediakeysession | data/mdn-content/files/en-us/web/api/mediakeysession/sessionid/index.md | ---
title: "MediaKeySession: sessionId property"
short-title: sessionId
slug: Web/API/MediaKeySession/sessionId
page-type: web-api-instance-property
browser-compat: api.MediaKeySession.sessionId
---
{{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}}
The **`MediaKeySession.sessionId`** is a read-only property
that contains a unique string generated by the content decryption module (CDM) for the
current media object and its associated keys or licenses.
## Value
A string.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediakeysession | data/mdn-content/files/en-us/web/api/mediakeysession/generaterequest/index.md | ---
title: "MediaKeySession: generateRequest() method"
short-title: generateRequest()
slug: Web/API/MediaKeySession/generateRequest
page-type: web-api-instance-method
browser-compat: api.MediaKeySession.generateRequest
---
{{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}}
The `MediaKeySession.generateRequest()` method returns a
{{jsxref('Promise')}} after generating a media request based on initialization data.
## Syntax
```js-nolint
generateRequest()
```
### Parameters
None.
### Return value
A {{jsxref('Promise')}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediakeysession | data/mdn-content/files/en-us/web/api/mediakeysession/keystatuses/index.md | ---
title: "MediaKeySession: keyStatuses property"
short-title: keyStatuses
slug: Web/API/MediaKeySession/keyStatuses
page-type: web-api-instance-property
browser-compat: api.MediaKeySession.keyStatuses
---
{{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}}
The **`MediaKeySession.keyStatuses`** read-only property
returns a reference to a read-only {{domxref('MediaKeyStatusMap')}} of the current
session's keys and their statuses.
## Value
A {{domxref('MediaKeyStatusMap')}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediakeysession | data/mdn-content/files/en-us/web/api/mediakeysession/update/index.md | ---
title: "MediaKeySession: update() method"
short-title: update()
slug: Web/API/MediaKeySession/update
page-type: web-api-instance-method
browser-compat: api.MediaKeySession.update
---
{{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}}
The `MediaKeySession.update()` method loads messages and licenses to the
CDM, and then returns a {{jsxref('Promise')}} .
## Syntax
```js-nolint
update(response)
```
### Parameters
- `response`
- : An instance that is either an {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, or a {{jsxref("DataView")}}.
### Return value
A {{jsxref('Promise')}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediakeysession | data/mdn-content/files/en-us/web/api/mediakeysession/load/index.md | ---
title: "MediaKeySession: load() method"
short-title: load()
slug: Web/API/MediaKeySession/load
page-type: web-api-instance-method
browser-compat: api.MediaKeySession.load
---
{{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}}
The `MediaKeySession.load()` method returns a {{jsxref('Promise')}} that
resolves to a boolean value after loading data for a specified session object.
## Syntax
```js-nolint
load(sessionId)
```
### Parameters
- `sessionId`
- : A unique string generated by the content description module for the current media
object and its associated keys or licenses.
### Return value
A {{jsxref('Promise')}} that resolves to a boolean indicating whether the load
succeeded or failed.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediakeysession | data/mdn-content/files/en-us/web/api/mediakeysession/message_event/index.md | ---
title: "MediaKeySession: message event"
short-title: message
slug: Web/API/MediaKeySession/message_event
page-type: web-api-event
browser-compat: api.MediaKeySession.message_event
---
{{APIRef("Encrypted Media Extensions")}}{{SecureContext_Header}}
The **`message`** event of the
{{domxref("MediaKeySession")}} interface fires when a message is generated by the
content decryption module.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("message", (event) => {});
onmessage = (event) => {};
```
## Event type
A {{domxref("MediaKeyMessageEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("MediaKeyMessageEvent")}}
## Event properties
- {{domxref("MediaKeyMessageEvent.message")}} {{ReadOnlyInline}}
- : Returns an {{jsxref("ArrayBuffer")}} with a message from the content decryption module. Messages vary by key system.
- {{domxref("MediaKeyMessageEvent.messageType")}} {{ReadOnlyInline}}
- : Indicates the type of message. May be one of `license-request`, `license-renewal`, `license-release`, or `individualization-request`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediakeysession | data/mdn-content/files/en-us/web/api/mediakeysession/keystatuseschange_event/index.md | ---
title: "MediaKeySession: keystatuseschange event"
short-title: keystatuseschange
slug: Web/API/MediaKeySession/keystatuseschange_event
page-type: web-api-event
browser-compat: api.MediaKeySession.keystatuseschange_event
---
{{APIRef("Encrypted Media Extensions")}}{{SecureContext_Header}}
The **`keystatuseschange`** event of the {{domxref("MediaKeySession")}} API fires when there has been a change in the keys or their statuses within a session.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("keystatuseschange", (event) => {});
onkeystatuseschange = (event) => {};
```
## Event type
An {{domxref("ExtendableEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("ExtendableEvent")}}
## Event properties
_Doesn't implement any specific properties, but inherits properties from its parent, {{domxref("Event")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediakeysession | data/mdn-content/files/en-us/web/api/mediakeysession/expiration/index.md | ---
title: "MediaKeySession: expiration property"
short-title: expiration
slug: Web/API/MediaKeySession/expiration
page-type: web-api-instance-property
browser-compat: api.MediaKeySession.expiration
---
{{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}}
The **`MediaKeySession.expiration`** read-only property returns
the time after which the keys in the current session can no longer be used to decrypt
media data, or NaN if no such time exists. This value is determined by the CDM and
measured in milliseconds since January 1, 1970, UTC. This value may change during a
session lifetime, such as when an action triggers the start of a window.
## Value
A number or NaN.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediakeysession | data/mdn-content/files/en-us/web/api/mediakeysession/close/index.md | ---
title: "MediaKeySession: close() method"
short-title: close()
slug: Web/API/MediaKeySession/close
page-type: web-api-instance-method
browser-compat: api.MediaKeySession.close
---
{{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}}
The `MediaKeySession.close()` method notifies that the current media session
is no longer needed, and that the content decryption module should release any resources
associated with this object and close it. Then, it returns a {{jsxref('Promise')}}.
## Syntax
```js-nolint
close()
```
### Parameters
None.
### Return value
A {{jsxref('Promise')}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/videotracklist/index.md | ---
title: VideoTrackList
slug: Web/API/VideoTrackList
page-type: web-api-interface
browser-compat: api.VideoTrackList
---
{{APIRef("HTML DOM")}}
The **`VideoTrackList`** interface is used to represent a list of the video tracks contained within a {{HTMLElement("video")}} element, with each track represented by a separate {{domxref("VideoTrack")}} object in the list.
Retrieve an instance of this object with {{domxref('HTMLMediaElement.videoTracks')}}. The individual tracks can be accessed using array syntax or functions such as {{jsxref("Array.forEach", "forEach()")}} for example.
{{InheritanceDiagram}}
## Instance properties
_This interface also inherits properties from its parent interface, {{domxref("EventTarget")}}._
- {{domxref("VideoTrackList.length", "length")}} {{ReadOnlyInline}}
- : The number of tracks in the list.
- {{domxref("VideoTrackList.selectedIndex", "selectedIndex")}} {{ReadOnlyInline}}
- : The index of the currently selected track, if any, or `−1` otherwise.
## Instance methods
_This interface also inherits methods from its parent interface, {{domxref("EventTarget")}}._
- {{domxref("VideoTrackList.getTrackById", "getTrackById()")}}
- : Returns the {{domxref("VideoTrack")}} found within the `VideoTrackList` whose {{domxref("VideoTrack.id", "id")}} matches the specified string. If no match is found, `null` is returned.
## Events
- {{domxref("VideoTrackList/addtrack_event", "addtrack")}}
- : Fired when a new video track has been added to the media element.
Also available via the `onaddtrack` property.
- {{domxref("VideoTrackList.change_event", "change")}}
- : Fired when a video track has been made active or inactive.
Also available via the `onchange` property.
- {{domxref("VideoTrackList/removetrack_event", "removetrack")}}
- : Fired when a new video track has been removed from the media element.
Also available via the `onremovetrack` property.
## Usage notes
In addition to being able to obtain direct access to the video tracks present on a media element, `VideoTrackList` lets you set event handlers on the {{domxref("VideoTrackList/addtrack_event", "addtrack")}} and {{domxref("VideoTrackList/removetrack_event", "removetrack")}} events, so that you can detect when tracks are added to or removed from the media element's stream.
## Examples
### Getting a media element's video track list
To get a media element's {{domxref("VideoTrackList")}}, use its {{domxref("HTMLMediaElement.videoTracks", "videoTracks")}} property.
```js
const videoTracks = document.querySelector("video").videoTracks;
```
### Monitoring track count changes
In this example, we have an app that displays information about the number of channels available. To keep it up to date, handlers for the {{domxref("VideoTrackList/addtrack_event", "addtrack")}} and {{domxref("VideoTrackList/removetrack_event", "removetrack")}} events are set up.
```js
videoTracks.onaddtrack = updateTrackCount;
videoTracks.onremovetrack = updateTrackCount;
function updateTrackCount(event) {
trackCount = videoTracks.length;
drawTrackCountIndicator(trackCount);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/videotracklist | data/mdn-content/files/en-us/web/api/videotracklist/length/index.md | ---
title: "VideoTrackList: length property"
short-title: length
slug: Web/API/VideoTrackList/length
page-type: web-api-instance-property
browser-compat: api.VideoTrackList.length
---
{{APIRef("HTML DOM")}}
The read-only **{{domxref("VideoTrackList")}}**
property **`length`** returns the number of entries in the
`VideoTrackList`, each of which is a {{domxref("VideoTrack")}} representing
one video track in the media element.
A value of 0 indicates that there are no
video tracks in the media.
## Value
A number indicating how many video tracks are included in the
`VideoTrackList`. Each track can be accessed by treating the
`VideoTrackList` as an array of objects of type {{domxref("VideoTrack")}}.
## Examples
This snippet gets the number of video tracks in the first {{HTMLElement("video")}}
element found in the {{Glossary("DOM")}} by {{domxref("Document.querySelector",
"querySelector()")}}.
```js
const videoElem = document.querySelector("video");
let numVideoTracks = 0;
if (videoElem.videoTracks) {
numVideoTracks = videoElem.videoTracks.length;
}
```
Note that this sample checks to be sure {{domxref("HTMLMediaElement.videoTracks")}} is
defined, to avoid failing on browsers without support for {{domxref("VideoTrack")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/videotracklist | data/mdn-content/files/en-us/web/api/videotracklist/addtrack_event/index.md | ---
title: "VideoTrackList: addtrack event"
short-title: addtrack
slug: Web/API/VideoTrackList/addtrack_event
page-type: web-api-event
browser-compat: api.VideoTrackList.addtrack_event
---
{{APIRef}}
The `addtrack` event is fired when a video track is added to a [`VideoTrackList`](/en-US/docs/Web/API/VideoTrackList).
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("addtrack", (event) => {});
onaddtrack = (event) => {};
```
## Event type
A {{domxref("TrackEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("TrackEvent")}}
## Event properties
_In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._
- {{domxref("TrackEvent.track", "track")}} {{ReadOnlyInline}}
- : The newly-added {{domxref("VideoTrack")}} the event is in reference to.
## Examples
Using `addEventListener()`:
```js
const videoElement = document.querySelector("video");
videoElement.videoTracks.addEventListener("addtrack", (event) => {
console.log(`Video track: ${event.track.label} added`);
});
```
Using the `onaddtrack` event handler property:
```js
const videoElement = document.querySelector("video");
videoElement.videoTracks.onaddtrack = (event) => {
console.log(`Video track: ${event.track.label} added`);
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- Related events: [`removetrack`](/en-US/docs/Web/API/VideoTrackList/removetrack_event), [`change`](/en-US/docs/Web/API/VideoTrackList/change_event)
- This event on [`AudioTrackList`](/en-US/docs/Web/API/AudioTrackList) targets: [`addtrack`](/en-US/docs/Web/API/AudioTrackList/addtrack_event)
- This event on [`MediaStream`](/en-US/docs/Web/API/MediaStream) targets: [`addtrack`](/en-US/docs/Web/API/MediaStream/addtrack_event)
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
| 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.