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
data/mdn-content/files/en-us/web/api/texttracklist/index.md
--- title: TextTrackList slug: Web/API/TextTrackList page-type: web-api-interface browser-compat: api.TextTrackList --- {{APIRef("HTML DOM")}} The **`TextTrackList`** interface is used to represent a list of the text tracks defined by the {{HTMLElement("track")}} element, with each track represented by a separate {{domxref("textTrack")}} object in the list. Retrieve an instance of this object with the {{domxref('HTMLMediaElement.textTracks', 'textTracks')}} property of an {{domxref('HTMLMediaElement')}} object. For a given {{domxref('HTMLMediaElement')}} object _media_, the individual tracks can be accessed using: - `media.TextTracks[n]`, to get the n-th text track from the object's list of text tracks - the `media.textTracks`.[`getTrackById()`](/en-US/docs/Web/API/TextTrackList/getTrackById) method {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties from its parent interface, {{domxref("EventTarget")}}._ - {{domxref("TextTrackList.length", "length")}} {{ReadOnlyInline}} - : The number of tracks in the list. ## Instance methods _This interface also inherits methods from its parent interface, {{domxref("EventTarget")}}._ - {{domxref("TextTrackList.getTrackById", "getTrackById()")}} - : Returns the {{domxref("TextTrack")}} found within the `TextTrackList` whose {{domxref("TextTrack.id", "id")}} matches the specified string. If no match is found, `null` is returned. ## Events - [`addtrack`](/en-US/docs/Web/API/TextTrackList/addtrack_event) - : Fired when a new text track has been added to the media element. Also available via the `onaddtrack` property. - [`change`](/en-US/docs/Web/API/TextTrackList/change_event) - : Fired when a text track has been made active or inactive. Also available via the `onchange` property. - [`removetrack`](/en-US/docs/Web/API/TextTrackList/removeTrack_event) - : Fired when a new text 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 text tracks present on a media element, `TextTrackList` lets you set event handlers on the {{domxref("TextTrackList/addtrack_event", "addtrack")}} and {{domxref("TextTrackList/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 video element's text track list To get a media element's `TextTrackList`, use its {{domxref("HTMLMediaElement.textTracks", "textTracks")}} property. ```js const textTracks = document.querySelector("video").textTracks; ``` ### 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("TextTrackList/addtrack_event", "addtrack")}} and {{domxref("TextTrackList/removetrack_event", "removetrack")}} events are set up. ```js textTracks.onaddtrack = updateTrackCount; textTracks.onremovetrack = updateTrackCount; function updateTrackCount(event) { trackCount = textTracks.length; drawTrackCountIndicator(trackCount); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/texttracklist
data/mdn-content/files/en-us/web/api/texttracklist/length/index.md
--- title: "TextTrackList: length property" short-title: length slug: Web/API/TextTrackList/length page-type: web-api-instance-property browser-compat: api.TextTrackList.length --- {{APIRef("HTML DOM")}} The read-only **{{domxref("TextTrackList")}}** property **`length`** returns the number of entries in the `TextTrackList`, each of which is a {{domxref("TextTrack")}} representing one track in the media element. A value of 0 indicates that there are no text tracks in the media. ## Value A number indicating how many text tracks are included in the `TextTrackList`. Each track can be accessed by treating the `TextTrackList` as an array of objects of type {{domxref("TextTrack")}}. ## Examples This snippet gets the number of text tracks in the first media element found in the {{Glossary("DOM")}} by {{domxref("Document.querySelector", "querySelector()")}}. ```js const mediaElem = document.querySelector("video, audio"); let numTextTracks = 0; if (mediaElem.textTracks) { numTextTracks = mediaElem.textTracks.length; } ``` Note that this sample checks to be sure {{domxref("HTMLMediaElement.textTracks")}} is defined, to avoid failing on browsers without support for {{domxref("TextTrack")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/texttracklist
data/mdn-content/files/en-us/web/api/texttracklist/addtrack_event/index.md
--- title: "TextTrackList: addtrack event" short-title: addtrack slug: Web/API/TextTrackList/addtrack_event page-type: web-api-event browser-compat: api.TextTrackList.addtrack_event --- {{APIRef}} The **`addtrack`** event is fired when a track is added to a [`TextTrackList`](/en-US/docs/Web/API/TextTrackList). ## 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 {{domxref("TextTrack")}} object to which the event refers. ## Examples Using `addEventListener()`: ```js const mediaElement = document.querySelector("video, audio"); mediaElement.textTracks.addEventListener("addtrack", (event) => { console.log(`Text track: ${event.track.label} added`); }); ``` Using the `onaddtrack` event handler property: ```js const mediaElement = document.querySelector("video, audio"); mediaElement.textTracks.onaddtrack = (event) => { console.log(`Text 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 [`VideoTrackList`](/en-US/docs/Web/API/VideoTrackList) targets: [`addtrack`](/en-US/docs/Web/API/VideoTrackList/addtrack_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
data/mdn-content/files/en-us/web/api/texttracklist
data/mdn-content/files/en-us/web/api/texttracklist/removetrack_event/index.md
--- title: "TextTrackList: removeTrack event" short-title: removeTrack slug: Web/API/TextTrackList/removeTrack_event page-type: web-api-event browser-compat: api.TextTrackList.removetrack_event --- {{APIRef}} The **`removetrack`** event is fired when a track is removed from a [`TextTrackList`](/en-US/docs/Web/API/TextTrackList). ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("removetrack", (event) => {}); onremovetrack = (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 {{domxref("TextTrack")}} object to which the event refers. ## Examples Using `addEventListener()`: ```js const mediaElement = document.querySelector("video, audio"); mediaElement.textTracks.addEventListener("removetrack", (event) => { console.log(`Text track: ${event.track.label} removed`); }); ``` Using the `onremovetrack` event handler property: ```js const mediaElement = document.querySelector("video, audio"); mediaElement.textTracks.onremovetrack = (event) => { console.log(`Text track: ${event.track.label} removed`); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: [`addtrack`](/en-US/docs/Web/API/VideoTrackList/addtrack_event), [`change`](/en-US/docs/Web/API/VideoTrackList/change_event) - This event on [`VideoTrackList`](/en-US/docs/Web/API/VideoTrackList) targets: [`removetrack`](/en-US/docs/Web/API/VideoTrackList/removetrack_event) - This event on [`AudioTrackList`](/en-US/docs/Web/API/AudioTrackList) targets: [`removetrack`](/en-US/docs/Web/API/AudioTrackList/removetrack_event) - This event on [`MediaStream`](/en-US/docs/Web/API/MediaStream) targets: [`removetrack`](/en-US/docs/Web/API/MediaStream/removetrack_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
data/mdn-content/files/en-us/web/api/texttracklist
data/mdn-content/files/en-us/web/api/texttracklist/change_event/index.md
--- title: "TextTrackList: change event" short-title: change slug: Web/API/TextTrackList/change_event page-type: web-api-event browser-compat: api.TextTrackList.change_event --- {{APIRef}} The **`change`** event is fired when a text track is made active or inactive, or a {{domxref('TextTrackList')}} is otherwise changed. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("change", (event) => {}); onchange = (event) => {}; ``` ## Event type A generic {{DOMxRef("Event")}} with no added properties. ## Examples Using `addEventListener()`: ```js const mediaElement = document.querySelectorAll("video, audio")[0]; mediaElement.textTracks.addEventListener("change", (event) => { console.log(`'${event.type}' event fired`); }); ``` Using the `onchange` event handler property: ```js const mediaElement = document.querySelector("video, audio"); mediaElement.textTracks.onchange = (event) => { console.log(`'${event.type}' event fired`); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: [`addtrack`](/en-US/docs/Web/API/VideoTrackList/addtrack_event), [`removetrack`](/en-US/docs/Web/API/VideoTrackList/removetrack_event) - This event on [`VideoTrackList`](/en-US/docs/Web/API/VideoTrackList) targets: [`change`](/en-US/docs/Web/API/VideoTrackList/change_event) - This event on [`AudioTrackList`](/en-US/docs/Web/API/AudioTrackList) targets: [`change`](/en-US/docs/Web/API/AudioTrackList/change_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
data/mdn-content/files/en-us/web/api/texttracklist
data/mdn-content/files/en-us/web/api/texttracklist/gettrackbyid/index.md
--- title: "TextTrackList: getTrackById() method" short-title: getTrackById() slug: Web/API/TextTrackList/getTrackById page-type: web-api-instance-method browser-compat: api.TextTrackList.getTrackById --- {{APIRef("HTML DOM")}} The **{{domxref("TextTrackList")}}** method **`getTrackById()`** returns the first {{domxref("TextTrack")}} object from the track list whose [`id`](/en-US/docs/Web/HTML/Global_attributes/id) matches the specified string. This lets you find a specified track if you know its ID string. ## Syntax ```js-nolint getTrackById(id) ``` ### Parameters - `id` - : A string indicating the ID of the track to locate within the track list. ### Return value A {{domxref("TextTrack")}} object indicating the first track found within the `TextTrackList` whose `id` matches the specified string. If no match is found, this method returns `null`. The tracks are searched in their natural order; that is, in the order defined by the media resource itself, or, if the resource doesn't define an order, the relative order in which the tracks are declared by the media resource. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmltablecaptionelement/index.md
--- title: HTMLTableCaptionElement slug: Web/API/HTMLTableCaptionElement page-type: web-api-interface browser-compat: api.HTMLTableCaptionElement --- {{ APIRef("HTML DOM") }} The **`HTMLTableCaptionElement`** interface provides special properties (beyond the regular {{domxref("HTMLElement")}} interface it also has available to it by inheritance) for manipulating table {{HTMLElement("caption")}} elements. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLTableCaptionElement.align")}} {{deprecated_inline}} - : A string which represents an enumerated attribute indicating alignment of the caption with respect to the table. ## Instance methods _No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}_. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML element implementing this interface: {{HTMLElement("caption")}}.
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/publickeycredential/index.md
--- title: PublicKeyCredential slug: Web/API/PublicKeyCredential page-type: web-api-interface browser-compat: api.PublicKeyCredential --- {{APIRef("Web Authentication API")}}{{securecontext_header}} The **`PublicKeyCredential`** interface provides information about a public key / private key pair, which is a credential for logging in to a service using an un-phishable and data-breach resistant asymmetric key pair instead of a password. It inherits from {{domxref("Credential")}}, and is part of the [Web Authentication API](/en-US/docs/Web/API/Web_Authentication_API) extension to the [Credential Management API](/en-US/docs/Web/API/Credential_Management_API). {{InheritanceDiagram}} > **Note:** This API is restricted to top-level contexts. Use from within an {{HTMLElement("iframe")}} element will not have any effect. ## Instance properties - {{domxref("PublicKeyCredential.authenticatorAttachment")}} {{ReadOnlyInline}} - : A string that indicates the mechanism by which the WebAuthn implementation is attached to the authenticator at the time the associated {{domxref("CredentialsContainer.create()","navigator.credentials.create()")}} or {{domxref("CredentialsContainer.get()","navigator.credentials.get()")}} call completes. - {{domxref("PublicKeyCredential.id")}} {{ReadOnlyInline}} - : Inherited from {{domxref("Credential")}} and overridden to be the [base64url encoding](/en-US/docs/Glossary/Base64) of {{domxref("PublicKeyCredential.rawId")}}. - {{domxref("PublicKeyCredential.rawId")}} {{ReadOnlyInline}} - : An {{jsxref("ArrayBuffer")}} that holds the globally unique identifier for this `PublicKeyCredential`. This identifier can be used to look up credentials for future calls to {{domxref("CredentialsContainer.get()","navigator.credentials.get()")}}. - {{domxref("PublicKeyCredential.response")}} {{ReadOnlyInline}} - : An instance of an {{domxref("AuthenticatorResponse")}} object. It is either of type {{domxref("AuthenticatorAttestationResponse")}} if the `PublicKeyCredential` was the results of a {{domxref("CredentialsContainer.create()","navigator.credentials.create()")}} call, or of type {{domxref("AuthenticatorAssertionResponse")}} if the `PublicKeyCredential` was the result of a {{domxref("CredentialsContainer.get()","navigator.credentials.get()")}} call. - `PublicKeyCredential.type` {{ReadOnlyInline}} - : Inherited from {{domxref("Credential")}}. Always set to `public-key` for `PublicKeyCredential` instances. ## Static methods - {{domxref("PublicKeyCredential.isConditionalMediationAvailable()")}} - : Returns a {{jsxref("Promise")}} which resolves to `true` if conditional mediation is available. - {{domxref("PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable_static", "PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()")}} - : Returns a {{jsxref("Promise")}} which resolves to `true` if an authenticator bound to the platform is capable of _verifying_ the user. - {{domxref("PublicKeyCredential.parseCreationOptionsFromJSON_static", "PublicKeyCredential.parseCreationOptionsFromJSON()")}} {{experimental_inline}} - : Convenience method for deserializing server-sent credential registration data when [registering a user with credentials](/en-US/docs/Web/API/Web_Authentication_API#creating_a_key_pair_and_registering_a_user). - {{domxref("PublicKeyCredential.parseRequestOptionsFromJSON_static", "PublicKeyCredential.parseRequestOptionsFromJSON()")}} {{experimental_inline}} - : Convenience method for deserializing server-sent credential request data when [authenticating a (registered) user](/en-US/docs/Web/API/Web_Authentication_API#authenticating_a_user). ## Instance methods - {{domxref("PublicKeyCredential.getClientExtensionResults()")}} - : If any extensions were requested, this method will return the results of processing those extensions. - {{domxref("PublicKeyCredential.toJSON()")}} {{experimental_inline}} - : Convenience method for creating a JSON string representation of a {{domxref("PublicKeyCredential")}} for sending to the server when [registering a user with credentials](/en-US/docs/Web/API/Web_Authentication_API#creating_a_key_pair_and_registering_a_user) and [authenticating a registered user](/en-US/docs/Web/API/Web_Authentication_API#authenticating_a_user). ## Examples ### Creating a new instance of PublicKeyCredential Here, we use {{domxref("CredentialsContainer.create()","navigator.credentials.create()")}} to generate a new credential. ```js const createCredentialOptions = { challenge: new Uint8Array([ 21, 31, 105 /* 29 more random bytes generated by the server */, ]), rp: { name: "Example CORP", id: "login.example.com", }, user: { id: new Uint8Array(16), name: "[email protected]", displayName: "Carina Anand", }, pubKeyCredParams: [ { type: "public-key", alg: -7, }, ], }; navigator.credentials .create({ createCredentialOptions }) .then((newCredentialInfo) => { const response = newCredentialInfo.response; const clientExtensionsResults = newCredentialInfo.getClientExtensionResults(); }) .catch((err) => { console.error(err); }); ``` ### Getting an existing instance of PublicKeyCredential Here, we fetch an existing credential from an authenticator, using {{domxref("CredentialsContainer.get()","navigator.credentials.get()")}}. ```js const requestCredentialOptions = { challenge: new Uint8Array([ /* bytes sent from the server */ ]), }; navigator.credentials .get({ requestCredentialOptions }) .then((credentialInfoAssertion) => { // send assertion response back to the server // to proceed with the control of the credential }) .catch((err) => { console.error(err); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The parent interface {{domxref("Credential")}}
0
data/mdn-content/files/en-us/web/api/publickeycredential
data/mdn-content/files/en-us/web/api/publickeycredential/response/index.md
--- title: "PublicKeyCredential: response property" short-title: response slug: Web/API/PublicKeyCredential/response page-type: web-api-instance-property browser-compat: api.PublicKeyCredential.response --- {{APIRef("Web Authentication API")}}{{securecontext_header}} The **`response`** read-only property of the {{domxref("PublicKeyCredential")}} interface is an {{domxref("AuthenticatorResponse")}} object which is sent from the authenticator to the user agent for the creation/fetching of credentials. The information contained in this response will be used by the relying party's server to verify the demand is legitimate. An `AuthenticatorResponse` is either: - an {{domxref("AuthenticatorAttestationResponse")}} (when the `PublicKeyCredential` is created via {{domxref("CredentialsContainer.create()")}}) - an {{domxref("AuthenticatorAssertionResponse")}} (when the `PublicKeyCredential` is obtained via {{domxref("CredentialsContainer.get()")}}). In order to validate the _creation_ of credentials, a relying party's server needs both: - this response - the extensions of the client (given by {{domxref("PublicKeyCredential.getClientExtensionResults()")}}) to validate the demand. > **Note:** When validating the fetching of existing credentials, the > whole `PublicKeyCredential` object and the client extensions are necessary > for the relying party's server. > **Note:** This property may only be used in top-level contexts and will > not be available in an {{HTMLElement("iframe")}} for example. ## Value An {{domxref("AuthenticatorResponse")}} object containing the data a relying party's script will receive and which should be sent to the relying party's server in order to validate the demand for creation or fetching. This object contains data from the client ({{domxref("AuthenticatorResponse/clientDataJSON")}}) and from the authenticator. ## Examples ```js const options = { challenge: new Uint8Array(16) /* from the server */, rp: { name: "Example CORP", id: "login.example.com", }, user: { id: new Uint8Array(16) /* from the server */, name: "[email protected]", displayName: "Carina Anand", }, pubKeyCredParams: [ { type: "public-key", alg: -7, }, ], }; navigator.credentials .create({ publicKey: options }) .then((pubKeyCredential) => { const response = pubKeyCredential.response; const clientExtResults = pubKeyCredential.getClientExtensionResults(); // Send response and client extensions to the server so that it can validate // and create credentials }) .catch((err) => { // Deal with any error }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/publickeycredential
data/mdn-content/files/en-us/web/api/publickeycredential/getclientextensionresults/index.md
--- title: "PublicKeyCredential: getClientExtensionResults() method" short-title: getClientExtensionResults() slug: Web/API/PublicKeyCredential/getClientExtensionResults page-type: web-api-instance-method browser-compat: api.PublicKeyCredential.getClientExtensionResults --- {{APIRef("Web Authentication API")}}{{securecontext_header}} The **`getClientExtensionResults()`** method of the {{domxref("PublicKeyCredential")}} interface returns a map between the identifiers of extensions requested during credential creation or authentication, and their results after processing by the user agent. During the creation or fetching of a `PublicKeyCredential` (via {{domxref("CredentialsContainer.create()","navigator.credentials.create()")}} and {{domxref("CredentialsContainer.get()","navigator.credentials.get()")}} respectively), it is possible to request "custom" processing by the client for different extensions, specified in the `publicKey` option's `extensions` property. You can find more information about requesting the different extensions in [Web Authentication extensions](/en-US/docs/Web/API/Web_Authentication_API/WebAuthn_extensions). > **Note:** `getClientExtensionResults()` only returns the results from extensions processed by the user agent (client). The results from extensions processed by the authenticator can be found in the [authenticator data](/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data) available in {{domxref("AuthenticatorAssertionResponse.authenticatorData")}}. ## Syntax ```js-nolint getClientExtensionResults() ``` ### Parameters None. ### Return value A {{jsxref("Map", "map")}}, with each entry being an extensions' identifier string as the key, and the output from the processing of the extension by the client as the value. ## Examples ```js const publicKey = { // Here are the extension "inputs" extensions: { appid: "https://accounts.example.com", }, allowCredentials: { id: "fgrt46jfgd...", transports: ["usb", "nfc"], type: "public-key", }, challenge: new Uint8Array(16) /* from the server */, }; navigator.credentials .get({ publicKey }) .then((publicKeyCred) => { const myResults = publicKeyCred.getClientExtensionResults(); // myResults will contain the output of processing the "appid" extension }) .catch((err) => { console.error(err); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} > **Note:** Extensions are optional and different browsers may recognize different extensions. Processing extensions is always optional for the client: if a browser does not recognize a given extension, it will just ignore it. For information on which extensions are supported by which browsers, see [Web Authentication extensions](/en-US/docs/Web/API/Web_Authentication_API/WebAuthn_extensions). ## See also - [The list of the currently defined extensions](https://www.w3.org/TR/webauthn/#sctn-defined-extensions) - {{domxref("AuthenticatorAssertionResponse.authenticatorData")}} which contains the result of the authenticator's extensions processing
0
data/mdn-content/files/en-us/web/api/publickeycredential
data/mdn-content/files/en-us/web/api/publickeycredential/isuserverifyingplatformauthenticatoravailable_static/index.md
--- title: "PublicKeyCredential: isUserVerifyingPlatformAuthenticatorAvailable() static method" short-title: isUserVerifyingPlatformAuthenticatorAvailable() slug: Web/API/PublicKeyCredential/isUserVerifyingPlatformAuthenticatorAvailable_static page-type: web-api-static-method browser-compat: api.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable_static --- {{APIRef("Web Authentication API")}}{{securecontext_header}} The **`isUserVerifyingPlatformAuthenticatorAvailable()`** static method of the {{domxref("PublicKeyCredential")}} interface returns a {{jsxref("Promise")}} which resolves to `true` if a user-verifying platform authenticator is present. A user-verifying platform authenticator is a kind of multi-factor authenticator that is part of the client device (it is generally not removable) and that involves an action from the user in order to identify them. Common user-verifying platform authenticators include: - Touch ID or Face ID (macOS and iOS) - Windows Hello (Windows) - Device unlock (fingerprint, face, PIN, etc.) on Android > **Note:** This method may only be used in top-level contexts and will not be available in an {{HTMLElement("iframe")}} for example. ## Syntax ```js-nolint PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} which resolves to a boolean value indicating whether or a not a user-verifying platform authenticator is available. > **Note:** In earlier versions of the specification, the boolean also > conveyed the consent of the user to disclose such an authenticator existed. ## Examples ```js PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() .then((available) => { if (available) { // We can proceed with the creation of a PublicKeyCredential // with this authenticator } else { // Use another kind of authenticator or a classical login/password // workflow } }) .catch((err) => { // Something went wrong console.error(err); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Windows Hello](https://docs.microsoft.com/windows-hardware/design/device-experiences/windows-hello) - [Web Authentication and Windows Hello - MSDN Guide](https://docs.microsoft.com/archive/microsoft-edge/legacy/developer/) and especially the [special considerations mentioning `isUserVerifyingPlatformAuthenticator()`](https://docs.microsoft.com/archive/microsoft-edge/legacy/developer/#special-considerations-for-windows-hello)
0
data/mdn-content/files/en-us/web/api/publickeycredential
data/mdn-content/files/en-us/web/api/publickeycredential/parserequestoptionsfromjson_static/index.md
--- title: "PublicKeyCredential: parseRequestOptionsFromJSON() static method" short-title: parseRequestOptionsFromJSON() slug: Web/API/PublicKeyCredential/parseRequestOptionsFromJSON_static page-type: web-api-static-method status: - experimental browser-compat: api.PublicKeyCredential.parseRequestOptionsFromJSON_static --- {{APIRef("Web Authentication API")}} {{SeeCompatTable}}{{securecontext_header}} The **`parseRequestOptionsFromJSON()`** static method of the {{domxref("PublicKeyCredential")}} interface converts a {{glossary("JSON type representation")}} into its corresponding [`publicKey` request credentials options object structure](/en-US/docs/Web/API/CredentialsContainer/get#publickey_object_structure). The method is a convenience function for converting information provided by a relying server to a web app in order to request an existing credential. ## Syntax ```js-nolint PublicKeyCredential.parseRequestOptionsFromJSON(options) ``` ### Parameters - `options` - : An object with the same structure as the Web Authentication API [`publicKey` request credentials options object](/en-US/docs/Web/API/CredentialsContainer/get#publickey_object_structure), but with [base64url](/en-US/docs/Glossary/Base64)-encoded strings used in place of buffer properties. ### Return value An object with the Web Authentication API [`publicKey` request credentials options object structure](/en-US/docs/Web/API/CredentialsContainer/get#publickey_object_structure). ### Exceptions - `EncodingError` {{domxref("DOMException")}} - : Thrown if any part of the `options` object cannot be converted into the [`publicKey` request credentials options object structure](/en-US/docs/Web/API/CredentialsContainer/get#publickey_object_structure). ## Description The Web Authentication process for [authenticating a (registered) user](/en-US/docs/Web/API/Web_Authentication_API#authenticating_a_user) involves a relying party server sending the web app information needed to find an existing credential, including details about the user identity, the relying party, a "challenge", and optionally where to look for the credential: for example on a local built-in authenticator, or on an external one over USB, BLE, and so on. The web app passes this information to an authenticator to find the credential, by calling [`navigator.credentials.get()`](/en-US/docs/Web/API/CredentialsContainer/get) with an argument that contains the server-supplied data in the [`publicKey` request credentials options object structure](/en-US/docs/Web/API/CredentialsContainer/get#publickey_object_structure). The specification does not define how the information needed for requesting a credential is sent. A convenient approach is for the server to encapsulate the information in a {{glossary("JSON type representation")}} of the [`publicKey` request credentials options object](/en-US/docs/Web/API/CredentialsContainer/get#publickey_object_structure) that mirrors its structure but encodes buffer properties such as the `challenge` as [base64url](/en-US/docs/Glossary/Base64) strings. This object can be serialized to a [JSON](/en-US/docs/Glossary/JSON) string, sent to the web app and deserialized, and then converted to the [`publicKey` request credentials options object structure](/en-US/docs/Web/API/CredentialsContainer/get#publickey_object_structure) using **`parseRequestOptionsFromJSON()`**. ## Examples When authorizing an already registered user, a relying party server will supply the web app with information about the requested credentials, the relying party, and a challenge. The code below defines this information in the form described in the [`options` parameter](#options) above: ```js const requestCredentialOptionsJSON = { challenge: new Uint8Array([139, 66, 181, 87, 7, 203, ...]), rpId: "acme.com", allowCredentials: [{ type: "public-key", id: new Uint8Array([64, 66, 25, 78, 168, 226, 174, ...]) }], userVerification: "required", } ``` Because this object only uses JSON data types, it can be serialized to JSON using [`JSON.stringify()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) and sent to the web app. ```js JSON.stringify(requestCredentialOptionsJSON); ``` The web app can deserialize the JSON string back to a `requestCredentialOptionsJSON` object (not shown). The **`parseRequestOptionsFromJSON()`** method is used to convert that object to the form that can be used in `navigator.credentials.get()`: ```js // Convert options to form used by get() const publicKey = PublicKeyCredential.parseRequestOptionsFromJSON( requestCredentialOptionsJSON, // JSON-type representation ); navigator.credentials .get({ publicKey }) .then((returnedCredentialInfo) => { // Handle the returned credential information here. }) .catch((err) => { console.error(err); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Authentication API](/en-US/docs/Web/API/Web_Authentication_API) - {{domxref("PublicKeyCredential.parseCreationOptionsFromJSON_static", "PublicKeyCredential.parseCreationOptionsFromJSON()")}}
0
data/mdn-content/files/en-us/web/api/publickeycredential
data/mdn-content/files/en-us/web/api/publickeycredential/authenticatorattachment/index.md
--- title: "PublicKeyCredential: authenticatorAttachment property" short-title: authenticatorAttachment slug: Web/API/PublicKeyCredential/authenticatorAttachment page-type: web-api-instance-property browser-compat: api.PublicKeyCredential.authenticatorAttachment --- {{APIRef("Web Authentication API")}}{{securecontext_header}} The **`authenticatorAttachment`** read-only property of the {{domxref("PublicKeyCredential")}} interface is a string that indicates the general category of authenticator used during the associated {{domxref("CredentialsContainer.create()","navigator.credentials.create()")}} or {{domxref("CredentialsContainer.get()","navigator.credentials.get()")}} call. ## Value A string, which will be one of the following values: - `"platform"` - : The authenticator is part of the device WebAuthn is running on (termed a **platform authenticator**), therefore WebAuthn will communicate with it using a transport available to that platform, such as a platform-specific API. A public key credential bound to a platform authenticator is called a **platform credential**. - `"cross-platform"` - : The authenticator is not a part of the device WebAuthn is running on (termed a **roaming authenticator** as it can roam between different devices), therefore WebAuthn will communicate with it using a cross-platform transport protocol such as Bluetooth or NFC. A public key credential bound to a roaming authenticator is called a **roaming credential**. ## Examples ```js const options = { challenge: new Uint8Array(26) /* from the server */, rp: { name: "Example CORP", id: "login.example.com", }, user: { id: new Uint8Array(26) /* To be changed for each user */, name: "[email protected]", displayName: "Carina Anand", }, pubKeyCredParams: [ { type: "public-key", alg: -7, }, ], }; navigator.credentials .create({ publicKey: options }) .then((pubKeyCredential) => { const attachment = pubKeyCredential.authenticatorAttachment; // Do something with authenticatorAttachment }) .catch((err) => { // Deal with any error }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/publickeycredential
data/mdn-content/files/en-us/web/api/publickeycredential/parsecreationoptionsfromjson_static/index.md
--- title: "PublicKeyCredential: parseCreationOptionsFromJSON() static method" short-title: parseCreationOptionsFromJSON() slug: Web/API/PublicKeyCredential/parseCreationOptionsFromJSON_static page-type: web-api-static-method status: - experimental browser-compat: api.PublicKeyCredential.parseCreationOptionsFromJSON_static --- {{APIRef("Web Authentication API")}} {{SeeCompatTable}}{{securecontext_header}} The **`parseCreationOptionsFromJSON()`** static method of the {{domxref("PublicKeyCredential")}} interface converts a {{glossary("JSON type representation")}} into its corresponding [`publicKey` create credentials options object structure](/en-US/docs/Web/API/CredentialsContainer/create#publickey_object_structure). The method is a convenience function for converting credential options information provided by a relying party server to the form that a web app can use to [create a credential](/en-US/docs/Web/API/Web_Authentication_API#creating_a_key_pair_and_registering_a_user). ## Syntax ```js-nolint PublicKeyCredential.parseCreationOptionsFromJSON(options) ``` ### Parameters - `options` - : An object with the same structure as the Web Authentication API [`publicKey` create credentials options object](/en-US/docs/Web/API/CredentialsContainer/create#publickey_object_structure), but with [base64url](/en-US/docs/Glossary/Base64)-encoded strings used in place of buffer properties. ### Return value An object with the Web Authentication API [`publicKey` create credentials options object structure](/en-US/docs/Web/API/CredentialsContainer/create#publickey_object_structure). ### Exceptions - `EncodingError` {{domxref("DOMException")}} - : Thrown if any part of the `options` object cannot be converted into the [`publicKey` create credentials options object structure](/en-US/docs/Web/API/CredentialsContainer/create#publickey_object_structure). ## Description The Web Authentication process for [creating a key pair and registering a user](/en-US/docs/Web/API/Web_Authentication_API#creating_a_key_pair_and_registering_a_user) involves a relying party server sending the web app information needed to create a credential, including details about the user identity, the relying party, and a "challenge". The web app passes this information to an authenticator to create the credential, by calling [`navigator.credentials.create()`](/en-US/docs/Web/API/CredentialsContainer/create) with an argument that contains the server-supplied data in the [`publicKey` create credentials options object structure](/en-US/docs/Web/API/CredentialsContainer/create#publickey_object_structure). The specification does not define how the information needed for creating a credential is sent. A convenient approach is for the server to encapsulate the information in a {{glossary("JSON type representation")}} of the [`publicKey` create credentials options object](/en-US/docs/Web/API/CredentialsContainer/create#publickey_object_structure) that mirrors its structure but encodes buffer properties such as the `challenge` and `user.id` as [base64url](/en-US/docs/Glossary/Base64) strings. This object can be serialized to a [JSON](/en-US/docs/Glossary/JSON) string, sent to the web app and deserialized, and then converted to the [`publicKey` create credentials options object structure](/en-US/docs/Web/API/CredentialsContainer/create#publickey_object_structure) using **`parseCreationOptionsFromJSON()`**. ## Examples When registering a new user, a relying party server will supply information about the expected credentials to the web app. The code below defines this information in the form described in the [`options` parameter](#options) above (taken from the ["getting an AuthenticatorAttestationResponse"](/en-US/docs/Web/API/AuthenticatorResponse#getting_an_authenticatorattestationresponse) in `AuthenticatorResponse`): ```js const createCredentialOptionsJSON = { challenge: "21, 31, 105, " /* 29 more random bytes generated by the server in this string */, rp: { name: "Example CORP", id: "login.example.com", }, user: { id: "16", name: "[email protected]", displayName: "Carina Anand", }, pubKeyCredParams: [ { type: "public-key", alg: -7, }, ], }; ``` Because this object only uses JSON data types, it can be serialized to JSON using [`JSON.stringify()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) and sent to the web app. ```js JSON.stringify(createCredentialOptionsJSON); ``` The web app can deserialize the JSON string back to a `createCredentialOptionsJSON` object (not shown). The **`parseCreationOptionsFromJSON()`** method is used to convert that object to the form that can be used in `navigator.credentials.create()`: ```js // Convert options to form used by create() const createCredentialOptions = PublicKeyCredential.parseCreationOptionsFromJSON( createCredentialOptionsJSON, // JSON-type representation ); navigator.credentials .create({ createCredentialOptions }) .then((newCredentialInfo) => { // Handle the new credential information here. }) .catch((err) => { console.error(err); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Authentication API](/en-US/docs/Web/API/Web_Authentication_API) - {{domxref("PublicKeyCredential.parseRequestOptionsFromJSON_static", "PublicKeyCredential.parseRequestOptionsFromJSON()")}} - {{domxref("PublicKeyCredential.toJSON()")}}
0
data/mdn-content/files/en-us/web/api/publickeycredential
data/mdn-content/files/en-us/web/api/publickeycredential/rawid/index.md
--- title: "PublicKeyCredential: rawId property" short-title: rawId slug: Web/API/PublicKeyCredential/rawId page-type: web-api-instance-property browser-compat: api.PublicKeyCredential.rawId --- {{APIRef("Web Authentication API")}}{{securecontext_header}} The **`rawId`** read-only property of the {{domxref("PublicKeyCredential")}} interface is an {{jsxref("ArrayBuffer")}} object containing the identifier of the credentials. The {{domxref("PublicKeyCredential.id")}} property is a [base64url encoded](/en-US/docs/Glossary/Base64) version of this identifier. > **Note:** This property may only be used in top-level contexts and will > not be available in an {{HTMLElement("iframe")}} for example. ## Value A {{jsxref("ArrayBuffer")}} containing the identifier of the credentials. This identifier is expected to be globally unique and is appointed for the current `PublicKeyCredential` and its associated {{domxref("AuthenticatorAssertionResponse")}}. ## Examples ```js const options = { challenge: new Uint8Array(26) /* from the server */, rp: { name: "Example CORP", id: "login.example.com", }, user: { id: new Uint8Array(26) /* To be changed for each user */, name: "[email protected]", displayName: "Carina Anand", }, pubKeyCredParams: [ { type: "public-key", alg: -7, }, ], }; navigator.credentials .create({ publicKey: options }) .then((pubKeyCredential) => { const rawId = pubKeyCredential.rawId; // Do something with rawId }) .catch((err) => { // Deal with any error }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/publickeycredential
data/mdn-content/files/en-us/web/api/publickeycredential/isconditionalmediationavailable/index.md
--- title: "PublicKeyCredential: isConditionalMediationAvailable() static method" short-title: isConditionalMediationAvailable() slug: Web/API/PublicKeyCredential/isConditionalMediationAvailable page-type: web-api-static-method browser-compat: api.PublicKeyCredential.isConditionalMediationAvailable_static --- {{APIRef("Web Authentication API")}}{{securecontext_header}} The **`isConditionalMediationAvailable()`** static method of the {{domxref("PublicKeyCredential")}} interface returns a {{jsxref("Promise")}} which resolves to `true` if conditional mediation is available. Conditional mediation, if available, results in any discovered credentials being presented to the user in a non-modal dialog box along with an indication of the origin requesting credentials. This is requested by including `mediation: 'conditional'` in your `get()` call. In practice, this means autofilling available credentials; you need to include `autocomplete="webauthn"` on your form fields so that they will show the WebAuthn sign-in options. A conditional `get()` call does not show the browser UI and remains pending until the user picks an account to sign-in with from available autofill suggestions: - If the user makes a gesture outside of the dialog, it closes without resolving or rejecting the Promise and without causing a user-visible error condition. - If the user selects a credential, that credential is returned to the caller. The prevent silent access flag (see {{domxref("CredentialsContainer.preventSilentAccess()")}}) is treated as being `true` regardless of its actual value: the conditional behavior always involves user mediation of some sort if applicable credentials are discovered. > **Note:** If no credentials are discovered, the non-modal dialog will not be visible, and the user agent can prompt the user to take action in a way that depends on the type of credential (for example, to insert a device containing credentials). ## Syntax ```js-nolint isConditionalMediationAvailable() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} which resolves to a boolean value indicating whether or not conditional mediation is available. ## Examples Before invoking a conditional WebAuthn API call, check if: - The browser supports the Web Authentication API. - The browser supports WebAuthn conditional UI. ```js // Availability of `window.PublicKeyCredential` means WebAuthn is usable. if ( window.PublicKeyCredential && PublicKeyCredential.isConditionalMediationAvailable ) { // Check if conditional mediation is available. const isCMA = await PublicKeyCredential.isConditionalMediationAvailable(); if (isCMA) { // Call WebAuthn authentication const publicKeyCredentialRequestOptions = { // Server generated challenge challenge: ****, // The same RP ID as used during registration rpId: "example.com", }; const credential = await navigator.credentials.get({ publicKey: publicKeyCredentialRequestOptions, signal: abortController.signal, // Specify 'conditional' to activate conditional UI mediation: "conditional", }); } } ``` > **Note:** See [Sign in with a passkey through form autofill](https://web.dev/articles/passkey-form-autofill) for more information about using conditional mediation. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/publickeycredential
data/mdn-content/files/en-us/web/api/publickeycredential/id/index.md
--- title: "PublicKeyCredential: id property" short-title: id slug: Web/API/PublicKeyCredential/id page-type: web-api-instance-property browser-compat: api.PublicKeyCredential.id --- {{APIRef("Web Authentication API")}}{{securecontext_header}} The **`id`** read-only property of the {{domxref("PublicKeyCredential")}} interface is a string, inherited from {{domxref("Credential")}}, which represents the identifier of the current `PublicKeyCredential` instance. This property is a [base64url encoded](/en-US/docs/Glossary/Base64) version of {{domxref("PublicKeyCredential.rawId")}}. > **Note:** This property may only be used in top-level contexts and will > not be available in an {{HTMLElement("iframe")}} for example. ## Value A string being the [base64url encoded](/en-US/docs/Glossary/Base64) version of {{domxref("PublicKeyCredential.rawId")}}. ## Examples ```js const publicKey = { challenge: new Uint8Array(26) /* this actually is given from the server */, rp: { name: "Example CORP", id: "login.example.com", }, user: { id: new Uint8Array(26) /* To be changed for each user */, name: "[email protected]", displayName: "Carina Anand", }, pubKeyCredParams: [ { type: "public-key", alg: -7, }, ], }; navigator.credentials .create({ publicKey }) .then((newCredentialInfo) => { const id = newCredentialInfo.id; // Do something with the id // send attestation response and client extensions // to the server to proceed with the registration // of the credential }) .catch((err) => { console.error(err); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Credential.id")}}
0
data/mdn-content/files/en-us/web/api/publickeycredential
data/mdn-content/files/en-us/web/api/publickeycredential/tojson/index.md
--- title: "PublicKeyCredential: toJSON() method" short-title: toJSON() slug: Web/API/PublicKeyCredential/toJSON page-type: web-api-instance-method status: - experimental browser-compat: api.PublicKeyCredential.toJSON --- {{APIRef("Web Authentication API")}} {{SeeCompatTable}}{{securecontext_header}} The **`toJSON()`** method of the {{domxref("PublicKeyCredential")}} interface returns a {{glossary("JSON type representation")}} of a {{domxref("PublicKeyCredential")}}. The properties of the returned object depend on whether the credential is returned by [`navigator.credentials.create()`](/en-US/docs/Web/API/CredentialsContainer/create) when [creating a key pair and registering a user](/en-US/docs/Web/API/Web_Authentication_API#creating_a_key_pair_and_registering_a_user), or [`navigator.credentials.get()`](/en-US/docs/Web/API/CredentialsContainer/get) when [authenticating a user](/en-US/docs/Web/API/Web_Authentication_API#authenticating_a_user). This method is automatically invoked when web app code calls [`JSON.stringify()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) to serialize a {{domxref("PublicKeyCredential")}} so that it can be sent to relying party server when registering or authenticating a user. It not intended to be called directly in web app code. ## Syntax ```js-nolint toJSON() ``` ### Parameters None. ### Return value A {{glossary("JSON type representation")}} of a [`PublicKeyCredential`](/en-US/docs/Web/API/PublicKeyCredential) object. The included properties depend on whether the credential was returned by [`navigator.credentials.create()`](/en-US/docs/Web/API/CredentialsContainer/create) on registration, or [`navigator.credentials.get()`](/en-US/docs/Web/API/CredentialsContainer/get) when authenticating a user. The values and types of included properties are the same as for [`PublicKeyCredential`](/en-US/docs/Web/API/PublicKeyCredential), with the exception that [base64url](/en-US/docs/Glossary/Base64)-encoded strings are used in place of buffer properties. The object properties are: - `id` - : The value returned by {{domxref("PublicKeyCredential.id")}}. - `rawId` - : A [base64url](/en-US/docs/Glossary/Base64)-encoded version of {{domxref("PublicKeyCredential.rawId")}}. - `authenticatorAttachment` {{optional_inline}} - : The value returned by {{domxref("PublicKeyCredential.authenticatorAttachment")}}. - `type` - : The string `"public-key"`. - `clientExtensionResults` - : An array contaning [base64url](/en-US/docs/Glossary/Base64)-encoded versions of the values returned by {{domxref("PublicKeyCredential.getClientExtensionResults()")}}. - `response` - : The response property object depends on whether the credentials are returned following a registration or authentication operation. - When registering a new user `response` will be a JSON-type representation of {{domxref("AuthenticatorAttestationResponse")}} where buffer values have been [base64url](/en-US/docs/Glossary/Base64) encoded. - When authenticating a user the returned value will be a JSON-type representation version of {{domxref("AuthenticatorAssertionResponse")}} where buffer values have been [base64url](/en-US/docs/Glossary/Base64) encoded. ## Examples When registering a new user, a relying party server will supply information about the expected credentials to the web app. The web app calls [`navigator.credentials.create()`](/en-US/docs/Web/API/CredentialsContainer/create) with the received information (`createCredentialOptions` below), which returns a promise that fulfills with the new credential (a {{domxref("PublicKeyCredential")}}). ```js const newCredentialInfo = await navigator.credentials.create({ createCredentialOptions, }); ``` The web app then serializes the returned credential using `JSON.stringify()` (which in turn calls `toJSON()`) and posts it back to the server. ```js const registration_url = "https://example.com/registration"; const apiRegOptsResp = await fetch(registration_url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(newCredentialInfo), //Calls newCredentialInfo.toJSON }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Authentication API](/en-US/docs/Web/API/Web_Authentication_API) - {{domxref("PublicKeyCredential.parseCreationOptionsFromJSON_static", "PublicKeyCredential.parseCreationOptionsFromJSON()")}} - {{domxref("PublicKeyCredential.parseRequestOptionsFromJSON_static", "PublicKeyCredential.parseRequestOptionsFromJSON()")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgrect/index.md
--- title: SVGRect slug: Web/API/SVGRect page-type: web-api-interface browser-compat: api.SVGRect --- {{APIRef("SVG")}} The **`SVGRect`** represents a rectangle. Rectangles consist of an `x` and `y` coordinate pair identifying a minimum `x` value, a minimum `y` value, and a `width` and `height`, which are constrained to be non-negative. An **`SVGRect`** object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. ## Instance properties - {{domxref("SVGRect.x")}} - : The exact effect of this coordinate depends on each element. If the attribute is not specified, the effect is as if a value of `0` were specified. - {{domxref("SVGRect.y")}} - : The exact effect of this coordinate depends on each element. If the attribute is not specified, the effect is as if a value of `0` were specified. - {{domxref("SVGRect.width")}} - : This represents the width of the rectangle. A value that is negative results to an error. A value of `0` disables rendering of the element - {{SVGAttr("SVGRect.height")}} - : This represents the height of the rectangle. A value that is negative results to an error. A value of `0` disables rendering of the element. ## Instance methods None. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/svgrect
data/mdn-content/files/en-us/web/api/svgrect/the__x__property/index.md
--- title: "SVGRect: x property" short-title: x slug: Web/API/SVGRect/The__X__property page-type: web-api-instance-property --- {{APIRef("SVG")}} The [x](https://svgwg.org/svg2-draft/geometry.html#XProperty) property describes the horizontal coordinate of the position of the element. ## Usage context <table class="no-markdown"> <thead> <tr> <th>Name</th> <th>x</th> </tr> </thead> <tbody> <tr> <td>Value</td> <td> <a href="https://www.w3.org/TR/css3-values/#lengths">&#x3C;length></a > | <a href="https://www.w3.org/TR/css3-values/#percentages" >&#x3C;percentage></a > </td> </tr> <tr> <td>Initial</td> <td>0</td> </tr> <tr> <td>Applies to</td> <td> {{ SVGElement("mask") }}, '<a href="https://svgwg.org/svg2-draft/struct.html#SVGElement" >svg</a >', '<a href="https://svgwg.org/svg2-draft/shapes.html#RectElement" >rect</a >', '<a href="https://svgwg.org/svg2-draft/embedded.html#ImageElement" >image</a >', '<a href="https://svgwg.org/svg2-draft/embedded.html#ForeignObjectElement" >foreignObject</a >' </td> </tr> <tr> <td>Inherited</td> <td>no</td> </tr> <tr> <td>Percentages</td> <td> refer to the size of the current viewport (see <a href="https://svgwg.org/svg2-draft/coords.html#Units" >Units</a >) </td> </tr> <tr> <td>Media</td> <td>visual</td> </tr> <tr> <td>Computed value</td> <td>absolute length or percentage</td> </tr> <tr> <td>Animatable</td> <td>yes</td> </tr> </tbody> </table> ## Simple usage A \<coordinate> is a length in the user coordinate system that is the given distance from the origin of the user coordinate system along the relevant axis (the x-axis for X coordinates, the y-axis for Y coordinates). Its syntax is the same as that for [\<length>](https://www.w3.org/TR/SVG11/types.html#DataTypeLength). ```html <svg width="100" height="50" xmlns="http://www.w3.org/2000/svg"> <rect x="10" y="0" width="40" height="40" fill="blue"></rect> </svg> <svg width="100" height="50" xmlns="http://www.w3.org/2000/svg"> <rect x="40" y="0" width="40" height="40" fill="green"></rect> </svg> ``` {{EmbedLiveSample("Simple usage", "100%", "100")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/wakelocksentinel/index.md
--- title: WakeLockSentinel slug: Web/API/WakeLockSentinel page-type: web-api-interface browser-compat: api.WakeLockSentinel --- {{securecontext_header}}{{APIRef("Screen Wake Lock API")}} The **`WakeLockSentinel`** interface of the [Screen Wake Lock API](/en-US/docs/Web/API/Screen_Wake_Lock_API) can be used to monitor the status of the platform screen wake lock, and manually release the lock when needed. The screen wake lock prevents device screens from dimming or locking when an application needs to keep running. A screen wake lock is requested using the {{domxref('WakeLock.request()','navigator.wakeLock.request()')}} method, which returns a {{jsxref('Promise')}} that fulfills with a `WakeLockSentinel` object if the lock is granted. An acquired screen wake lock can be released manually via the {{domxref('WakeLockSentinel.release','release()')}} method, or automatically via the platform screen wake lock. The latter may occur if the document becomes inactive or loses visibility, if the device is low on power, or if the user turns on a power save mode. A released `WakeLockSentinel` cannot be re-used: a new sentinel must be be requested using {{domxref('WakeLock.request()','navigator.wakeLock.request()')}} if a new lock is needed. Releasing all `WakeLockSentinel` instances of a given wake lock type will cause the underlying platform wake lock to be released. An event is fired at the `WakeLockSentinel` if the platform lock is released, allowing applications to configure their UI, and re-request the lock if needed. {{InheritanceDiagram}} ## Instance properties _Also inherits properties from its parent interface, {{DOMxRef("EventTarget")}}._ - {{domxref("WakeLockSentinel.released", "released")}} {{ReadOnlyInline}} - : Returns a boolean indicating whether the `WakeLockSentinel` has been released. - {{domxref("WakeLockSentinel.type", "type")}} {{ReadOnlyInline}} - : Returns a string representation of the currently acquired `WakeLockSentinel` type. Return values are: - `screen`: A screen wake lock. Prevents devices from dimming or locking the screen. ## Instance methods _Also inherits methods from its parent interface, {{DOMxRef("EventTarget")}}._ - {{domxref('WakeLockSentinel.release()', 'release()')}} - : Releases the `WakeLockSentinel`, returning a {{jsxref("Promise")}} that is resolved once the sentinel has been successfully released. ## Events - {{domxref("WakeLockSentinel.release_event", "release")}} - : Fired when the {{domxref('WakeLockSentinel.release','release()')}} method is called or the wake lock is released by the user agent. ## Examples In this example, we create an asynchronous function that requests a `WakeLockSentinel`. Once the screen wake lock is acquired we listen for the `release` event, which can be used to give appropriate UI feedback. The sentinel can be acquired or released via appropriate interactions. ```js // create a reference for the wake lock let wakeLock = null; // create an async function to request a wake lock const requestWakeLock = async () => { try { wakeLock = await navigator.wakeLock.request("screen"); // listen for our release event wakeLock.addEventListener("release", () => { // if wake lock is released alter the UI accordingly }); } catch (err) { // if wake lock request fails - usually system related, such as battery } }; wakeLockOnButton.addEventListener("click", () => { requestWakeLock(); }); wakeLockOffButton.addEventListener("click", () => { if (wakeLock !== null) { wakeLock.release().then(() => { wakeLock = null; }); } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Stay awake with the Screen Wake Lock API](https://developer.chrome.com/docs/capabilities/web-apis/wake-lock/)
0
data/mdn-content/files/en-us/web/api/wakelocksentinel
data/mdn-content/files/en-us/web/api/wakelocksentinel/release_event/index.md
--- title: "WakeLockSentinel: release event" short-title: release slug: Web/API/WakeLockSentinel/release_event page-type: web-api-event browser-compat: api.WakeLockSentinel.release_event --- {{APIRef("Screen Wake Lock API")}}{{SecureContext_Header}} The **`release`** event of the {{domxref("WakeLockSentinel")}} interface is fired when the sentinel object's handle has been released. A {{domxref("WakeLockSentinel")}} can be released manually via the `release()` method, or automatically via the platform wake lock. This can happen if the document becomes inactive or looses visibility, if the device is low on power or the user turns on a power save mode. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("release", (event) => {}); onrelease = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples This example updates the UI if the wake lock is released. ```js wakeLock.addEventListener("release", () => { // if wake lock is released alter the UI accordingly statusElement.textContent = "Wake Lock has been released"; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Stay awake with the Screen Wake Lock API](https://developer.chrome.com/docs/capabilities/web-apis/wake-lock/)
0
data/mdn-content/files/en-us/web/api/wakelocksentinel
data/mdn-content/files/en-us/web/api/wakelocksentinel/release/index.md
--- title: "WakeLockSentinel: release() method" short-title: release() slug: Web/API/WakeLockSentinel/release page-type: web-api-instance-method browser-compat: api.WakeLockSentinel.release --- {{APIRef("Screen Wake Lock API")}}{{SecureContext_Header}} The **`release()`** method of the {{domxref("WakeLockSentinel")}} interface releases the {{domxref("WakeLockSentinel")}}, returning a {{jsxref("Promise")}} that is resolved once the sentinel has been successfully released. ## Syntax ```js-nolint release() ``` ### Parameters None. ### Return value Returns a {{jsxref("Promise")}} that resolves with `undefined`. ### Exceptions No exceptions are thrown. You should always listen for the {{domxref("WakeLockSentinel/release_event", "release")}} event to check if a wake lock has been released. ## Examples In this example, when a user clicks a button the {{domxref("WakeLockSentinel")}} is released. ```js wakeLockOffButton.addEventListener("click", () => { WakeLockSentinel.release(); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Stay awake with the Screen Wake Lock API](https://developer.chrome.com/docs/capabilities/web-apis/wake-lock/)
0
data/mdn-content/files/en-us/web/api/wakelocksentinel
data/mdn-content/files/en-us/web/api/wakelocksentinel/released/index.md
--- title: "WakeLockSentinel: released property" short-title: released slug: Web/API/WakeLockSentinel/released page-type: web-api-instance-property browser-compat: api.WakeLockSentinel.released --- {{APIRef("Screen Wake Lock API")}}{{SecureContext_Header}} The **`released`** read-only property of the {{domxref("WakeLockSentinel")}} interface returns a boolean that indicates whether a {{domxref("WakeLockSentinel")}} has been released. The `WakeLockSentinel` is released when the associated platform screen wake lock is revoked; afterwards `released` will always return `true`. If a subsequent screen wake lock is required, the application will need to request a new screen wake lock (the current `WakeLockSentinel` cannot be reused). ## Value A boolean value that is `false` until the {{domxref("WakeLockSentinel")}} has been released (either through a call to {{domxref("WakeLockSentinel.release()")}} or because the lock has been released automatically) and the {{domxref("WakeLockSentinel/release_event", "release")}} event has been emitted, after which it becomes `true` and no longer changes. ## Examples This example shows how the value of the `released` property changes within a {{domxref("WakeLockSentinel")}}'s life cycle. ```js const sentinel = await navigator.wakeLock.request("screen"); console.log(sentinel.released); // Logs "false" sentinel.onrelease = () => { console.log(sentinel.released); // Logs "true" }; await sentinel.release(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Stay awake with the Screen Wake Lock API](https://developer.chrome.com/docs/capabilities/web-apis/wake-lock/)
0
data/mdn-content/files/en-us/web/api/wakelocksentinel
data/mdn-content/files/en-us/web/api/wakelocksentinel/type/index.md
--- title: "WakeLockSentinel: type property" short-title: type slug: Web/API/WakeLockSentinel/type page-type: web-api-instance-property browser-compat: api.WakeLockSentinel.type --- {{APIRef("Screen Wake Lock API")}}{{SecureContext_Header}} The **`type`** read-only property of the {{domxref("WakeLockSentinel")}} interface returns a string representation of the currently acquired {{domxref("WakeLockSentinel")}} type. ## Value A string representation of the currently acquired wake lock type. Currently, the value is always `screen`, which represents a screen wake lock. It prevents devices from dimming or locking the screen. ## Examples This example shows an asynchronous function that acquires a {{domxref("WakeLockSentinel")}}, then logs the type to the console. ```js const requestWakeLock = async () => { wakeLock = await navigator.wakeLock.request("screen"); console.log(wakeLock.type); // logs 'screen' }; requestWakeLock(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Stay awake with the Screen Wake Lock API](https://developer.chrome.com/docs/capabilities/web-apis/wake-lock/)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/idledetector/index.md
--- title: IdleDetector slug: Web/API/IdleDetector page-type: web-api-interface status: - experimental browser-compat: api.IdleDetector --- {{securecontext_header}}{{APIRef("Idle Detection API")}}{{SeeCompatTable}} The **`IdleDetector`** interface of the {{domxref('idle_detection_api','Idle Detection API','','true')}} provides methods and events for detecting user activity on a device or screen. This interface requires a secure context. {{InheritanceDiagram}} ## Constructor - {{domxref("IdleDetector.IdleDetector", "IdleDetector()")}} {{Experimental_Inline}} - : Creates a new `IdleDetector` object. ## Instance properties - {{domxref("IdleDetector.userState")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a string indicating whether the users has interacted with either the screen or the device within the threshold provided to `start()`, one of `"active"` or `"idle"`. This attribute returns `null` before `start()` is called. - {{domxref("IdleDetector.screenState")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a string indicating whether the screen is locked, one of `"locked"` or `"unlocked"`. This attribute returns `null` before `start()` is called. ## Events - {{domxref("IdleDetector.change_event", "change")}} {{Experimental_Inline}} - : Called when the value of `userState` or `screenState` has changed. ## Static methods - [`IdleDetector.requestPermission()`](/en-US/docs/Web/API/IdleDetector/requestPermission_static) {{Experimental_Inline}} - : Returns a {{jsxref('Promise')}} that resolves when the user has chosen whether to grant the origin access to their idle state. Resolves with `"granted"` on acceptance and `"denied"` on refusal. ## Instance methods - {{domxref("IdleDetector.start()")}} {{Experimental_Inline}} - : Returns a `Promise` that resolves when the detector starts listening for changes in the user's idle state. `userState` and `screenState` are given initial values. This method takes an optional `options` object with the `threshold` in milliseconds where inactivity should be reported and `signal` for an `AbortSignal` to abort the idle detector. ## Examples The following example shows creating a detector and logging changes to the user's idle state. A button is used to get the necessary user activation before requesting permission. ```js const controller = new AbortController(); const signal = controller.signal; startButton.addEventListener("click", async () => { if ((await IdleDetector.requestPermission()) !== "granted") { console.error("Idle detection permission denied."); return; } try { const idleDetector = new IdleDetector(); idleDetector.addEventListener("change", () => { const userState = idleDetector.userState; const screenState = idleDetector.screenState; console.log(`Idle change: ${userState}, ${screenState}.`); }); await idleDetector.start({ threshold: 60_000, signal, }); console.log("IdleDetector is active."); } catch (err) { // Deal with initialization errors like permission denied, // running outside of top-level frame, etc. console.error(err.name, err.message); } }); stopButton.addEventListener("click", () => { controller.abort(); console.log("IdleDetector is stopped."); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/idledetector
data/mdn-content/files/en-us/web/api/idledetector/screenstate/index.md
--- title: "IdleDetector: screenState property" short-title: screenState slug: Web/API/IdleDetector/screenState page-type: web-api-instance-property status: - experimental browser-compat: api.IdleDetector.screenState --- {{securecontext_header}}{{APIRef("Idle Detection API")}}{{SeeCompatTable}} The **`screenState`** read-only property of the {{domxref("IdleDetector")}} interface returns a string indicating whether the screen is locked, one of `"locked"` or `"unlocked"`. ## Value Either `"locked"` or `"unlocked"` if {{domxref("IdleDetector.start()")}} has been called, or `null` otherwise. ## Examples In the following example, the `change` callback prints the status of `userState` and `screenState` to the console. ```js idleDetector.addEventListener("change", () => { const userState = idleDetector.userState; const screenState = idleDetector.screenState; console.log(`Idle change: ${userState}, ${screenState}.`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/idledetector
data/mdn-content/files/en-us/web/api/idledetector/start/index.md
--- title: "IdleDetector: start() method" short-title: start() slug: Web/API/IdleDetector/start page-type: web-api-instance-method status: - experimental browser-compat: api.IdleDetector.start --- {{securecontext_header}}{{APIRef("Idle Detection API")}}{{SeeCompatTable}} The **`start()`** method of the {{domxref("IdleDetector")}} interface returns a {{jsxref("Promise")}} that resolves when the detector starts listening for changes in the user's idle state. This method takes an optional `options` object with the `threshold` in milliseconds where inactivity should be reported and `signal` for an `AbortSignal` to abort the idle detector. ## Syntax ```js-nolint start() start(options) ``` ### Parameters - `options` {{optional_inline}} - : An object with the following properties: - `threshold` - : The minimum number of idle milliseconds before reporting should begin. - `signal` - : A reference to an {{domxref('AbortSignal')}} instance allowing you to abort idle detection. ### Return value A {{jsxref("Promise")}}. ### Exceptions - `NotAllowedError` {{domxref("DOMException")}} - : Use of this feature was blocked by a [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy). ## Examples The following example shows how to start idle detection using the `options` argument. It retrieves an instance of `AbortSignal` from an instance of {{domxref("AbortController")}}. ```js const controller = new AbortController(); const signal = controller.signal; await idleDetector.start({ threshold: 60_000, signal, }); console.log("IdleDetector is active."); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/idledetector
data/mdn-content/files/en-us/web/api/idledetector/userstate/index.md
--- title: "IdleDetector: userState property" short-title: userState slug: Web/API/IdleDetector/userState page-type: web-api-instance-property status: - experimental browser-compat: api.IdleDetector.userState --- {{securecontext_header}}{{APIRef("Idle Detection API")}}{{SeeCompatTable}} The **`userState`** read-only property of the {{domxref("IdleDetector")}} interface returns a string indicating whether the user has interacted with the device since the call to `start()`. ## Value Either `"active"` or `"idle"` if {{domxref("IdleDetector.start()")}} has been called, or `null` otherwise. ## Examples In the following example, the `change` callback prints the status of `userState` and `screenState` to the console. ```js idleDetector.addEventListener("change", () => { const userState = idleDetector.userState; const screenState = idleDetector.screenState; console.log(`Idle change: ${userState}, ${screenState}.`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/idledetector
data/mdn-content/files/en-us/web/api/idledetector/requestpermission_static/index.md
--- title: "IdleDetector: requestPermission() static method" short-title: requestPermission() slug: Web/API/IdleDetector/requestPermission_static page-type: web-api-static-method status: - experimental browser-compat: api.IdleDetector.requestPermission_static --- {{securecontext_header}}{{APIRef("Idle Detection API")}}{{SeeCompatTable}} The **`requestPermission()`** static method of the {{domxref("IdleDetector")}} interface returns a {{jsxref('Promise')}} that resolves with a string when the user has chosen whether to grant the origin access to their idle state. Resolves with `"granted"` on acceptance and `"denied"` on refusal. ## Syntax ```js-nolint IdleDetector.requestPermission() ``` ### Parameters None. ### Return value A `Promise` that resolves with `"granted"` or `"denied"`. ## Security [Transient user activation](/en-US/docs/Web/Security/User_activation) is required. The user has to interact with the page or a UI element in order for this feature to work. ## Examples The following example uses a `click` event on a button to trigger requesting the user for permission to detect when user is idle. ```js startButton.addEventListener("click", async () => { if ((await IdleDetector.requestPermission()) !== "granted") { console.error("Idle detection permission denied."); return; } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/idledetector
data/mdn-content/files/en-us/web/api/idledetector/change_event/index.md
--- title: "IdleDetector: change event" short-title: change slug: Web/API/IdleDetector/change_event page-type: web-api-event status: - experimental browser-compat: api.IdleDetector.change_event --- {{securecontext_header}}{{APIRef("Idle Detection API")}}{{SeeCompatTable}} The **`change`** event of the {{domxref("IdleDetector")}} interface fires when the value of `userState` or `screenState` has changed. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("change", (event) => {}); onchange = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Example In the following example, the `change` callback prints the status of `userState` and `screenState` to the console. ```js idleDetector.addEventListener("change", () => { const userState = idleDetector.userState; const screenState = idleDetector.screenState; console.log(`Idle change: ${userState}, ${screenState}.`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/idledetector
data/mdn-content/files/en-us/web/api/idledetector/idledetector/index.md
--- title: "IdleDetector: IdleDetector() constructor" short-title: IdleDetector() slug: Web/API/IdleDetector/IdleDetector page-type: web-api-constructor status: - experimental browser-compat: api.IdleDetector.IdleDetector --- {{securecontext_header}}{{APIRef("Idle Detection API")}}{{SeeCompatTable}} The **`IdleDetector()`** constructor creates a new {{domxref("IdleDetector")}} object which provides events indicating when the user is no longer interacting with their device or the screen has locked. ## Syntax ```js-nolint new IdleDetector() ``` ### Parameters None. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/authenticatorattestationresponse/index.md
--- title: AuthenticatorAttestationResponse slug: Web/API/AuthenticatorAttestationResponse page-type: web-api-interface browser-compat: api.AuthenticatorAttestationResponse --- {{APIRef("Web Authentication API")}}{{securecontext_header}} The **`AuthenticatorAttestationResponse`** interface of the [Web Authentication API](/en-US/docs/Web/API/Web_Authentication_API) is the result of a WebAuthn credential registration. It contains information about the credential that the server needs to perform WebAuthn assertions, such as its credential ID and public key. An `AuthenticatorAttestationResponse` object instance is available in the {{domxref("PublicKeyCredential.response", "response")}} property of a {{domxref("PublicKeyCredential")}} object returned by a successful {{domxref("CredentialsContainer.create()")}} call. This interface inherits from {{domxref("AuthenticatorResponse")}}. {{InheritanceDiagram}} > **Note:** This interface is restricted to top-level contexts. Use of its features from within an {{HTMLElement("iframe")}} element will not have any effect. ## Instance properties _Also inherits properties from its parent, {{domxref("AuthenticatorResponse")}}._ - {{domxref("AuthenticatorAttestationResponse.attestationObject")}} {{ReadOnlyInline}} - : An {{jsxref("ArrayBuffer")}} containing authenticator data and an attestation statement for a new key pair generated by the authenticator. - {{domxref("AuthenticatorResponse.clientDataJSON")}} {{ReadOnlyInline}} - : Inherited from {{domxref("AuthenticatorResponse")}}, this property contains the JSON-compatible serialization of the data passed from the browser to the authenticator in order to generate this credential β€” i.e., when {{domxref("CredentialsContainer.create()")}} is called with a `publicKey` option. This data contains some information from the options passed into the `create()` call, and some information controlled by the browser. ## Instance methods - {{domxref("AuthenticatorAttestationResponse.getAuthenticatorData()")}} - : Returns an {{jsxref("ArrayBuffer")}} containing the authenticator data contained within the {{domxref("AuthenticatorAttestationResponse.attestationObject")}} property. - {{domxref("AuthenticatorAttestationResponse.getPublicKey()")}} - : Returns an {{jsxref("ArrayBuffer")}} containing the DER `SubjectPublicKeyInfo` of the new credential (see [Subject Public Key Info](https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.7)), or `null` if this is not available. - {{domxref("AuthenticatorAttestationResponse.getPublicKeyAlgorithm()")}} - : Returns a number that is equal to a [COSE Algorithm Identifier](https://www.iana.org/assignments/cose/cose.xhtml#algorithms), representing the cryptographic algorithm used for the new credential. - {{domxref("AuthenticatorAttestationResponse.getTransports()")}} - : Returns an array of strings describing which transport methods (e.g., `usb`, `nfc`) are believed to be supported with the authenticator. The array may be empty if the information is not available. ## Examples See [Creating a public key credential using the WebAuthn API](/en-US/docs/Web/API/CredentialsContainer/create#creating_a_public_key_credential_using_the_webauthn_api) for a detailed example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("AuthenticatorAssertionResponse")}}: the interface for the type of response given when retrieving an existing credential - {{domxref("AuthenticatorResponse")}}: the parent interface
0
data/mdn-content/files/en-us/web/api/authenticatorattestationresponse
data/mdn-content/files/en-us/web/api/authenticatorattestationresponse/attestationobject/index.md
--- title: "AuthenticatorAttestationResponse: attestationObject property" short-title: attestationObject slug: Web/API/AuthenticatorAttestationResponse/attestationObject page-type: web-api-instance-property browser-compat: api.AuthenticatorAttestationResponse.attestationObject --- {{APIRef("Web Authentication API")}}{{securecontext_header}} The **`attestationObject`** property of the {{domxref("AuthenticatorAttestationResponse")}} interface returns an {{jsxref("ArrayBuffer")}} containing the new public key, as well as signature over the entire `attestationObject` with a private key that is stored in the authenticator when it is manufactured. As part of the {{domxref("CredentialsContainer.create()")}} call, an authenticator will create a new keypair as well as an `attestationObject` for that keypair. The public key that corresponds to the private key that has created the attestation signature is well known; however, there are various well known attestation public key chains for different ecosystems (for example, Android or TPM attestations). ## Value After decoding the [CBOR](https://datatracker.ietf.org/doc/html/rfc8949) encoded `ArrayBuffer`, the resulting JavaScript object will contain the following properties: - `authData` - : The [Authenticator data](/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data) for the operation. Note that in {{domxref("AuthenticatorAssertionResponse")}}, the `authenticatorData` is exposed as a property in a JavaScript object (see {{domxref("AuthenticatorAssertionResponse.authenticatorData")}}) while in {{domxref("AuthenticatorAttestationResponse")}}, the `authenticatorData` is a property in a [CBOR](https://datatracker.ietf.org/doc/html/rfc8949) map. The same {{domxref("AuthenticatorAssertionResponse.authenticatorData")}} field is used by both `AuthenticatorAttestationResponse` and by `AuthenticatorAssertionResponse`. When used in attestation, it contains an optional field, `attestedCredentialData`. This field is not included when used in the `AuthenticatorAssertionResponse`. The attestedCredentialData field contains the `credentialId` and `credentialPublicKey`. - `fmt` - : A text string that indicates the format of the attStmt. The [WebAuthn specification defines a number of formats](https://www.w3.org/TR/webauthn/#defined-attestation-formats); however, formats may also be defined in other specifications and registered in an [IANA registry](https://www.w3.org/TR/webauthn/#sctn-att-fmt-reg). Formats defined by WebAuthn are: - `"packed"` - `"tpm"` - `"android-key"` - `"android-safetynet"` - `"fido-u2f"` - `"none"` - `attStmt` - : An attestation statement that is of the format defined by `"fmt"`. For now, [see the WebAuthn specification for details on each format](https://www.w3.org/TR/webauthn/#defined-attestation-formats). ## Examples See [Creating a public key credential using the WebAuthn API](/en-US/docs/Web/API/CredentialsContainer/create#creating_a_public_key_credential_using_the_webauthn_api) for a detailed example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("CredentialsContainer.create()")}}: the method used to create a statement with a cryptographic `challenge` which signature by the authenticator is contained in `attStmt`, with the specified `attestation` transport option.
0
data/mdn-content/files/en-us/web/api/authenticatorattestationresponse
data/mdn-content/files/en-us/web/api/authenticatorattestationresponse/getpublickeyalgorithm/index.md
--- title: "AuthenticatorAttestationResponse: getPublicKeyAlgorithm() method" short-title: getPublicKeyAlgorithm() slug: Web/API/AuthenticatorAttestationResponse/getPublicKeyAlgorithm page-type: web-api-instance-method browser-compat: api.AuthenticatorAttestationResponse.getPublicKeyAlgorithm --- {{APIRef("Web Authentication API")}}{{securecontext_header}} The **`getPublicKeyAlgorithm()`** method of the {{domxref("AuthenticatorAttestationResponse")}} interface returns a number that is equal to a [COSE Algorithm Identifier](https://www.iana.org/assignments/cose/cose.xhtml#algorithms), representing the cryptographic algorithm used for the new credential. This is a convenience function created to allow easy access to the algorithm type. This information will need to be stored in order to verify future authentication operations (i.e., using {{domxref("CredentialsContainer.get()","navigator.credentials.get()")}}). ## Syntax ```js-nolint getPublicKeyAlgorithm() ``` ### Parameters None. ### Return value A number that is equal to a [COSE Algorithm Identifier](https://www.iana.org/assignments/cose/cose.xhtml#algorithms), representing the cryptographic algorithm used for the new credential. ## Examples See [Creating a public key credential using the WebAuthn API](/en-US/docs/Web/API/CredentialsContainer/create#creating_a_public_key_credential_using_the_webauthn_api) for a detailed example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/authenticatorattestationresponse
data/mdn-content/files/en-us/web/api/authenticatorattestationresponse/gettransports/index.md
--- title: "AuthenticatorAttestationResponse: getTransports() method" short-title: getTransports() slug: Web/API/AuthenticatorAttestationResponse/getTransports page-type: web-api-instance-method browser-compat: api.AuthenticatorAttestationResponse.getTransports --- {{APIRef("Web Authentication API")}}{{securecontext_header}} The **`getTransports()`** method of the {{domxref("AuthenticatorAttestationResponse")}} interface returns an array of strings describing the different transports which may be used by the authenticator. Such transports may be USB, NFC, BLE, internal (applicable when the authenticator is not removable from the device), or a hybrid approach. Sites should not interpret this array but instead store it along with the rest of the credential information. In a subsequent {{domxref("CredentialsContainer.get()", "navigator.credentials.get()")}} call, the `transports` value(s) specified inside `publicKey.allowCredentials` should be set to the stored array value. This provides a hint to the browser as to which types of authenticators to try when making an assertion for this credential. ## Syntax ```js-nolint getTransports() ``` ### Parameters None. ### Return value An {{jsxref("Array")}} of strings representing the different transports supported by the authenticator, in lexicographical order. Values may include: - `"ble"`: The authenticator may be used over [BLE (Bluetooth Low Energy)](https://en.wikipedia.org/wiki/Bluetooth_Low_Energy). - `"hybrid"`: The authenticator can be used over a combination of (often separate) data transport and proximity mechanisms. This supports, for example, authentication on a desktop computer using a smartphone. - `"internal"`: The authenticator is specifically bound to the client device (cannot be removed). - `"nfc"`: The authenticator may be used over [NFC (Near Field Communication)](https://en.wikipedia.org/wiki/Near-field_communication). - `"usb"`: The authenticator can be contacted over USB. ## Examples See [Creating a public key credential using the WebAuthn API](/en-US/docs/Web/API/CredentialsContainer/create#creating_a_public_key_credential_using_the_webauthn_api) for a detailed example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/authenticatorattestationresponse
data/mdn-content/files/en-us/web/api/authenticatorattestationresponse/getpublickey/index.md
--- title: "AuthenticatorAttestationResponse: getPublicKey() method" short-title: getPublicKey() slug: Web/API/AuthenticatorAttestationResponse/getPublicKey page-type: web-api-instance-method browser-compat: api.AuthenticatorAttestationResponse.getPublicKey --- {{APIRef("Web Authentication API")}}{{securecontext_header}} The **`getPublicKey()`** method of the {{domxref("AuthenticatorAttestationResponse")}} interface returns an {{jsxref("ArrayBuffer")}} containing the DER `SubjectPublicKeyInfo` of the new credential (see [Subject Public Key Info](https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.7)), or `null` if this is not available. This is a convenience function, created to allow easy access to the public key. This key will need to be stored in order to verify future authentication operations (i.e., using {{domxref("CredentialsContainer.get()","navigator.credentials.get()")}}). ## Syntax ```js-nolint getPublicKey() ``` ### Parameters None. ### Return value An {{jsxref("ArrayBuffer")}} containing the DER `SubjectPublicKeyInfo` of the new credential (see [Subject Public Key Info](https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.7)), or `null` if this is not available. ## Examples See [Creating a public key credential using the WebAuthn API](/en-US/docs/Web/API/CredentialsContainer/create#creating_a_public_key_credential_using_the_webauthn_api) for a detailed example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/authenticatorattestationresponse
data/mdn-content/files/en-us/web/api/authenticatorattestationresponse/getauthenticatordata/index.md
--- title: "AuthenticatorAttestationResponse: getAuthenticatorData() method" short-title: getAuthenticatorData() slug: Web/API/AuthenticatorAttestationResponse/getAuthenticatorData page-type: web-api-instance-method browser-compat: api.AuthenticatorAttestationResponse.getAuthenticatorData --- {{APIRef("Web Authentication API")}}{{securecontext_header}} The **`getAuthenticatorData()`** method of the {{domxref("AuthenticatorAttestationResponse")}} interface returns an {{jsxref("ArrayBuffer")}} containing the authenticator data contained within the {{domxref("AuthenticatorAttestationResponse.attestationObject")}} property. This is a convenience function, created to allow easy access to the authenticator data without having to write extra parsing code to extract it from the `attestationObject`. ## Syntax ```js-nolint getAuthenticatorData() ``` ### Parameters None. ### Return value An {{jsxref("ArrayBuffer")}} with a {{jsxref("ArrayBuffer.byteLength")}} of at least 37 bytes, which contains the data structure explained in [Authenticator data](/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data). This will be equivalent to the authenticator data contained within the {{domxref("AuthenticatorAttestationResponse.attestationObject")}} property. ## Examples See [Creating a public key credential using the WebAuthn API](/en-US/docs/Web/API/CredentialsContainer/create#creating_a_public_key_credential_using_the_webauthn_api) for a detailed example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/audioprocessingevent/index.md
--- title: AudioProcessingEvent slug: Web/API/AudioProcessingEvent page-type: web-api-interface status: - deprecated browser-compat: api.AudioProcessingEvent --- {{APIRef("Web Audio API")}}{{deprecated_header}} The `AudioProcessingEvent` interface of the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) represents events that occur when a {{domxref("ScriptProcessorNode")}} input buffer is ready to be processed. An `audioprocess` event with this interface is fired on a {{domxref("ScriptProcessorNode")}} when audio processing is required. During audio processing, the input buffer is read and processed to produce output audio data, which is then written to the output buffer. > **Warning:** This feature has been deprecated and should be replaced by an [`AudioWorklet`](/en-US/docs/Web/API/AudioWorklet). {{InheritanceDiagram}} ## Constructor - {{domxref("AudioProcessingEvent.AudioProcessingEvent", "AudioProcessingEvent()")}} {{Deprecated_Inline}} - : Creates a new `AudioProcessingEvent` object. ## Instance properties _Also implements the properties inherited from its parent, {{domxref("Event")}}_. - {{domxref("AudioProcessingEvent.playbackTime", "playbackTime")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : A double representing the time when the audio will be played, as defined by the time of {{domxref("BaseAudioContext/currentTime", "AudioContext.currentTime")}}. - {{domxref("AudioProcessingEvent.inputBuffer", "inputBuffer")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : An {{domxref("AudioBuffer")}} that is the buffer containing the input audio data to be processed. The number of channels is defined as a parameter `numberOfInputChannels`, of the factory method {{domxref("BaseAudioContext/createScriptProcessor", "AudioContext.createScriptProcessor()")}}. Note that the returned <code>AudioBuffer</code> is only valid in the scope of the event handler. - {{domxref("AudioProcessingEvent.outputBuffer", "outputBuffer")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : An {{domxref("AudioBuffer")}} that is the buffer where the output audio data should be written. The number of channels is defined as a parameter, <code>numberOfOutputChannels</code>, of the factory method {{domxref("BaseAudioContext/createScriptProcessor", "AudioContext.createScriptProcessor()")}}. Note that the returned <code>AudioBuffer</code> is only valid in the scope of the event handler. ## Examples ### Adding white noise using a script processor The following example shows how to use of a `ScriptProcessorNode` to take a track loaded via {{domxref("BaseAudioContext/decodeAudioData", "AudioContext.decodeAudioData()")}}, process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the {{domxref("AudioDestinationNode")}}. For each channel and each sample frame, the `scriptNode.onaudioprocess` function takes the associated `audioProcessingEvent` and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. > **Note:** For a full working example, see our [script-processor-node](https://mdn.github.io/webaudio-examples/script-processor-node/) > GitHub repo. (You can also access the [source code](https://github.com/mdn/webaudio-examples/tree/main/script-processor-node).) ```js const myScript = document.querySelector("script"); const myPre = document.querySelector("pre"); const playButton = document.querySelector("button"); // Create AudioContext and buffer source let audioCtx; async function init() { audioCtx = new AudioContext(); const source = audioCtx.createBufferSource(); // Create a ScriptProcessorNode with a bufferSize of 4096 and // a single input and output channel const scriptNode = audioCtx.createScriptProcessor(4096, 1, 1); // Load in an audio track using fetch() and decodeAudioData() try { const response = await fetch("viper.ogg"); const arrayBuffer = await response.arrayBuffer(); source.buffer = await audioCtx.decodeAudioData(arrayBuffer); } catch (err) { console.error( `Unable to fetch the audio file: ${name} Error: ${err.message}`, ); } // Give the node a function to process audio events scriptNode.addEventListener("audioprocess", (audioProcessingEvent) => { // The input buffer is the song we loaded earlier let inputBuffer = audioProcessingEvent.inputBuffer; // The output buffer contains the samples that will be modified // and played let outputBuffer = audioProcessingEvent.outputBuffer; // Loop through the output channels (in this case there is only one) for (let channel = 0; channel < outputBuffer.numberOfChannels; channel++) { let inputData = inputBuffer.getChannelData(channel); let outputData = outputBuffer.getChannelData(channel); // Loop through the 4096 samples for (let sample = 0; sample < inputBuffer.length; sample++) { // make output equal to the same as the input outputData[sample] = inputData[sample]; // add noise to each output sample outputData[sample] += (Math.random() * 2 - 1) * 0.1; } } }); source.connect(scriptNode); scriptNode.connect(audioCtx.destination); source.start(); // When the buffer source stops playing, disconnect everything source.addEventListener("ended", () => { source.disconnect(scriptNode); scriptNode.disconnect(audioCtx.destination); }); } // wire up play button playButton.addEventListener("click", () => { if (!audioCtx) { init(); } }); ``` ## Browser compatibility {{Compat}} ## See also - [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
0
data/mdn-content/files/en-us/web/api/audioprocessingevent
data/mdn-content/files/en-us/web/api/audioprocessingevent/playbacktime/index.md
--- title: "AudioProcessingEvent: playbackTime property" short-title: playbackTime slug: Web/API/AudioProcessingEvent/playbackTime page-type: web-api-instance-property status: - deprecated browser-compat: api.AudioProcessingEvent.playbackTime --- {{APIRef}}{{Deprecated_header}} The **`playbackTime`** read-only property of the {{domxref("AudioProcessingEvent")}} interface represents the time when the audio will be played. It is in the same coordinate system as the time used by the {{domxref("AudioContext")}}. ## Value A number that doesn't need to be an integer. ## Examples ```js const audioContext = new AudioContext(); const processor = audioContext.createScriptProcessor(256, 2, 2); processor.addEventListener("audioprocess", (event) => { const inputBuffer = event.inputBuffer; const outputBuffer = event.outputBuffer; for (let channel = 0; channel < outputBuffer.numberOfChannels; channel++) { const inputData = inputBuffer.getChannelData(channel); const outputData = outputBuffer.getChannelData(channel); // Log the corresponding time for this audio buffer console.log(`Received audio data to be played at ${event.playbackTime}`); // Process the audio data here for (let i = 0; i < outputBuffer.length; i++) { outputData[i] = inputData[i] * 0.5; } } }); processor.connect(audioContext.destination); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("AudioProcessingEvent")}} - {{domxref("ScriptProcessorNode")}}
0
data/mdn-content/files/en-us/web/api/audioprocessingevent
data/mdn-content/files/en-us/web/api/audioprocessingevent/outputbuffer/index.md
--- title: "AudioProcessingEvent: outputBuffer property" short-title: outputBuffer slug: Web/API/AudioProcessingEvent/outputBuffer page-type: web-api-instance-property status: - deprecated browser-compat: api.AudioProcessingEvent.outputBuffer --- {{APIRef}}{{Deprecated_header}} The **`outputBuffer`** read-only property of the {{domxref("AudioProcessingEvent")}} interface represents the output buffer of an audio processing event. The output buffer is represented by an {{domxref("AudioBuffer")}} object, which contains a collection of audio channels, each of which is an array of floating-point values representing the audio signal waveform encoded as a series of amplitudes. The number of channels and the length of each channel are determined by the channel count and buffer size properties of the `AudioBuffer`. ## Value An {{domxref("AudioBuffer")}} object. ## Examples In this example, a {{domxref("ScriptProcessorNode")}} is created with a buffer size of 256 samples, 2 input channels, and 2 output channels. When an {{domxref("ScriptProcessorNode/audioprocess_event", "audioprocess")}} event is fired, the input and output buffers are retrieved from the event object. The audio data in the input buffer is processed, and the result is written to the output buffer. In this case, the audio data is scaled down by a factor of 0.5. ```js const audioContext = new AudioContext(); const processor = audioContext.createScriptProcessor(256, 2, 2); processor.addEventListener("audioprocess", (event) => { const inputBuffer = event.inputBuffer; const outputBuffer = event.outputBuffer; for (let channel = 0; channel < outputBuffer.numberOfChannels; channel++) { const inputData = inputBuffer.getChannelData(channel); const outputData = outputBuffer.getChannelData(channel); // Process the audio data here for (let i = 0; i < outputBuffer.length; i++) { outputData[i] = inputData[i] * 0.5; } } }); processor.connect(audioContext.destination); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("AudioProcessingEvent.inputBuffer")}} - {{domxref("ScriptProcessorNode")}}
0
data/mdn-content/files/en-us/web/api/audioprocessingevent
data/mdn-content/files/en-us/web/api/audioprocessingevent/inputbuffer/index.md
--- title: "AudioProcessingEvent: inputBuffer property" short-title: inputBuffer slug: Web/API/AudioProcessingEvent/inputBuffer page-type: web-api-instance-property status: - deprecated browser-compat: api.AudioProcessingEvent.inputBuffer --- {{APIRef}}{{Deprecated_header}} The **`inputBuffer`** read-only property of the {{domxref("AudioProcessingEvent")}} interface represents the input buffer of an audio processing event. The input buffer is represented by an {{domxref("AudioBuffer")}} object, which contains a collection of audio channels, each of which is an array of floating-point values representing the audio signal waveform encoded as a series of amplitudes. The number of channels and the length of each channel are determined by the channel count and buffer size properties of the `AudioBuffer`. ## Value An {{domxref("AudioBuffer")}} object. ## Examples In this example, a {{domxref("ScriptProcessorNode")}} is created with a buffer size of 256 samples, 2 input channels, and 2 output channels. When an {{domxref("ScriptProcessorNode/audioprocess_event", "audioprocess")}} event is fired, the input and output buffers are retrieved from the event object. The audio data in the input buffer is processed, and the result is written to the output buffer. In this case, the audio data is scaled down by a factor of 0.5. ```js const audioContext = new AudioContext(); const processor = audioContext.createScriptProcessor(256, 2, 2); processor.addEventListener("audioprocess", (event) => { const inputBuffer = event.inputBuffer; const outputBuffer = event.outputBuffer; for (let channel = 0; channel < outputBuffer.numberOfChannels; channel++) { const inputData = inputBuffer.getChannelData(channel); const outputData = outputBuffer.getChannelData(channel); // Process the audio data here for (let i = 0; i < outputBuffer.length; i++) { outputData[i] = inputData[i] * 0.5; } } }); processor.connect(audioContext.destination); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("AudioProcessingEvent.outputBuffer")}} - {{domxref("ScriptProcessorNode")}}
0
data/mdn-content/files/en-us/web/api/audioprocessingevent
data/mdn-content/files/en-us/web/api/audioprocessingevent/audioprocessingevent/index.md
--- title: "AudioProcessingEvent: AudioProcessingEvent() constructor" short-title: AudioProcessingEvent() slug: Web/API/AudioProcessingEvent/AudioProcessingEvent page-type: web-api-constructor status: - deprecated browser-compat: api.AudioProcessingEvent.AudioProcessingEvent --- {{APIRef}}{{Deprecated_header}} The **`AudioProcessingEvent()`** constructor creates a new {{domxref("AudioProcessingEvent")}} object. > **Note:** Usually, this constructor is not directly called by your code, as the browser creates these objects itself and provides them to the event handler. ## Syntax ```js-nolint new AudioProcessingEvent(type, options) ``` ### Parameters - `type` - : A string with the name of the event. It is case-sensitive and browsers always set it to `audioprocess`. - `options` - : An object that has the following properties: - `playbackTime` - : A number representing the time when the audio will be played. - `inputBuffer` - : An {{domxref("AudioBuffer")}} containing the input audio data. - `outputBuffer` - : An {{domxref("AudioBuffer")}} where the output audio data will be written. ### Return value A new {{domxref("AudioProcessingEvent")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("AudioProcessingEvent")}} - {{domxref("ScriptProcessorNode")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/web_serial_api/index.md
--- title: Web Serial API slug: Web/API/Web_Serial_API page-type: web-api-overview status: - experimental browser-compat: api.Serial --- {{DefaultAPISidebar("Web Serial API")}}{{SecureContext_Header}}{{SeeCompatTable}} The **Web Serial API** provides a way for websites to read from and write to serial devices. These devices may be connected via a serial port, or be USB or Bluetooth devices that emulate a serial port. ## Concepts and Usage The Web Serial API is one of a set of APIs that allow websites to communicate with peripherals connected to a user's computer. It provides the ability to connect to devices that are required by the operating system to communicate via the serial API, rather than USB which can be accessed via the {{domxref("WebUSB API")}}, or input devices that can be accessed via {{domxref("WebHID API")}}. Examples of serial devices include 3D printers, and microcontrollers such as the [BBC micro:bit board](https://microbit.org/). ## Interfaces - {{domxref("Serial")}} {{Experimental_Inline}} - : Provides attributes and methods for finding and connecting to serial ports from a web page. - {{domxref("SerialPort")}} {{Experimental_Inline}} - : Provides access to a serial port on the host device. ## Extensions to other interfaces - {{domxref("Navigator.serial")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a {{domxref("Serial")}} object, which represents the entry point into the {{domxref("Web Serial API")}} to enable the control of serial ports. - {{domxref("WorkerNavigator.serial")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a {{domxref("Serial")}} object, which represents the entry point into the {{domxref("Web Serial API")}} to enable the control of serial ports. ## Examples The following examples demonstrate some of the functionality provided by the Web Serial API. ### Checking for available ports The following example shows how to check for available ports and allows the user to grant it permission to access additional ports. The `connect` and `disconnect` events let sites react when a device is connected or disconnected from the system. The {{domxref("Serial.getPorts()","getPorts()")}} method is then called to see connected ports that the site already has access to. If the site doesn't have access to any connected ports it has to wait until it has user activation to proceed. In this example we use a {{domxref("Element.click_event", "click")}} event handler on a button for this task. A filter is passed to {{domxref("Serial.requestPort()","requestPort()")}} with a USB vendor ID in order to limit the set of devices shown to the user to only USB devices built by a particular manufacturer. ```js navigator.serial.addEventListener("connect", (e) => { // Connect to `e.target` or add it to a list of available ports. }); navigator.serial.addEventListener("disconnect", (e) => { // Remove `e.target` from the list of available ports. }); navigator.serial.getPorts().then((ports) => { // Initialize the list of available ports with `ports` on page load. }); button.addEventListener("click", () => { const usbVendorId = 0xabcd; navigator.serial .requestPort({ filters: [{ usbVendorId }] }) .then((port) => { // Connect to `port` or add it to the list of available ports. }) .catch((e) => { // The user didn't select a port. }); }); ``` ### Reading data from a port The following example shows how to read data from a port. The outer loop handles non-fatal errors, creating a new reader until a fatal error is encountered and {{domxref("SerialPort.readable")}} becomes `null`. ```js while (port.readable) { const reader = port.readable.getReader(); try { while (true) { const { value, done } = await reader.read(); if (done) { // |reader| has been canceled. break; } // Do something with |value|... } } catch (error) { // Handle |error|... } finally { reader.releaseLock(); } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Read from and write to a serial port](https://developer.chrome.com/docs/capabilities/serial) - [Getting started with the Web Serial API](https://codelabs.developers.google.com/codelabs/web-serial#0)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/index.md
--- title: ServiceWorkerGlobalScope slug: Web/API/ServiceWorkerGlobalScope page-type: web-api-interface browser-compat: api.ServiceWorkerGlobalScope --- {{APIRef("Service Workers API")}} The **`ServiceWorkerGlobalScope`** interface of the [Service Worker API](/en-US/docs/Web/API/Service_Worker_API) represents the global execution context of a service worker. Developers should keep in mind that the ServiceWorker state is not persisted across the termination/restart cycle, so each event handler should assume it's being invoked with a bare, default global state. Once successfully registered, a service worker can and will be terminated when idle to conserve memory and processor power. An active service worker is automatically restarted to respond to events, such as {{domxref("ServiceWorkerGlobalScope.fetch_event", "fetch")}} or {{domxref("ServiceWorkerGlobalScope.message_event", "message")}}. Additionally, synchronous requests are not allowed from within a service worker β€” only asynchronous requests, like those initiated via the {{domxref("fetch()")}} method, can be used. This interface inherits from the {{domxref("WorkerGlobalScope")}} interface, and its parent {{domxref("EventTarget")}}. {{InheritanceDiagram}} ## Instance properties _This interface inherits properties from the {{domxref("WorkerGlobalScope")}} interface, and its parent {{domxref("EventTarget")}}._ - {{domxref("ServiceWorkerGlobalScope.clients")}} {{ReadOnlyInline}} - : Contains the {{domxref("Clients")}} object associated with the service worker. - {{domxref("ServiceWorkerGlobalScope.cookieStore")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a reference to the {{domxref("CookieStore")}} object associated with the service worker. - {{domxref("ServiceWorkerGlobalScope.registration")}} {{ReadOnlyInline}} - : Contains the {{domxref("ServiceWorkerRegistration")}} object that represents the service worker's registration. - {{domxref("ServiceWorkerGlobalScope.serviceWorker")}} {{ReadOnlyInline}} - : Contains the {{domxref("ServiceWorker")}} object that represents the service worker. ## Instance methods _This interface inherits methods from the {{domxref("WorkerGlobalScope")}} interface, and its parent {{domxref("EventTarget")}}._ - {{domxref("ServiceWorkerGlobalScope.skipWaiting()")}} - : Allows the current service worker registration to progress from waiting to active state while service worker clients are using it. ## Events Listen to this event using {{domxref("EventTarget/addEventListener()", "addEventListener()")}} or by assigning an event listener to the `oneventname` property of this interface. - {{domxref("ServiceWorkerGlobalScope/activate_event", "activate")}} - : Occurs when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active")}} worker. - {{domxref("ServiceWorkerGlobalScope/backgroundfetchabort_event", "backgroundfetchabort")}} {{Experimental_Inline}} - : Fired when a [background fetch](/en-US/docs/Web/API/Background_Fetch_API) operation has been canceled by the user or the app. - {{domxref("ServiceWorkerGlobalScope/backgroundfetchclick_event", "backgroundfetchclick")}} {{Experimental_Inline}} - : Fired when the user has clicked on the UI for a [background fetch](/en-US/docs/Web/API/Background_Fetch_API) operation. - {{domxref("ServiceWorkerGlobalScope/backgroundfetchfail_event", "backgroundfetchfail")}} {{Experimental_Inline}} - : Fired when at least one of the requests in a [background fetch](/en-US/docs/Web/API/Background_Fetch_API) operation has failed. - {{domxref("ServiceWorkerGlobalScope/backgroundfetchsuccess_event", "backgroundfetchsuccess")}} {{Experimental_Inline}} - : Fired when all of the requests in a [background fetch](/en-US/docs/Web/API/Background_Fetch_API) operation have succeeded. - {{domxref("ServiceWorkerGlobalScope/canmakepayment_event", "canmakepayment")}} {{Experimental_Inline}} - : Fired on a payment app's service worker to check whether it is ready to handle a payment. Specifically, it is fired when the merchant website calls {{domxref("PaymentRequest.PaymentRequest", "new PaymentRequest()")}}. - {{domxref("ServiceWorkerGlobalScope/contentdelete_event", "contentdelete")}} {{Experimental_Inline}} - : Occurs when an item is removed from the {{domxref("ContentIndex", "Content Index")}}. - {{domxref("ServiceWorkerGlobalScope/cookiechange_event", "cookiechange")}} {{Experimental_Inline}} - : Fired when a cookie change has occurred that matches the service worker's cookie change subscription list. - {{domxref("ServiceWorkerGlobalScope/fetch_event", "fetch")}} - : Occurs when a {{domxref("fetch()")}} is called. - {{domxref("ServiceWorkerGlobalScope/install_event", "install")}} - : Occurs when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.installing")}} worker. - {{domxref("ServiceWorkerGlobalScope/message_event", "message")}} - : Occurs when incoming messages are received. Controlled pages can use the {{domxref("MessagePort.postMessage()")}} method to send messages to service workers. - {{domxref("ServiceWorkerGlobalScope/messageerror_event", "messageerror")}} - : Occurs when incoming messages can't be deserialized. - {{domxref("ServiceWorkerGlobalScope/notificationclick_event", "notificationclick")}} - : Occurs when a user clicks on a displayed notification. - {{domxref("ServiceWorkerGlobalScope/notificationclose_event", "notificationclose")}} - : Occurs when a user closes a displayed notification. - {{domxref("ServiceWorkerGlobalScope/paymentrequest_event", "paymentrequest")}} {{Experimental_Inline}} - : Fired on a payment app when a payment flow has been initiated on the merchant website via the {{domxref("PaymentRequest.show()")}} method. - {{domxref("ServiceWorkerGlobalScope/sync_event", "sync")}} - : Triggered when a call to {{domxref("SyncManager.register")}} is made from a service worker client page. The attempt to sync is made either immediately if the network is available or as soon as the network becomes available. - {{domxref("ServiceWorkerGlobalScope/periodicsync_event", "periodicsync")}} {{Experimental_Inline}} - : Occurs at periodic intervals, which were specified when registering a {{domxref("PeriodicSyncManager")}}. - {{domxref("ServiceWorkerGlobalScope/push_event", "push")}} - : Occurs when a server push notification is received. - {{domxref("ServiceWorkerGlobalScope/pushsubscriptionchange_event", "pushsubscriptionchange")}} - : Occurs when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time). ## Examples This code snippet is from the [service worker prefetch sample](https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/prefetch/service-worker.js) (see [prefetch example live](https://googlechrome.github.io/samples/service-worker/prefetch/).) The {{domxref("ServiceWorkerGlobalScope.fetch_event", "onfetch")}} event handler listens for the `fetch` event. When fired, the code returns a promise that resolves to the first matching request in the {{domxref("Cache")}} object. If no match is found, the code fetches a response from the network. The code also handles exceptions thrown from the {{domxref("fetch()")}} operation. Note that an HTTP error response (e.g., 404) will not trigger an exception. It will return a normal response object that has the appropriate error code set. ```js self.addEventListener("fetch", (event) => { console.log("Handling fetch event for", event.request.url); event.respondWith( caches.match(event.request).then((response) => { if (response) { console.log("Found response in cache:", response); return response; } console.log("No response found in cache. About to fetch from network…"); return fetch(event.request).then( (response) => { console.log("Response from network is:", response); return response; }, (error) => { console.error("Fetching failed:", error); throw error; }, ); }), ); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) - [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker)
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/fetch_event/index.md
--- title: "ServiceWorkerGlobalScope: fetch event" short-title: fetch slug: Web/API/ServiceWorkerGlobalScope/fetch_event page-type: web-api-event browser-compat: api.ServiceWorkerGlobalScope.fetch_event --- {{APIRef("Service Workers API")}} The **`fetch`** event is fired in the service worker's global scope when the main app thread makes a network request. It enables the service worker to intercept network requests and send customized responses (for example, from a local cache). This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("fetch", (event) => {}); onfetch = (event) => {}; ``` ## Description The `fetch` event is fired in the service worker's global scope when the main app thread makes a network request. This includes not only explicit {{domxref("fetch()")}} calls from the main thread, but also implicit network requests to load pages and subresources (such as JavaScript, CSS, and images) made by the browser following page navigation. The event handler is passed a {{domxref("FetchEvent")}} object, which provides access to the request as a {{domxref("Request")}} instance. The `FetchEvent` also provides a {{domxref("FetchEvent.respondWith()", "respondWith()")}} method, that takes a {{domxref("Response")}} (or a `Promise` that resolves to a `Response`) as a parameter. This enables the service worker event handler to provide the response that is returned to the request in the main thread. For example, the service worker can return: - A locally cached response retrieved from the {{domxref("Cache")}} interface. - A response that the service worker synthesizes, using methods like {{domxref("Response.json()")}} or the {{domxref("Response.Response()", "Response()")}} constructor. - A network error, using the {{domxref("Response.error_static()", "Response.error()")}} method. This will cause the `fetch()` call to reject. The `respondWith()` method can only be called once for a given request. If multiple `fetch` event listeners are added, they will be called in the order they were registered until one of them calls `respondWith()`. The `respondWith()` method must be called synchronously: that is, you can't call it in a `then` handler. Typically, a `fetch` event handler will execute different strategies depending on features of the request such as its URL: ```js function strategy1() { return fetch("picnic.jpg"); } function strategy2() { return Response.error(); } const pattern1 = /^\/salamander/; const pattern2 = /^\/lizard/; self.addEventListener("fetch", (event) => { const url = new URL(event.request.url); if (pattern1.test(url.pathname)) { event.respondWith(strategy1()); } else if (pattern2.test(url.pathname)) { event.respondWith(strategy2()); } }); ``` If `respondWith()` is not called in the handler, then the user agent automatically makes the original network request. For example, in the code above, all requests that do not match `pattern1` or `pattern2` are made as if the service worker did not exist. ## Event type A {{domxref("FetchEvent")}}. ## Examples ### Cache falling back to network This `fetch` event handler first tries to find the response in the cache. If a response is found, it returns the cached response. Otherwise, it tries to fetch the resource from the network. ```js async function cacheThenNetwork(request) { const cachedResponse = await caches.match(request); if (cachedResponse) { console.log("Found response in cache:", cachedResponse); return cachedResponse; } console.log("Falling back to network"); return fetch(request); } self.addEventListener("fetch", (event) => { console.log(`Handling fetch event for ${event.request.url}`); event.respondWith(cacheThenNetwork(event.request)); }); ``` ### Cache only This `fetch` event handler implements a "cache only" policy for scripts and stylesheets. If the request's {{domxref("Request.destination", "destination")}} property is `"script"` or `"style"`, the handler only looks in the cache, returning an error if the response was not found. All other requests go through to the network. ```js async function cacheOnly(request) { const cachedResponse = await caches.match(request); if (cachedResponse) { console.log("Found response in cache:", cachedResponse); return cachedResponse; } return Response.error(); } self.addEventListener("fetch", (event) => { if ( event.request.destination === "script" || event.request.destination === "style" ) { event.respondWith(cacheOnly(event.request)); } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) - [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker) - {{domxref("fetch()")}} method - {{domxref("Request")}} interface - {{domxref("Response")}} interface
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/backgroundfetchclick_event/index.md
--- title: "ServiceWorkerGlobalScope: backgroundfetchclick event" short-title: backgroundfetchclick slug: Web/API/ServiceWorkerGlobalScope/backgroundfetchclick_event page-type: web-api-event status: - experimental browser-compat: api.ServiceWorkerGlobalScope.backgroundfetchclick_event --- {{APIRef("Background Fetch API")}}{{SeeCompatTable}} The **`backgroundfetchclick`** event of the {{domxref("ServiceWorkerGlobalScope")}} interface is fired when the user clicks on the UI that the browser provides to show the user the progress of the [background fetch](/en-US/docs/Web/API/Background_Fetch_API) operation. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("backgroundfetchclick", (event) => {}); onbackgroundfetchclick = (event) => {}; ``` ## Event type A {{domxref("BackgroundFetchEvent")}}. {{InheritanceDiagram("BackgroundFetchEvent")}} ## Event properties _Inherits properties from its parent, {{domxref("ExtendableEvent")}}._ - {{domxref("BackgroundFetchEvent.registration")}} - : Returns the {{domxref("BackgroundFetchRegistration")}} whose progress dialog the user clicked on. ## Description When a [background fetch](/en-US/docs/Web/API/Background_Fetch_API) operation starts, the browser shows a UI element to the user to indicate the progress of the operation. If the user clicks this element, the browser starts the service worker, if necessary, and fires the `backgroundfetchclick` event in the service worker's global scope. A common task for the handler in this situation is to open a window giving the user more details about the fetch operation. ## Examples ### Opening a window with more details This event handler uses the global {{domxref("ServiceWorkerGlobalScope.clients", "clients")}} property to open a window giving the user more details about the fetch. It opens a different window depending on whether the fetch has completed or not. ```js addEventListener("backgroundfetchclick", (event) => { const registration = event.registration; if (registration.result === "success") { clients.openWindow("/play-movie"); } else { clients.openWindow("/movie-download-progress"); } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Background Fetch API](/en-US/docs/Web/API/Background_Fetch_API)
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/backgroundfetchsuccess_event/index.md
--- title: "ServiceWorkerGlobalScope: backgroundfetchsuccess event" short-title: backgroundfetchsuccess slug: Web/API/ServiceWorkerGlobalScope/backgroundfetchsuccess_event page-type: web-api-event status: - experimental browser-compat: api.ServiceWorkerGlobalScope.backgroundfetchsuccess_event --- {{APIRef("Background Fetch API")}}{{SeeCompatTable}} The **`backgroundfetchsuccess`** event of the {{domxref("ServiceWorkerGlobalScope")}} interface is fired when a [background fetch](/en-US/docs/Web/API/Background_Fetch_API) operation has completed successfully: that is, when all network requests in the fetch have completed successfully. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("backgroundfetchsuccess", (event) => {}); onbackgroundfetchsuccess = (event) => {}; ``` ## Event type A {{domxref("BackgroundFetchUpdateUIEvent")}}. {{InheritanceDiagram("BackgroundFetchUpdateUIEvent")}} ## Event properties _Inherits properties from its parent, {{domxref("BackgroundFetchEvent")}}._ - {{domxref("BackgroundFetchUpdateUIEvent.updateUI()")}} - : Updates the UI of the element that the browser displays to show the progress of the fetch operation. ## Description When a [background fetch](/en-US/docs/Web/API/Background_Fetch_API) operation completes successfully (meaning that all individual network requests have completed successfully), the browser starts the service worker, if necessary, and fires the `backgroundfetchsuccess` event in the service worker's global scope. In the handler for this event, the service worker can retrieve and store the responses (for example, using the {{domxref("Cache")}} API). To access the response data, the service worker uses the event's {{domxref("BackgroundFetchEvent/registration", "registration")}} property. In the background fetch API, the browser shows a UI element to the user to indicate the progress of the operation. In the `backgroundfetchsuccess` handler, the service worker can update that UI to show that the operation has completed successfully. To do this, the handler calls the event's {{domxref("BackgroundFetchUpdateUIEvent/updateUI", "updateUI()")}} method, passing in a new title and/or icons. ## Examples ### Storing responses and updating UI This event handler stores all responses in the cache, and updates the UI. ```js addEventListener("backgroundfetchsuccess", (event) => { const registration = event.registration; event.waitUntil(async () => { // Open a cache const cache = await caches.open("movies"); // Get all the records const records = await registration.matchAll(); // Cache all responses const cachePromises = records.map(async (record) => { const response = await record.responseReady; await cache.put(record.request, response); }); // Wait for caching to finish await Promise.all(cachePromises); // Update the browser's UI event.updateUI({ title: "Move download complete" }); }); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Background Fetch API](/en-US/docs/Web/API/Background_Fetch_API)
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/messageerror_event/index.md
--- title: "ServiceWorkerGlobalScope: messageerror event" short-title: messageerror slug: Web/API/ServiceWorkerGlobalScope/messageerror_event page-type: web-api-event browser-compat: api.ServiceWorkerGlobalScope.messageerror_event --- {{APIRef("Service Workers API")}} The **`messageerror`** event of the {{domxref("ServiceWorkerGlobalScope")}} interface occurs when incoming messages can't be deserialized. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("messageerror", (event) => {}); onmessageerror = (event) => {}; ``` ## Event type An {{domxref("ExtendableMessageEvent")}}. Inherits from {{domxref("ExtendableEvent")}}. {{InheritanceDiagram("ExtendableMessageEvent")}} ## Event properties _Inherits properties from its parent, {{domxref("ExtendableEvent")}}_. - {{domxref("ExtendableMessageEvent.data")}} {{ReadOnlyInline}} - : Returns the event's data. It can be any data type. If dispatched in `messageerror` event, the property will be `null`. - {{domxref("ExtendableMessageEvent.origin")}} {{ReadOnlyInline}} - : Returns the origin of the {{domxref("Client")}} that sent the message. - {{domxref("ExtendableMessageEvent.lastEventId")}} {{ReadOnlyInline}} - : Represents, in [server-sent events](/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events), the last event ID of the event source. - {{domxref("ExtendableMessageEvent.source")}} {{ReadOnlyInline}} - : Returns a reference to the {{domxref("Client")}} object that sent the message. - {{domxref("ExtendableMessageEvent.ports")}} {{ReadOnlyInline}} - : Returns the array containing the {{domxref("MessagePort")}} objects representing the ports of the associated message channel. ## Examples In the below example a page gets a handle to the {{domxref("ServiceWorker")}} object via {{domxref("ServiceWorkerRegistration.active")}}, and then calls its `postMessage()` function. ```js // main.js if (navigator.serviceWorker) { navigator.serviceWorker.register("service-worker.js"); navigator.serviceWorker.addEventListener("message", (event) => { // event is a MessageEvent object console.log(`The service worker sent me a message: ${event.data}`); }); navigator.serviceWorker.ready.then((registration) => { registration.active.postMessage("Hi service worker"); }); } ``` The service worker can listen for the message deserialization error by listening to the `messageerror` event: ```js // service-worker.js self.addEventListener("messageerror", (event) => { // event is an ExtendableMessageEvent object console.error("Message deserialization failed"); }); ``` Alternatively, the script can listen for the message deserialization error using `onmessageerror`: ```js // service-worker.js self.onmessageerror = (event) => { // event is an ExtendableMessageEvent object console.error("Message deserialization failed"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("ServiceWorkerGlobalScope/message_event", "message")}} - {{domxref("ServiceWorker.postMessage()")}} - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) - [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker) - [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/registration/index.md
--- title: "ServiceWorkerGlobalScope: registration property" short-title: registration slug: Web/API/ServiceWorkerGlobalScope/registration page-type: web-api-instance-property browser-compat: api.ServiceWorkerGlobalScope.registration --- {{APIRef("Service Workers API")}} The **`registration`** read-only property of the {{domxref("ServiceWorkerGlobalScope")}} interface returns a reference to the {{domxref("ServiceWorkerRegistration")}} object, which represents the service worker's registration. ## Value A {{domxref("ServiceWorkerRegistration")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) - [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker) - [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/periodicsync_event/index.md
--- title: "ServiceWorkerGlobalScope: periodicsync event" short-title: periodicsync slug: Web/API/ServiceWorkerGlobalScope/periodicsync_event page-type: web-api-event status: - experimental browser-compat: api.ServiceWorkerGlobalScope.periodicsync_event --- {{APIRef("Periodic Background Sync")}}{{SeeCompatTable}} The **`periodicsync`** event of the {{domxref("ServiceWorkerGlobalScope")}} interface is fired at timed intervals, specified when registering a {{domxref('PeriodicSyncManager')}}. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("periodicsync", (event) => {}); onperiodicsync = (event) => {}; ``` ## Event type A {{domxref("PeriodicSyncEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("PeriodicSyncEvent")}} ## Event properties _Inherits properties from its ancestor, {{domxref("Event")}}_. - {{domxref('PeriodicSyncEvent.tag')}} {{ReadOnlyInline}} - : Returns the developer-defined identifier for this `PeriodicSyncEvent`. Multiple tags can be used by the web app to run different periodic tasks at different frequencies. ## Examples The following example shows how to respond to a periodic sync event in the service worker. ```js self.addEventListener("periodicsync", (event) => { if (event.tag === "get-latest-news") { event.waitUntil(fetchAndCacheLatestNews()); } }); ``` You can also set up the event handler using the `onperiodicsync` property: ```js self.onperiodicsync = (event) => { // ... }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Richer offline experiences with the Periodic Background Sync API](https://developer.chrome.com/docs/capabilities/periodic-background-sync) - [A Periodic Background Sync demo app](https://webplatformapis.com/periodic_sync/periodicSync_improved.html)
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/notificationclose_event/index.md
--- title: "ServiceWorkerGlobalScope: notificationclose event" short-title: notificationclose slug: Web/API/ServiceWorkerGlobalScope/notificationclose_event page-type: web-api-event browser-compat: api.ServiceWorkerGlobalScope.notificationclose_event --- {{APIRef("Web Notifications")}} The **`notificationclose`** event of the {{domxref("ServiceWorkerGlobalScope")}} interface fires when a user closes a displayed notification spawned by {{domxref("ServiceWorkerRegistration.showNotification()")}}. Notifications created on the main thread or in workers which aren't service workers using the {{domxref("Notification.Notification","Notification()")}} constructor will instead receive a {{domxref("Notification/close_event", "close")}} event on the {{domxref("Notification")}} object itself. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("notificationclose", (event) => {}); onnotificationclose = (event) => {}; ``` ## Event type A {{domxref("NotificationEvent")}}. Inherits from {{domxref("ExtendableEvent")}} and {{domxref("Event")}}. {{InheritanceDiagram("NotificationEvent")}} ## Event properties _Inherits properties from its ancestor, {{domxref("ExtendableEvent")}} and {{domxref("Event")}}_. - {{domxref("NotificationEvent.notification")}} {{ReadOnlyInline}} - : Returns a {{domxref("Notification")}} object representing the notification that was clicked to fire the event. - {{domxref("NotificationEvent.action")}} {{ReadOnlyInline}} - : Returns the string ID of the notification button the user clicked. This value returns an empty string if the user clicked the notification somewhere other than an action button, or the notification does not have a button. ## Example ```js // Inside a service worker. self.onnotificationclose = (event) => { console.log("On notification close: ", event.notification.tag); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/cookiechange_event/index.md
--- title: "ServiceWorkerGlobalScope: cookiechange event" short-title: cookiechange slug: Web/API/ServiceWorkerGlobalScope/cookiechange_event page-type: web-api-event status: - experimental browser-compat: api.ServiceWorkerGlobalScope.cookiechange_event --- {{APIRef("Cookie Store API")}}{{SeeCompatTable}} The **`cookiechange`** event of the {{domxref("ServiceWorkerGlobalScope")}} interface is fired when a cookie change occurs that matches the service worker's cookie change subscription list. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("cookiechange", (event) => {}); oncookiechange = (event) => {}; ``` ## Event type An {{domxref("ExtendableCookieChangeEvent")}}. Inherits from {{domxref("ExtendableEvent")}}. {{InheritanceDiagram("ExtendableCookieChangeEvent")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/notificationclick_event/index.md
--- title: "ServiceWorkerGlobalScope: notificationclick event" short-title: notificationclick slug: Web/API/ServiceWorkerGlobalScope/notificationclick_event page-type: web-api-event browser-compat: api.ServiceWorkerGlobalScope.notificationclick_event --- {{APIRef("Web Notifications")}} The **`notificationclick`** event of the {{domxref("ServiceWorkerGlobalScope")}} interface is fired to indicate that a system notification spawned by {{domxref("ServiceWorkerRegistration.showNotification()")}} has been clicked. Notifications created on the main thread or in workers which aren't service workers using the {{domxref("Notification.Notification","Notification()")}} constructor will instead receive a {{domxref("Notification/click_event", "click")}} event on the {{domxref("Notification")}} object itself. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("notificationclick", (event) => {}); onnotificationclick = (event) => {}; ``` ## Event type A {{domxref("NotificationEvent")}}. Inherits from {{domxref("ExtendableEvent")}} and {{domxref("Event")}}. {{InheritanceDiagram("NotificationEvent")}} ## Event properties _Inherits properties from its ancestors, {{domxref("ExtendableEvent")}} and {{domxref("Event")}}_. - {{domxref("NotificationEvent.notification")}} {{ReadOnlyInline}} - : Returns a {{domxref("Notification")}} object representing the notification that was clicked to fire the event. - {{domxref("NotificationEvent.action")}} {{ReadOnlyInline}} - : Returns the string ID of the notification button the user clicked. This value returns an empty string if the user clicked the notification somewhere other than an action button, or the notification does not have a button. ## Examples You can use the `notificationclick` event in an {{domxref("EventTarget/addEventListener", "addEventListener")}} method: ```js self.addEventListener("notificationclick", (event) => { console.log("On notification click: ", event.notification.tag); event.notification.close(); // This looks to see if the current is already open and // focuses if it is event.waitUntil( clients .matchAll({ type: "window", }) .then((clientList) => { for (const client of clientList) { if (client.url === "/" && "focus" in client) return client.focus(); } if (clients.openWindow) return clients.openWindow("/"); }), ); }); ``` Or use the `onnotificationclick` event handler property: ```js self.onnotificationclick = (event) => { console.log("On notification click: ", event.notification.tag); event.notification.close(); // This looks to see if the current is already open and // focuses if it is event.waitUntil( clients .matchAll({ type: "window", }) .then((clientList) => { for (const client of clientList) { if (client.url === "/" && "focus" in client) return client.focus(); } if (clients.openWindow) return clients.openWindow("/"); }), ); }; ``` You can handle event actions using `event.action` within a `notificationclick` event handler: ```js navigator.serviceWorker.register("sw.js"); Notification.requestPermission().then((result) => { if (result === "granted") { navigator.serviceWorker.ready.then((registration) => { // Show a notification that includes an action titled Archive. registration.showNotification("New mail from Alice", { actions: [ { action: "archive", title: "Archive", }, ], }); }); } }); self.addEventListener( "notificationclick", (event) => { event.notification.close(); if (event.action === "archive") { // User selected the Archive action. archiveEmail(); } else { // User selected (e.g., clicked in) the main body of notification. clients.openWindow("/inbox"); } }, false, ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Service Worker API](/en-US/docs/Web/API/Service_Worker_API) - [Notifications API](/en-US/docs/Web/API/Notifications_API)
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/serviceworker/index.md
--- title: "ServiceWorkerGlobalScope: serviceWorker property" short-title: serviceWorker slug: Web/API/ServiceWorkerGlobalScope/serviceWorker page-type: web-api-instance-property browser-compat: api.ServiceWorkerGlobalScope.serviceWorker --- {{APIRef("Service Workers API")}} The **`serviceWorker`** read-only property of the {{domxref("ServiceWorkerGlobalScope")}} interface returns a reference to the {{domxref("ServiceWorker")}} object, which represents the service worker. ## Value A {{domxref("ServiceWorker")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers)
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/canmakepayment_event/index.md
--- title: "ServiceWorkerGlobalScope: canmakepayment event" short-title: canmakepayment slug: Web/API/ServiceWorkerGlobalScope/canmakepayment_event page-type: web-api-event status: - experimental browser-compat: api.ServiceWorkerGlobalScope.canmakepayment_event --- {{APIRef("Payment Handler API")}}{{SeeCompatTable}} The **`canmakepayment`** event of the {{domxref("ServiceWorkerGlobalScope")}} interface is fired on a payment app's service worker to check whether it is ready to handle a payment. Specifically, it is fired when the merchant website calls {{domxref("PaymentRequest.PaymentRequest", "new PaymentRequest()")}}. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("canmakepayment", (event) => {}); oncanmakepayment = (event) => {}; ``` ## Event type A {{domxref("CanMakePaymentEvent")}}. Inherits from {{domxref("ExtendableEvent")}}. {{InheritanceDiagram("CanMakePaymentEvent")}} ## Examples The `canmakepayment` event is fired on a payment app's service worker to check whether it is ready to handle a payment. Specifically, it is fired when the merchant website calls {{domxref("PaymentRequest.PaymentRequest", "new PaymentRequest()")}}. The service worker can then use the {{domxref("CanMakePaymentEvent.respondWith()")}} method to respond appropriately: ```js self.addEventListener("canmakepayment", (e) => { e.respondWith( new Promise((resolve, reject) => { someAppSpecificLogic() .then((result) => { resolve(result); }) .catch((error) => { reject(error); }); }), ); }); ``` `respondWith()` returns a {{jsxref("Promise")}} that resolves with a boolean value to signal that the service worker is ready to handle a payment request (`true`), or not (`false`). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Payment Handler API", "Payment Handler API", "", "nocode")}} - [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/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/activate_event/index.md
--- title: "ServiceWorkerGlobalScope: activate event" short-title: activate slug: Web/API/ServiceWorkerGlobalScope/activate_event page-type: web-api-event browser-compat: api.ServiceWorkerGlobalScope.activate_event --- {{APIRef("Service Workers API")}} The **`activate`** event of the {{domxref("ServiceWorkerGlobalScope")}} interface is fired when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active")}} worker. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("activate", (event) => {}); onactivate = (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")}}._ ## Examples The following snippet shows how you could use an `activate` event handler to upgrade a cache. ```js self.addEventListener("activate", (event) => { const cacheAllowlist = ["v2"]; event.waitUntil( caches.forEach((cache, cacheName) => { if (!cacheAllowlist.includes(cacheName)) { return caches.delete(cacheName); } }), ); }); ``` You can also set up the event handler using the `onactivate` property: ```js self.onactivate = (event) => { // ... }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("ServiceWorkerGlobalScope/install_event", "install")}} event - {{domxref("ServiceWorkerGlobalScope")}} - [Service Worker API](/en-US/docs/Web/API/Service_Worker_API)
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/clients/index.md
--- title: "ServiceWorkerGlobalScope: clients property" short-title: clients slug: Web/API/ServiceWorkerGlobalScope/clients page-type: web-api-instance-property browser-compat: api.ServiceWorkerGlobalScope.clients --- {{APIRef("Service Workers API")}} The **`clients`** read-only property of the {{domxref("ServiceWorkerGlobalScope")}} interface returns the [`Clients`](/en-US/docs/Web/API/Clients) object associated with the service worker. ## Value The {{domxref("Clients")}} object associated with the specific worker. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) - [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker) - [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/install_event/index.md
--- title: "ServiceWorkerGlobalScope: install event" short-title: install slug: Web/API/ServiceWorkerGlobalScope/install_event page-type: web-api-event browser-compat: api.ServiceWorkerGlobalScope.install_event --- {{APIRef("Service Workers API")}} The **`install`** event of the {{domxref("ServiceWorkerGlobalScope")}} interface is fired when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.installing")}} worker. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("install", (event) => {}); oninstall = (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")}}._ ## Examples The following snippet shows how an `install` event handler can be used to populate a cache with a number of responses, which the service worker can then use to serve assets offline: ```js self.addEventListener("install", (event) => { event.waitUntil( caches .open("v1") .then((cache) => cache.addAll([ "/", "/index.html", "/style.css", "/app.js", "/image-list.js", "/star-wars-logo.jpg", "/gallery/", "/gallery/bountyHunters.jpg", "/gallery/myLittleVader.jpg", "/gallery/snowTroopers.jpg", ]), ), ); }); ``` You can also set up the event handler using the `oninstall` property: ```js self.oninstall = (event) => { // ... }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("ServiceWorkerGlobalScope/activate_event", "activate")}} event - {{domxref("ServiceWorkerGlobalScope")}} - [Service Worker API](/en-US/docs/Web/API/Service_Worker_API)
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/skipwaiting/index.md
--- title: "ServiceWorkerGlobalScope: skipWaiting() method" short-title: skipWaiting() slug: Web/API/ServiceWorkerGlobalScope/skipWaiting page-type: web-api-instance-method browser-compat: api.ServiceWorkerGlobalScope.skipWaiting --- {{APIRef("Service Workers API")}} The **`ServiceWorkerGlobalScope.skipWaiting()`** method of the {{domxref("ServiceWorkerGlobalScope")}} forces the waiting service worker to become the active service worker. Use this method with {{domxref("Clients.claim()")}} to ensure that updates to the underlying service worker take effect immediately for both the current client and all other active clients. ## Syntax ```js-nolint skipWaiting() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that resolves with `undefined` after trying to activate the newly installed service worker. ## Examples While `self.skipWaiting()` can be called at any point during the service worker's execution, it will only have an effect if there's a newly installed service worker that might otherwise remain in the `waiting` state. Therefore, it's common to call `self.skipWaiting()` from inside of an {{domxref("InstallEvent")}} handler. The following example causes a newly installed service worker to progress into the `activating` state, regardless of whether there is already an active service worker. ```js self.addEventListener("install", (event) => { // The promise that skipWaiting() returns can be safely ignored. self.skipWaiting(); // Perform any other actions required for your // service worker to install, potentially inside // of event.waitUntil(); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) - [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker) - {{domxref("Clients.claim()")}} - [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/cookiestore/index.md
--- title: "ServiceWorkerGlobalScope: cookieStore property" short-title: cookieStore slug: Web/API/ServiceWorkerGlobalScope/cookieStore page-type: web-api-instance-property status: - experimental browser-compat: api.ServiceWorkerGlobalScope.cookieStore --- {{APIRef("Cookie Store API")}}{{SeeCompatTable}} The **`cookieStore`** read-only property of the {{domxref("ServiceWorkerGlobalScope")}} interface returns a reference to the {{domxref("CookieStore")}} object associated with this service worker. ## Value A {{domxref("CookieStore")}} object instance. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/sync_event/index.md
--- title: "ServiceWorkerGlobalScope: sync event" short-title: sync slug: Web/API/ServiceWorkerGlobalScope/sync_event page-type: web-api-event browser-compat: api.ServiceWorkerGlobalScope.sync_event --- {{APIRef("Background Sync")}} The **`sync`** event of the {{domxref("ServiceWorkerGlobalScope")}} interface is fired when the page (or worker) that registered the event with the {{domxref('SyncManager')}} is running and as soon as network connectivity is available. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("sync", (event) => {}); onsync = (event) => {}; ``` ## Event type A {{domxref("SyncEvent")}}. Inherits from {{domxref("ExtendableEvent")}} and {{domxref("Event")}}. {{InheritanceDiagram("SyncEvent")}} ## Event properties _Inherits properties from its ancestor, {{domxref("ExtendableEvent")}} and {{domxref("Event")}}_. - {{domxref("SyncEvent.tag")}} {{ReadOnlyInline}} - : Returns the developer-defined identifier for this `SyncEvent`. - {{domxref("SyncEvent.lastChance")}} {{ReadOnlyInline}} - : Returns `true` if the user agent will not make further synchronization attempts after the current attempt. ## Examples The following example shows how to respond to a sync event in the service worker. ```js self.addEventListener("sync", (event) => { if (event.tag === "sync-messages") { event.waitUntil(sendOutboxMessages()); } }); ``` You can also set up the event handler using the `onsync` property: ```js self.onsync = (event) => { // ... }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Richer offline experiences with the Periodic Background Sync API](https://developer.chrome.com/docs/capabilities/periodic-background-sync) - [A Periodic Background Sync demo app](https://webplatformapis.com/periodic_sync/periodicSync_improved.html)
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/push_event/index.md
--- title: "ServiceWorkerGlobalScope: push event" short-title: push slug: Web/API/ServiceWorkerGlobalScope/push_event page-type: web-api-event browser-compat: api.ServiceWorkerGlobalScope.push_event --- {{APIRef("Push API")}}{{SecureContext_Header}} The **`push`** event is sent to a service worker's global scope (represented by the {{domxref("ServiceWorkerGlobalScope")}} interface) when the service worker has received a push message. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("push", (event) => {}); onpush = (event) => {}; ``` ## Event type A {{domxref("PushEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("PushEvent")}} ## Event properties _Inherits properties from its parent, {{domxref("ExtendableEvent")}}. Additional properties:_ - {{domxref("PushEvent.data")}} {{ReadOnlyInline}} - : Returns a reference to a {{domxref("PushMessageData")}} object containing data sent to the {{domxref("PushSubscription")}}. ## Example This example sets up a handler for `push` events that takes {{Glossary("JSON")}} data, parses it, and dispatches the message for handling based on information contained within the message. ```js self.addEventListener( "push", (event) => { let message = event.data.json(); switch (message.type) { case "init": doInit(); break; case "shutdown": doShutdown(); break; } }, false, ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Push API](/en-US/docs/Web/API/Push_API) - {{domxref("ServiceWorkerGlobalScope/pushsubscriptionchange_event", "pushsubscriptionchange")}} event
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/backgroundfetchabort_event/index.md
--- title: "ServiceWorkerGlobalScope: backgroundfetchabort event" short-title: backgroundfetchabort slug: Web/API/ServiceWorkerGlobalScope/backgroundfetchabort_event page-type: web-api-event status: - experimental browser-compat: api.ServiceWorkerGlobalScope.backgroundfetchabort_event --- {{APIRef("Background Fetch API")}}{{SeeCompatTable}} The **`backgroundfetchabort`** event of the {{domxref("ServiceWorkerGlobalScope")}} interface is fired when the user or the app itself cancels a [background fetch](/en-US/docs/Web/API/Background_Fetch_API) operation. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("backgroundfetchabort", (event) => {}); onbackgroundfetchabort = (event) => {}; ``` ## Event type A {{domxref("BackgroundFetchEvent")}}. {{InheritanceDiagram("BackgroundFetchEvent")}} ## Event properties _Inherits properties from its parent, {{domxref("ExtendableEvent")}}._ - {{domxref("BackgroundFetchEvent.registration")}} - : Returns the {{domxref("BackgroundFetchRegistration")}} for the aborted fetch. ## Description In the background fetch API, the browser shows a UI element to the user to indicate the progress of the operation. This element also enables the user to cancel the fetch. The app itself can also cancel the fetch by calling {{domxref("BackgroundFetchRegistration.abort()")}}. If the fetch is canceled, the browser aborts the fetch, starts the service worker, if necessary, and fires the `backgroundfetchabort` event in the service worker's global scope. In the handler for this event, the service worker can clean up any related data for the operation. It can also retrieve and store any successful responses (for example, using the {{domxref("Cache")}} API). To access the response data, the service worker uses the event's {{domxref("BackgroundFetchEvent/registration", "registration")}} property. ## Examples ### Cleaning up This event handler might perform any cleanup of data associated with the aborted fetch. ```js addEventListener("backgroundfetchabort", (event) => { // clean up any related data }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Background Fetch API](/en-US/docs/Web/API/Background_Fetch_API)
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/message_event/index.md
--- title: "ServiceWorkerGlobalScope: message event" short-title: message slug: Web/API/ServiceWorkerGlobalScope/message_event page-type: web-api-event browser-compat: api.ServiceWorkerGlobalScope.message_event --- {{APIRef("Service Workers API")}} The **`message`** event of the {{domxref("ServiceWorkerGlobalScope")}} interface occurs when incoming messages are received. Controlled pages can use the {{domxref("ServiceWorker.postMessage()")}} method to send messages to service workers. The service worker can optionally send a response back via the {{domxref("Client.postMessage()")}}, corresponding to the controlled page. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("message", (event) => {}); onmessage = (event) => {}; ``` ## Event type An {{domxref("ExtendableMessageEvent")}}. Inherits from {{domxref("ExtendableEvent")}}. {{InheritanceDiagram("ExtendableMessageEvent")}} ## Event properties _Inherits properties from its parent, {{domxref("ExtendableEvent")}}_. - {{domxref("ExtendableMessageEvent.data")}} {{ReadOnlyInline}} - : Returns the event's data. It can be any data type. If dispatched in `messageerror` event, the property will be `null`. - {{domxref("ExtendableMessageEvent.origin")}} {{ReadOnlyInline}} - : Returns the origin of the {{domxref("Client")}} that sent the message. - {{domxref("ExtendableMessageEvent.lastEventId")}} {{ReadOnlyInline}} - : Represents, in [server-sent events](/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events), the last event ID of the event source. - {{domxref("ExtendableMessageEvent.source")}} {{ReadOnlyInline}} - : Returns a reference to the {{domxref("Client")}} object that sent the message. - {{domxref("ExtendableMessageEvent.ports")}} {{ReadOnlyInline}} - : Returns the array containing the {{domxref("MessagePort")}} objects representing the ports of the associated message channel. ## Examples In the below example a page gets a handle to the {{domxref("ServiceWorker")}} object via {{domxref("ServiceWorkerRegistration.active")}}, and then calls its `postMessage()` function. ```js // main.js if (navigator.serviceWorker) { navigator.serviceWorker.register("service-worker.js"); navigator.serviceWorker.addEventListener("message", (event) => { // event is a MessageEvent object console.log(`The service worker sent me a message: ${event.data}`); }); navigator.serviceWorker.ready.then((registration) => { registration.active.postMessage("Hi service worker"); }); } ``` The service worker can receive the message by listening to the `message` event: ```js // service-worker.js addEventListener("message", (event) => { // event is an ExtendableMessageEvent object console.log(`The client sent me a message: ${event.data}`); event.source.postMessage("Hi client"); }); ``` Alternatively, the script can listen for the message using `onmessage`: ```js // service-worker.js self.onmessage = (event) => { // event is an ExtendableMessageEvent object console.log(`The client sent me a message: ${event.data}`); event.source.postMessage("Hi client"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) - [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker) - [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/pushsubscriptionchange_event/index.md
--- title: "ServiceWorkerGlobalScope: pushsubscriptionchange event" short-title: pushsubscriptionchange slug: Web/API/ServiceWorkerGlobalScope/pushsubscriptionchange_event page-type: web-api-event browser-compat: api.ServiceWorkerGlobalScope.pushsubscriptionchange_event --- {{APIRef("Push API")}}{{SecureContext_Header}} The **`pushsubscriptionchange`** event is sent to the [global scope](/en-US/docs/Web/API/ServiceWorkerGlobalScope) of a {{domxref("ServiceWorker")}} to indicate a change in push subscription that was triggered outside the application's control. This may occur if the subscription was refreshed by the browser, but it may also happen if the subscription has been revoked or lost. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("pushsubscriptionchange", (event) => {}); onpushsubscriptionchange = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Usage notes Although examples demonstrating how to share subscription related information with the application server tend to use {{domxref("fetch()")}}, this is not necessarily the best choice for real-world use, since it will not work if the app is offline, for example. Consider using another method to synchronize subscription information between your service worker and the app server, or make sure your code using `fetch()` is robust enough to handle cases where attempts to exchange data fail. > **Note:** In earlier drafts of the specification, this event was defined to be sent when a {{domxref("PushSubscription")}} has expired. ## Examples This example, run in the context of a service worker, listens for a `pushsubscriptionchange` event and re-subscribes to the lapsed subscription. ```js self.addEventListener( "pushsubscriptionchange", (event) => { const conv = (val) => btoa(String.fromCharCode.apply(null, new Uint8Array(val))); const getPayload = (subscription) => ({ endpoint: subscription.endpoint, publicKey: conv(subscription.getKey("p256dh")), authToken: conv(subscription.getKey("auth")), }); const subscription = self.registration.pushManager .subscribe(event.oldSubscription.options) .then((subscription) => fetch("register", { method: "post", headers: { "Content-type": "application/json", }, body: JSON.stringify({ old: getPayload(event.oldSubscription), new: getPayload(subscription), }), }), ); event.waitUntil(subscription); }, false, ); ``` When a `pushsubscriptionchange` event arrives, indicating that the subscription has expired, we resubscribe by calling the push manager's {{domxref("PushManager.subscribe", "subscribe()")}} method. When the returned promise is resolved, we receive the new subscription. This is delivered to the app server using a {{domxref("fetch()")}} call to post a {{Glossary("JSON")}} formatted rendition of the subscription's {{domxref("PushSubscription.endpoint", "endpoint")}} to the app server. You can also use the `onpushsubscriptionchange` event handler property to set up the event handler: ```js self.onpushsubscriptionchange = (event) => { event.waitUntil( self.registration.pushManager .subscribe(event.oldSubscription.options) .then((subscription) => { /* ... */ }), ); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Push API](/en-US/docs/Web/API/Push_API)
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/backgroundfetchfail_event/index.md
--- title: "ServiceWorkerGlobalScope: backgroundfetchfail event" short-title: backgroundfetchfail slug: Web/API/ServiceWorkerGlobalScope/backgroundfetchfail_event page-type: web-api-event status: - experimental browser-compat: api.ServiceWorkerGlobalScope.backgroundfetchfail_event --- {{APIRef("Background Fetch API")}}{{SeeCompatTable}} The **`backgroundfetchfail`** event of the {{domxref("ServiceWorkerGlobalScope")}} interface is fired when a [background fetch](/en-US/docs/Web/API/Background_Fetch_API) operation has failed: that is, when at least one network request in the fetch has failed to complete successfully. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("backgroundfetchfail", (event) => {}); onbackgroundfetchfail = (event) => {}; ``` ## Event type A {{domxref("BackgroundFetchUpdateUIEvent")}}. {{InheritanceDiagram("BackgroundFetchUpdateUIEvent")}} ## Event properties _Inherits properties from its parent, {{domxref("BackgroundFetchEvent")}}._ - {{domxref("BackgroundFetchUpdateUIEvent.updateUI()")}} - : Updates the UI of the element that the browser displays to show the progress of the fetch operation. ## Description When a [background fetch](/en-US/docs/Web/API/Background_Fetch_API) operation fails (meaning that at least one of the individual network requests has not completed successfully), the browser starts the service worker, if necessary, and fires the `backgroundfetchfail` event in the service worker's global scope. In the background fetch API, the browser shows a UI element to the user to indicate the progress of the operation. In the `backgroundfetchfail` handler, the service worker can update that UI to show that the operation has failed. To do this, the handler calls the event's {{domxref("BackgroundFetchUpdateUIEvent/updateUI", "updateUI()")}} method, passing in a new title and/or icons. In the handler for this `backgroundfetchfail`, the service worker can also clean up any related data for the operation. It can also retrieve and store any successful responses (for example, using the {{domxref("Cache")}} API). To access the response data, the service worker uses the event's {{domxref("BackgroundFetchEvent/registration", "registration")}} property. ## Examples ### Updating UI This event handler updates the UI to let the user know that the operation failed. ```js addEventListener("backgroundfetchfail", (event) => { event.updateUI({ title: "Could not complete download" }); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Background Fetch API](/en-US/docs/Web/API/Background_Fetch_API)
0
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/paymentrequest_event/index.md
--- title: "ServiceWorkerGlobalScope: paymentrequest event" short-title: paymentrequest slug: Web/API/ServiceWorkerGlobalScope/paymentrequest_event page-type: web-api-event status: - experimental browser-compat: api.ServiceWorkerGlobalScope.paymentrequest_event --- {{APIRef("Payment Handler API")}}{{SeeCompatTable}} The **`paymentrequest`** event of the {{domxref("ServiceWorkerGlobalScope")}} interface is fired on a payment app when a payment flow has been initiated on the merchant website via the {{domxref("PaymentRequest.show()")}} method. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("paymentrequest", (event) => {}); onpaymentrequest = (event) => {}; ``` ## Event type A {{domxref("PaymentRequestEvent")}}. Inherits from {{domxref("ExtendableEvent")}}. {{InheritanceDiagram("PaymentRequestEvent")}} ## 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 - {{domxref("Payment Handler API", "Payment Handler API", "", "nocode")}} - [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/serviceworkerglobalscope
data/mdn-content/files/en-us/web/api/serviceworkerglobalscope/contentdelete_event/index.md
--- title: "ServiceWorkerGlobalScope: contentdelete event" short-title: contentdelete slug: Web/API/ServiceWorkerGlobalScope/contentdelete_event page-type: web-api-event status: - experimental browser-compat: api.ServiceWorkerGlobalScope.contentdelete_event --- {{APIRef("Content Index API")}}{{SeeCompatTable}} The **`contentdelete`** event of the {{domxref("ServiceWorkerGlobalScope")}} interface is fired when an item is removed from the indexed content via the user agent. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("contentdelete", (event) => {}); oncontentdelete = (event) => {}; ``` ## Event type A {{domxref("ContentIndexEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ContentIndexEvent")}} ## Event properties _In addition to the properties listed below, this interface inherits the properties of its parent interface, {{domxref("Event")}}._ - {{domxref("ContentIndexEvent.id", "id")}} {{ReadOnlyInline}} - : A string which identifies the deleted content index via it's `id`. ## Examples The following example uses a `contentdelete` event handler to remove cached content related to the deleted index item. ```js self.addEventListener("contentdelete", (event) => { const deletion = caches .open("cache-name") .then((cache) => Promise.all([ cache.delete(`/icon/${event.id}`), cache.delete(`/content/${event.id}`), ]), ); event.waitUntil(deletion); }); ``` You can also set up the event handler using the `oncontentdelete` property: ```js self.oncontentdelete = (event) => { // ... }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Content index API](/en-US/docs/Web/API/Content_Index_API) - [An introductory article on the Content Index API](https://developer.chrome.com/docs/capabilities/web-apis/content-indexing-api) - [An app which uses the Content Index API to list and remove 'save for later' content](https://contentindex.dev/)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svganimationelement/index.md
--- title: SVGAnimationElement slug: Web/API/SVGAnimationElement page-type: web-api-interface browser-compat: api.SVGAnimationElement --- {{APIRef("SVG")}} The **`SVGAnimationElement`** interface is the base interface for all of the animation element interfaces: {{domxref("SVGAnimateElement")}}, {{domxref("SVGSetElement")}}, {{domxref("SVGAnimateColorElement")}}, {{domxref("SVGAnimateMotionElement")}} and {{domxref("SVGAnimateTransformElement")}}. {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties from its parent, {{domxref("SVGElement")}}._ - {{domxref("SVGAnimationElement.requiredExtensions")}} {{ReadOnlyInline}} - : An {{domxref("SVGStringList")}} reflecting the {{SVGAttr("requiredExtensions")}} attribute of the given element. - {{domxref("SVGAnimationElement.systemLanguage")}} {{ReadOnlyInline}} - : An {{domxref("SVGStringList")}} reflecting the {{SVGAttr("systemLanguage")}} attribute of the given element. - {{domxref("SVGAnimationElement.targetElement")}} {{ReadOnlyInline}} - : An {{domxref("SVGElement")}} representing the element which is being animated. If no target element is being animated (for example, because the {{SVGAttr("href")}} specifies an unknown element) the value returned is `null`. ## Instance methods _This interface also inherits methods from its parent, {{domxref("SVGElement")}}._ - {{domxref("SVGAnimationElement.getStartTime()")}} - : Returns a float representing the begin time, in seconds, for this animation element's current interval, if it exists, regardless of whether the interval has begun yet. If there is no current interval, then a {{domxref("DOMException")}} with code `INVALID_STATE_ERR` is thrown. - {{domxref("SVGAnimationElement.getCurrentTime()")}} - : Returns a float representing the current time in seconds relative to time zero for the given time container. - {{domxref("SVGAnimationElement.getSimpleDuration()")}} - : Returns a float representing the number of seconds for the simple duration for this animation. If the simple duration is undefined (e.g., the end time is indefinite), then a {{domxref("DOMException")}} with code `NOT_SUPPORTED_ERR` is raised. - {{domxref("SVGAnimationElement.beginElement()")}} - : Creates a begin instance time for the current time. The new instance time is added to the begin instance times list. The behavior of this method is equivalent to `beginElementAt(0)`. - {{domxref("SVGAnimationElement.beginElementAt()")}} - : Creates a begin instance time for the current time plus the specified offset. The new instance time is added to the begin instance times list. - {{domxref("SVGAnimationElement.endElement()")}} - : Creates an end instance time for the current time. The new instance time is added to the end instance times list. The behavior of this method is equivalent to `endElementAt(0)`. - {{domxref("SVGAnimationElement.endElementAt()")}} - : Creates an end instance time for the current time plus the specified offset. The new instance time is added to the end instance times list. ## Events Listen to these events using [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener) or by assigning an event listener to the `on...` handler property of this interface. - [`beginEvent`](/en-US/docs/Web/API/SVGAnimationElement/beginEvent_event) - : Fired when the element local timeline begins to play. - [`endEvent`](/en-US/docs/Web/API/SVGAnimationElement/endEvent_event) - : Fired when at the active end of the animation is reached. - [`repeatEvent`](/en-US/docs/Web/API/SVGAnimationElement/repeatEvent_event) - : Fired when the element's local timeline repeats. It will be fired each time the element repeats, after the first iteration. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/svganimationelement
data/mdn-content/files/en-us/web/api/svganimationelement/targetelement/index.md
--- title: "SVGAnimationElement: targetElement property" short-title: targetElement slug: Web/API/SVGAnimationElement/targetElement page-type: web-api-instance-property browser-compat: api.SVGAnimationElement.targetElement --- {{APIRef("SVG")}} The **`SVGAnimationElement.targetElement`** property refers to the element which is being animated. If no target element is being animated (for example, because the {{SVGAttr("href")}} attribute specifies an unknown element), the value returned is `null`. ## Value A SVGElement object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/svganimationelement
data/mdn-content/files/en-us/web/api/svganimationelement/repeatevent_event/index.md
--- title: "SVGAnimationElement: repeatEvent event" short-title: repeatEvent slug: Web/API/SVGAnimationElement/repeatEvent_event page-type: web-api-event browser-compat: api.SVGAnimationElement.repeatEvent_event --- {{APIRef("SVG")}} The **`repeatEvent`** event of the {{domxref("SVGAnimationElement")}} interface is fired when the element's local timeline repeats. It will be fired each time the element repeats, after the first iteration. > **Note:** Associated with the `repeatEvent` event is an integer that indicates which repeat iteration is beginning; this can be found in the `detail` property of the event object. The value is a 0-based integer, but the repeat event is not raised for the first iteration and so the observed values will be >= 1. This is supported in Firefox, but not in Chrome. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("repeatEvent", (event) => {}); onrepeat = (event) => {}; ``` ## Event type A {{domxref("TimeEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("TimeEvent")}} ## Event properties - {{domxref("TimeEvent.detail")}} {{ReadOnlyInline}} - : A `long` that specifies some detail information about the Event, depending on the type of the event. For this event type, indicates the repeat number for the animation. - {{domxref("TimeEvent.view")}} {{ReadOnlyInline}} - : A {{glossary("WindowProxy")}} that identifies the Window from which the event was generated. ## Examples ### Animated circle ```html <svg xmlns="http://www.w3.org/2000/svg" width="300px" height="100px"> <title>SVG SMIL Animate with Path</title> <circle cx="0" cy="50" r="50" fill="blue" stroke="black" stroke-width="1"> <animateMotion path="M 0 0 H 300 Z" dur="5s" repeatCount="indefinite" /> </circle> </svg> <hr /> <ul></ul> ``` ```css ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } ``` ```js let svgElem = document.querySelector("svg"); let animateElem = document.querySelector("animateMotion"); let list = document.querySelector("ul"); animateElem.addEventListener("beginEvent", () => { let listItem = document.createElement("li"); listItem.textContent = "beginEvent fired"; list.appendChild(listItem); }); animateElem.addEventListener("repeatEvent", (e) => { let listItem = document.createElement("li"); let msg = "repeatEvent fired"; if (e.detail) { msg += `; repeat number: ${e.detail}`; } listItem.textContent = msg; list.appendChild(listItem); }); ``` {{EmbedLiveSample('Animated_circle', '100%', '270')}} ### Event handler property equivalent Note that you can also create an event listener for the `repeat` event using the `onrepeat` event handler property: ```js animateElem.onrepeat = () => { console.log("repeatEvent fired"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [SVG animation with SMIL](/en-US/docs/Web/SVG/SVG_animation_with_SMIL) - {{domxref("SVGAnimationElement.beginEvent_event", "beginEvent")}} event - {{domxref("SVGAnimationElement.endEvent_event", "endEvent")}} event
0
data/mdn-content/files/en-us/web/api/svganimationelement
data/mdn-content/files/en-us/web/api/svganimationelement/beginevent_event/index.md
--- title: "SVGAnimationElement: beginEvent event" short-title: beginEvent slug: Web/API/SVGAnimationElement/beginEvent_event page-type: web-api-event browser-compat: api.SVGAnimationElement.beginEvent_event --- {{APIRef("SVG")}} The **`beginEvent`** event of the {{domxref("SVGAnimationElement")}} interface is fired when the element local timeline begins to play. It will be raised each time the element begins the active duration (i.e., when it restarts, but not when it repeats). It may be raised both in the course of normal (i.e. scheduled or interactive) timeline play, as well as in the case that the element was begun with a DOM method. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("beginEvent", (event) => {}); onbegin = (event) => {}; ``` ## Event type A {{domxref("TimeEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("TimeEvent")}} ## Event properties - {{domxref("TimeEvent.detail")}} {{ReadOnlyInline}} - : A `long` that specifies some detail information about the Event, depending on the type of the event. For this event type, indicates the repeat number for the animation. - {{domxref("TimeEvent.view")}} {{ReadOnlyInline}} - : A {{glossary("WindowProxy")}} that identifies the Window from which the event was generated. ## Examples ### Animated circle ```html <svg xmlns="http://www.w3.org/2000/svg" width="300px" height="100px"> <title>SVG SMIL Animate with Path</title> <circle cx="0" cy="50" r="50" fill="blue" stroke="black" stroke-width="1"> <animateMotion path="M 0 0 H 300 Z" dur="5s" repeatCount="indefinite" /> </circle> </svg> <hr /> <ul></ul> ``` ```css ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } ``` ```js let svgElem = document.querySelector("svg"); let animateElem = document.querySelector("animateMotion"); let list = document.querySelector("ul"); animateElem.addEventListener("beginEvent", () => { let listItem = document.createElement("li"); listItem.textContent = "beginEvent fired"; list.appendChild(listItem); }); animateElem.addEventListener("repeatEvent", (e) => { let listItem = document.createElement("li"); let msg = "repeatEvent fired"; if (e.detail) { msg += `; repeat number: ${e.detail}`; } listItem.textContent = msg; list.appendChild(listItem); }); ``` {{EmbedLiveSample('Animated_circle', '100%', '270')}} ### Event handler property equivalent Note that you can also create an event listener for the `begin` event using the `onbegin` event handler property: ```js animateElem.onbegin = () => { console.log("beginEvent fired"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [SVG animation with SMIL](/en-US/docs/Web/SVG/SVG_animation_with_SMIL) - {{domxref("SVGAnimationElement.endEvent_event", "endEvent")}} event - {{domxref("SVGAnimationElement.repeatEvent_event", "repeatEvent")}} event
0
data/mdn-content/files/en-us/web/api/svganimationelement
data/mdn-content/files/en-us/web/api/svganimationelement/endevent_event/index.md
--- title: "SVGAnimationElement: endEvent event" short-title: endEvent slug: Web/API/SVGAnimationElement/endEvent_event page-type: web-api-event browser-compat: api.SVGAnimationElement.endEvent_event --- {{APIRef("SVG")}} The **`endEvent`** event of the {{domxref("SVGAnimationElement")}} interface is fired when at the active end of the animation is reached. > **Note:** This event is not raised at the simple end of each animation repeat. This event may be raised both in the course of normal (i.e. scheduled or interactive) timeline play, as well as in the case that the element was ended with a DOM method. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("endEvent", (event) => {}); onend = (event) => {}; ``` ## Event type A {{domxref("TimeEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("TimeEvent")}} ## Event properties - {{domxref("TimeEvent.detail")}} {{ReadOnlyInline}} - : A `long` that specifies some detail information about the Event, depending on the type of the event. For this event type, indicates the repeat number for the animation. - {{domxref("TimeEvent.view")}} {{ReadOnlyInline}} - : A {{glossary("WindowProxy")}} that identifies the Window from which the event was generated. ## Examples ### Animated circle ```html <svg xmlns="http://www.w3.org/2000/svg" width="300px" height="100px"> <title>SVG SMIL Animate with Path</title> <circle cx="0" cy="50" r="50" fill="blue" stroke="black" stroke-width="1"> <animateMotion path="M 0 0 H 300 Z" dur="5s" repeatCount="indefinite" /> </circle> </svg> <hr /> <button>Stop animation</button> <ul></ul> ``` ```css ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } ``` ```js let svgElem = document.querySelector("svg"); let animateElem = document.querySelector("animateMotion"); let list = document.querySelector("ul"); let btn = document.querySelector("button"); animateElem.addEventListener("beginEvent", () => { let listItem = document.createElement("li"); listItem.textContent = "beginEvent fired"; list.appendChild(listItem); }); animateElem.addEventListener("endEvent", () => { let listItem = document.createElement("li"); listItem.textContent = "endEvent fired"; list.appendChild(listItem); }); animateElem.addEventListener("repeatEvent", (e) => { let listItem = document.createElement("li"); let msg = "repeatEvent fired"; if (e.detail) { msg += `; repeat number: ${e.detail}`; } listItem.textContent = msg; list.appendChild(listItem); }); btn.addEventListener("click", () => { btn.disabled = true; animateElem.setAttribute("repeatCount", "1"); }); ``` {{EmbedLiveSample('Animated_circle', '100%', '300')}} ### Event handler property equivalent Note that you can also create an event listener for the `end` event using the `onend` event handler property: ```js animateElem.onend = () => { console.log("endEvent fired"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [SVG animation with SMIL](/en-US/docs/Web/SVG/SVG_animation_with_SMIL) - {{domxref("SVGAnimationElement.beginEvent_event", "beginEvent")}} event - {{domxref("SVGAnimationElement.repeatEvent_event", "repeatEvent")}} event
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/eckeygenparams/index.md
--- title: EcKeyGenParams slug: Web/API/EcKeyGenParams page-type: web-api-interface spec-urls: https://w3c.github.io/webcrypto/#dfn-EcKeyGenParams --- {{ APIRef("Web Crypto API") }} The **`EcKeyGenParams`** 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.generateKey()")}}, when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as either of [ECDSA](/en-US/docs/Web/API/SubtleCrypto/sign#ecdsa) or [ECDH](/en-US/docs/Web/API/SubtleCrypto/deriveKey#ecdh). ## Instance properties - `name` - : A string. This should be set to `ECDSA` or `ECDH`, depending on the algorithm you want to use. - `namedCurve` - : A string representing the name of the elliptic curve to use. This may be any of the following names for [NIST](https://www.nist.gov/)-approved curves: - `P-256` - `P-384` - `P-521` ## Examples See the examples for {{domxref("SubtleCrypto.generateKey()")}}. ## Specifications {{Specifications}} ## Browser compatibility Browsers that support the "ECDH" or "ECDSA" algorithms for the {{domxref("SubtleCrypto.generateKey()")}} method will support this type. ## See also - {{domxref("SubtleCrypto.generateKey()")}}.
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgfontfaceurielement/index.md
--- title: SVGFontFaceUriElement slug: Web/API/SVGFontFaceUriElement page-type: web-api-interface status: - deprecated browser-compat: api.SVGFontFaceUriElement --- {{APIRef("SVG")}}{{deprecated_header}} The **`SVGFontFaceUriElement`** interface corresponds to the {{SVGElement("font-face-uri")}} elements. Object-oriented access to the attributes of the {{SVGElement("font-face-uri")}} element via the SVG DOM is not possible. {{InheritanceDiagram}} ## Instance properties _This interface has no properties but inherits properties from its parent, {{domxref("SVGElement")}}._ ## Instance methods _This interface has no methods but inherits methods from its parent, {{domxref("SVGElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{SVGElement("font-face-uri")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/hkdfparams/index.md
--- title: HkdfParams slug: Web/API/HkdfParams page-type: web-api-interface spec-urls: https://w3c.github.io/webcrypto/#dfn-HkdfParams --- {{ APIRef("Web Crypto API") }} The **`HkdfParams`** 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.deriveKey()")}}, when using the [HKDF](/en-US/docs/Web/API/SubtleCrypto/deriveKey#hkdf) algorithm. ## Instance properties - `name` - : A string. This should be set to `HKDF`. - `hash` - : A string representing the [digest algorithm](/en-US/docs/Web/API/SubtleCrypto/digest#supported_algorithms) to use. This may be one of: - `SHA-1` - `SHA-256` - `SHA-384` - `SHA-512` - `salt` - : An {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, or a {{jsxref("DataView")}}. The [HKDF specification](https://datatracker.ietf.org/doc/html/rfc5869) states that adding salt "adds significantly to the strength of HKDF". Ideally, the salt is a random or pseudo-random value with the same length as the output of the digest function. Unlike the input key material passed into `deriveKey()`, salt does not need to be kept secret. - `info` - : An {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, or a {{jsxref("DataView")}} representing application-specific contextual information. This is used to bind the derived key to an application or context, and enables you to derive different keys for different contexts while using the same input key material. It's important that this should be independent of the input key material itself. This property is required but may be an empty buffer. ## Examples See the examples for {{domxref("SubtleCrypto.deriveKey()")}}. ## Specifications {{Specifications}} ## Browser compatibility Browsers that support the "HKDF" algorithm for the {{domxref("SubtleCrypto.deriveKey()")}} method will support this type. ## See also - {{domxref("SubtleCrypto.deriveKey()")}}.
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/performanceobserver/index.md
--- title: PerformanceObserver slug: Web/API/PerformanceObserver page-type: web-api-interface browser-compat: api.PerformanceObserver --- {{APIRef("Performance API")}} {{AvailableInWorkers}} The **`PerformanceObserver`** interface is used to observe performance measurement events and be notified of new {{domxref("PerformanceEntry","performance entries", '', 'true')}} as they are recorded in the browser's _performance timeline_. ## Constructor - {{domxref("PerformanceObserver.PerformanceObserver","PerformanceObserver()")}} - : Creates and returns a new `PerformanceObserver` object. ## Static properties - {{domxref("PerformanceObserver.supportedEntryTypes_static", "PerformanceObserver.supportedEntryTypes")}} {{ReadOnlyInline}} - : Returns an array of the {{domxref("PerformanceEntry.entryType","entryType")}} values supported by the user agent. ## Instance methods - {{domxref("PerformanceObserver.observe","PerformanceObserver.observe()")}} - : Specifies the set of entry types to observe. The performance observer's callback function will be invoked when performance entry is recorded for one of the specified `entryTypes`. - {{domxref("PerformanceObserver.disconnect","PerformanceObserver.disconnect()")}} - : Stops the performance observer callback from receiving performance entries. - {{domxref("PerformanceObserver.takeRecords","PerformanceObserver.takeRecords()")}} - : Returns the current list of performance entries stored in the performance observer, emptying it out. ## Examples ### Creating a PerformanceObserver The following example creates a `PerformanceObserver` watching for "mark" ({{domxref("PerformanceMark")}}) and "measure" ({{domxref("PerformanceMeasure")}}) events. The `perfObserver` callback provides a `list` ({{domxref("PerformanceObserverEntryList")}}) which allows you to get observed performance entries. ```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}} ## See also - {{domxref('MutationObserver')}} - {{domxref('ResizeObserver')}} - {{domxref('IntersectionObserver')}}
0
data/mdn-content/files/en-us/web/api/performanceobserver
data/mdn-content/files/en-us/web/api/performanceobserver/takerecords/index.md
--- title: "PerformanceObserver: takeRecords() method" short-title: takeRecords() slug: Web/API/PerformanceObserver/takeRecords page-type: web-api-instance-method browser-compat: api.PerformanceObserver.takeRecords --- {{APIRef("Performance API")}} The **`takeRecords()`** method of the {{domxref('PerformanceObserver')}} interface returns the current list of {{domxref("PerformanceEntry","performance entries")}} stored in the performance observer, emptying it out. ## Syntax ```js-nolint takeRecords() ``` ### Parameters None. ### Return value A list of {{domxref("PerformanceEntry")}} objects. ## Examples ### Taking records The following example stores the current list of performance entries into `records` and empties the performance observer. ```js const observer = new PerformanceObserver((list, obj) => { list.getEntries().forEach((entry) => { // Process "mark" and "measure" events }); }); observer.observe({ entryTypes: ["mark", "measure"] }); const records = observer.takeRecords(); console.log(records[0].name); console.log(records[0].startTime); console.log(records[0].duration); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performanceobserver
data/mdn-content/files/en-us/web/api/performanceobserver/observe/index.md
--- title: "PerformanceObserver: observe() method" short-title: observe() slug: Web/API/PerformanceObserver/observe page-type: web-api-instance-method browser-compat: api.PerformanceObserver.observe --- {{APIRef("Performance API")}} The **`observe()`** method of the **{{domxref("PerformanceObserver")}}** interface is used to specify the set of performance entry types to observe. See {{domxref("PerformanceEntry.entryType")}} for a list of entry types and {{domxref("PerformanceObserver.supportedEntryTypes_static", "PerformanceObserver.supportedEntryTypes")}} for a list of entry types the user agent supports. When a matching performance entry is recorded, the performance observer's callback functionβ€”set when creating the {{domxref("PerformanceObserver")}}β€”is invoked. ## Syntax ```js-nolint observe(options) ``` ### Parameters - `options` - : An object with the following possible members: - `buffered` - : A boolean flag to indicate whether buffered entries should be queued into the observer's buffer. Must be used only with the "`type`" option. - `durationThreshold` - : A {{domxref("DOMHighResTimeStamp")}} defining the threshold for {{domxref("PerformanceEventTiming")}} entries. Defaults to 104ms and is rounded to the nearest of 8ms. Lowest possible threshold is 16ms. May not be used together with the `entryTypes` option. - `entryTypes` - : An array of string objects, each specifying one performance entry type to observe. May not be used together with the "`type`", "`buffered`", or "`durationThreshold`" options. See {{domxref("PerformanceEntry.entryType")}} for a list of valid performance entry type names. Unrecognized types are ignored, though the browser may output a warning message to the console to help developers debug their code. If no valid types are found, `observe()` has no effect. - `type` - : A single string specifying exactly one performance entry type to observe. May not be used together with the `entryTypes` option. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Watching multiple performance entry types This example creates a `PerformanceObserver` and watches for `"mark"` and `"measure"` entry types as specified by the `entryTypes` option given in the `observe()` method. ```js const observer = new PerformanceObserver((list, obj) => { list.getEntries().forEach((entry) => { // Process "mark" and "measure" events }); }); observer.observe({ entryTypes: ["mark", "measure"] }); ``` ### Watching a single performance entry type The following example retrieves buffered events and subscribes to newer events for resource timing events ({{domxref("PerformanceResourceTiming")}}) using the `buffered` and `type` configuration options. Whenever you need to configure the observer to use the `buffered` or `durationThreshold` option, use `type` instead of `entryType`. Collecting multiple types of performance entry types will not work otherwise. ```js const observer = new PerformanceObserver((list, obj) => { list.getEntries().forEach((entry) => { // Process "resource" events }); }); observer.observe({ type: "resource", buffered: true }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performanceobserver
data/mdn-content/files/en-us/web/api/performanceobserver/supportedentrytypes_static/index.md
--- title: "PerformanceObserver: supportedEntryTypes static property" short-title: supportedEntryTypes slug: Web/API/PerformanceObserver/supportedEntryTypes_static page-type: web-api-static-property browser-compat: api.PerformanceObserver.supportedEntryTypes_static --- {{APIRef("Performance API")}} The static **`supportedEntryTypes`** read-only property of the {{domxref("PerformanceObserver")}} interface returns an array of the {{domxref("PerformanceEntry.entryType","entryType")}} values supported by the user agent. As the list of supported entries varies per browser and is evolving, this property allows web developers to check which are available. ## Value An array of {{domxref("PerformanceEntry.entryType")}} values. ## Examples ### Using the console to check supported types To find out which {{domxref("PerformanceEntry.entryType","entryType")}} values a browser supports, enter <kbd>PerformanceObserver.supportedEntryTypes</kbd> into the console. This will return an array of supported values. ```js PerformanceObserver.supportedEntryTypes; // returns ["element", "event", "first-input", "largest-contentful-paint", "layout-shift", "longtask", "mark", "measure", "navigation", "paint", "resource"] in Chrome 89 ``` ### Checking for unsupported types The following function checks for support of an array of possible entry types. The unsupported types are logged to the console, however this information could be logged to client-side analytics to indicate that the particular type could not be observed. ```js function detectSupport(entryTypes) { for (const entryType of entryTypes) { if (!PerformanceObserver.supportedEntryTypes.includes(entryType)) { console.log(entryType); } } } detectSupport(["resource", "mark", "first-input", "largest-contentful-paint"]); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performanceobserver
data/mdn-content/files/en-us/web/api/performanceobserver/performanceobserver/index.md
--- title: "PerformanceObserver: PerformanceObserver() constructor" short-title: PerformanceObserver() slug: Web/API/PerformanceObserver/PerformanceObserver page-type: web-api-constructor browser-compat: api.PerformanceObserver.PerformanceObserver --- {{APIRef("Performance API")}} The **`PerformanceObserver()`** constructor creates a new {{domxref("PerformanceObserver")}} object with the given observer `callback`. The observer callback is invoked when {{domxref("PerformanceEntry","performance entry events", '', 'true')}} are recorded for the {{domxref("PerformanceEntry.entryType","entry types",'','true')}} that have been registered, via the {{domxref("PerformanceObserver.observe","observe()")}} method. ## Syntax ```js-nolint new PerformanceObserver(callback) ``` ### Parameters - `callback` - : A `PerformanceObserverCallback` callback that will be invoked when observed performance events are recorded. When the callback is invoked, the following parameters are available: - `entries` - : The {{domxref("PerformanceObserverEntryList","list of performance observer entries", '', 'true')}}. - `observer` - : The {{domxref("PerformanceObserver","observer")}} object that is receiving the above entries. - `droppedEntriesCount` {{optional_inline}} - : The number of buffered entries which got dropped from the buffer due to the buffer being full. See the [`buffered`](/en-US/docs/Web/API/PerformanceObserver/observe#parameters) flag. ### Return value A new {{domxref("PerformanceObserver")}} object which will call the specified `callback` when observed performance events occur. ## Examples ### Creating a PerformanceObserver The following example creates a `PerformanceObserver` watching for "mark" ({{domxref("PerformanceMark")}}) and "measure" ({{domxref("PerformanceMeasure")}}) events. The `perfObserver` callback provides a `list` ({{domxref("PerformanceObserverEntryList")}}) which allows you get observed performance entries. ```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"] }); ``` ### Dropped buffer entries You can use {{domxref("PerformanceObserver")}} with a `buffered` flag to listen to past performance entries. There is a buffer size limit, though. The performance observer callback contains an optional `droppedEntriesCount` parameter that informs you about the amount of lost entries due to the buffer storage being full. ```js function perfObserver(list, observer, droppedEntriesCount) { list.getEntries().forEach((entry) => { // do something with the entries }); if (droppedEntriesCount > 0) { console.warn( `${droppedEntriesCount} entries got dropped due to the buffer being full.`, ); } } const observer = new PerformanceObserver(perfObserver); observer.observe({ type: "resource", buffered: true }); ``` Usually, there are a lot of resource timing entries, and for these entries specifically, you can also set a larger buffer using {{domxref("performance.setResourceTimingBufferSize()")}} and watch for the {{domxref("Performance/resourcetimingbufferfull_event", "resourcetimingbufferfull")}} event. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performanceobserver
data/mdn-content/files/en-us/web/api/performanceobserver/disconnect/index.md
--- title: "PerformanceObserver: disconnect() method" short-title: disconnect() slug: Web/API/PerformanceObserver/disconnect page-type: web-api-instance-method browser-compat: api.PerformanceObserver.disconnect --- {{APIRef("Performance API")}} The **`disconnect()`** method of the {{domxref('PerformanceObserver')}} interface is used to stop the performance observer from receiving any {{domxref("PerformanceEntry","performance entry", '', 'true')}} events. ## Syntax ```js-nolint disconnect() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Stopping a performance observer The following example disconnects the performance observer to disable receiving any more performance entry events. ```js const observer = new PerformanceObserver((list, obj) => { list.getEntries().forEach((entry) => { // Process "measure" events // … // Disable additional performance events observer.disconnect(); }); }); observer.observe({ entryTypes: ["mark", "measure"] }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/deviceorientationevent/index.md
--- title: DeviceOrientationEvent slug: Web/API/DeviceOrientationEvent page-type: web-api-interface browser-compat: api.DeviceOrientationEvent --- {{apiref("Device Orientation Events")}}{{securecontext_header}} The **`DeviceOrientationEvent`** interface of the {{domxref("Device Orientation Events", "", "", "nocode")}} provides web developers with information from the physical orientation of the device running the web page. {{InheritanceDiagram}} ## Constructor - {{domxref("DeviceOrientationEvent.DeviceOrientationEvent","DeviceOrientationEvent.DeviceOrientationEvent()")}} - : Creates a new `DeviceOrientationEvent`. ## Instance properties - {{domxref("DeviceOrientationEvent.absolute")}} {{ReadOnlyInline}} - : A boolean that indicates whether or not the device is providing orientation data absolutely. - {{domxref("DeviceOrientationEvent.alpha")}} {{ReadOnlyInline}} - : A number representing the motion of the device around the z axis, express in degrees with values ranging from 0 (inclusive) to 360 (exclusive). - {{domxref("DeviceOrientationEvent.beta")}} {{ReadOnlyInline}} - : A number representing the motion of the device around the x axis, express in degrees with values ranging from -180 (inclusive) to 180 (exclusive). This represents a front to back motion of the device. - {{domxref("DeviceOrientationEvent.gamma")}} {{ReadOnlyInline}} - : A number representing the motion of the device around the y axis, express in degrees with values ranging from -90 (inclusive) to 90 (exclusive). This represents a left to right motion of the device. - `DeviceOrientationEvent.webkitCompassHeading` {{Non-Standard_Inline}} {{ReadOnlyInline}} - : A number represents the difference between the motion of the device around the z axis of the world system and the direction of the north, express in degrees with values ranging from 0 to 360. - `DeviceOrientationEvent.webkitCompassAccuracy` {{Non-Standard_Inline}} {{ReadOnlyInline}} - : The accuracy of the compass means that the deviation is positive or negative. It's usually 10. ## Example ```js window.addEventListener("deviceorientation", (event) => { console.log(`${event.alpha} : ${event.beta} : ${event.gamma}`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Device orientation events/Detecting device orientation", "Detecting device orientation", "", "nocode")}} - {{domxref("Device orientation events/Orientation and motion data explained", "Orientation and motion data explained", "", "nocode")}} - {{domxref("DeviceMotionEvent")}} - {{domxref("Window.devicemotion_event", "devicemotion")}} event - {{domxref("Window.deviceorientation_event", "deviceorientation")}} event - {{domxref("Window.deviceorientationabsolute_event", "deviceorientationabsolute")}} event
0
data/mdn-content/files/en-us/web/api/deviceorientationevent
data/mdn-content/files/en-us/web/api/deviceorientationevent/gamma/index.md
--- title: "DeviceOrientationEvent: gamma property" short-title: gamma slug: Web/API/DeviceOrientationEvent/gamma page-type: web-api-instance-property browser-compat: api.DeviceOrientationEvent.gamma --- {{APIRef("Device Orientation Events")}}{{securecontext_header}} The **`gamma`** read-only property of the {{domxref("DeviceOrientationEvent")}} interface returns the rotation of the device around the Y axis; that is, the number of degrees, ranged between `-90` and `90`, by which the device is tilted left or right. See [Orientation and motion data explained](/en-US/docs/Web/API/Device_orientation_events/Orientation_and_motion_data_explained) for details. ## Value A number. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Device orientation events/Detecting device orientation", "Detecting device orientation", "", "nocode")}} - {{domxref("Device orientation events/Orientation and motion data explained", "Orientation and motion data explained", "", "nocode")}} - {{domxref("Window.deviceorientation_event", "deviceorientation")}} event - {{domxref("Window.deviceorientationabsolute_event", "deviceorientationabsolute")}} event
0
data/mdn-content/files/en-us/web/api/deviceorientationevent
data/mdn-content/files/en-us/web/api/deviceorientationevent/beta/index.md
--- title: "DeviceOrientationEvent: beta property" short-title: beta slug: Web/API/DeviceOrientationEvent/beta page-type: web-api-instance-property browser-compat: api.DeviceOrientationEvent.beta --- {{APIRef("Device Orientation Events")}}{{securecontext_header}} The **`beta`** read-only property of the {{domxref("DeviceOrientationEvent")}} interface returns the rotation of the device around the X axis; that is, the number of degrees, ranged between -180 and 180, by which the device is tipped forward or backward. See [Orientation and motion data explained](/en-US/docs/Web/API/Device_orientation_events/Orientation_and_motion_data_explained) for details. ## Value A number. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Device orientation events/Detecting device orientation", "Detecting device orientation", "", "nocode")}} - {{domxref("Device orientation events/Orientation and motion data explained", "Orientation and motion data explained", "", "nocode")}} - {{domxref("Window.deviceorientation_event", "deviceorientation")}} event - {{domxref("Window.deviceorientationabsolute_event", "deviceorientationabsolute")}} event
0
data/mdn-content/files/en-us/web/api/deviceorientationevent
data/mdn-content/files/en-us/web/api/deviceorientationevent/deviceorientationevent/index.md
--- title: "DeviceOrientationEvent: DeviceOrientationEvent() constructor" short-title: DeviceOrientationEvent() slug: Web/API/DeviceOrientationEvent/DeviceOrientationEvent page-type: web-api-constructor browser-compat: api.DeviceOrientationEvent.DeviceOrientationEvent --- {{APIRef("Device Orientation Events")}}{{securecontext_header}} The **`DeviceOrientationEvent()`** constructor creates a new {{domxref("DeviceOrientationEvent")}} object. ## Syntax ```js-nolint new DeviceOrientationEvent(type) new DeviceOrientationEvent(type, options) ``` ### Parameters - `type` - : A string with the name of the event. It is case-sensitive and browsers set it to `deviceorientation` or `deviceorientationabsolute`. In the latter case, `options.absolute` is always `true`. - `options` {{optional_inline}} - : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties: - `alpha` {{optional_inline}} - : A number representing the motion of the device around the z axis, expressed in degrees with values ranging from 0 to 360. It defaults to `null`. - `beta` {{optional_inline}} - : A number representing the motion of the device around the x axis, expressed in degrees with values ranging from -180 to 180. This represents a front to back motion of the device. It defaults to `null`. - `gamma` {{optional_inline}} - : A number representing the motion of the device around the y axis, expressed in degrees with values ranging from -90 to 90. This represents a left to right motion of the device. It defaults to `null`. - `absolute` - : A boolean value that indicates whether or not the device is providing orientation data absolutely. It defaults to `false`. ## Return value A new {{domxref("DeviceOrientationEvent")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/deviceorientationevent
data/mdn-content/files/en-us/web/api/deviceorientationevent/alpha/index.md
--- title: "DeviceOrientationEvent: alpha property" short-title: alpha slug: Web/API/DeviceOrientationEvent/alpha page-type: web-api-instance-property browser-compat: api.DeviceOrientationEvent.alpha --- {{APIRef("Device Orientation Events")}}{{securecontext_header}} The **`alpha`** read-only property of the {{domxref("DeviceOrientationEvent")}} interface returns the rotation of the device around the Z axis; that is, the number of degrees by which the device is being twisted around the center of the screen. See [Orientation and motion data explained](/en-US/docs/Web/API/Device_orientation_events/Orientation_and_motion_data_explained) for details. ## Value A number. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Device orientation events/Detecting device orientation", "Detecting device orientation", "", "nocode")}} - {{domxref("Device orientation events/Orientation and motion data explained", "Orientation and motion data explained", "", "nocode")}} - {{domxref("Window.deviceorientation_event", "deviceorientation")}} event - {{domxref("Window.deviceorientationabsolute_event", "deviceorientationabsolute")}} event
0
data/mdn-content/files/en-us/web/api/deviceorientationevent
data/mdn-content/files/en-us/web/api/deviceorientationevent/absolute/index.md
--- title: "DeviceOrientationEvent: absolute property" short-title: absolute slug: Web/API/DeviceOrientationEvent/absolute page-type: web-api-instance-property browser-compat: api.DeviceOrientationEvent.absolute --- {{APIRef("Device Orientation Events")}}{{securecontext_header}} The **`absolute`** read-only property of the {{domxref("DeviceOrientationEvent")}} interface indicates whether or not the device is providing orientation data absolutely (that is, in reference to the Earth's coordinate frame) or using some arbitrary frame determined by the device. See [Orientation and motion data explained](/en-US/docs/Web/API/Device_orientation_events/Orientation_and_motion_data_explained) for details. ## Value - `true` if the orientation data in `instanceOfDeviceOrientationEvent` is provided as the difference between the Earth's coordinate frame and the device's coordinate frame - `false` if the orientation data is being provided in reference to some arbitrary, device-determined coordinate frame. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Device orientation events/Detecting device orientation", "Detecting device orientation", "", "nocode")}} - {{domxref("Device orientation events/Orientation and motion data explained", "Orientation and motion data explained", "", "nocode")}} - {{domxref("Window.deviceorientation_event", "deviceorientation")}} event - {{domxref("Window.deviceorientationabsolute_event", "deviceorientationabsolute")}} event
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/fileentrysync/index.md
--- title: FileEntrySync slug: Web/API/FileEntrySync page-type: web-api-interface status: - deprecated - non-standard browser-compat: api.FileEntrySync --- {{APIRef("File and Directory Entries API")}} {{Non-standard_header}}{{Deprecated_Header}} The `FileEntrySync` interface represents a file in a file system. It lets you write content to a file. > **Warning:** This interface is deprecated and is no more on the standard track. > _Do not use it anymore._ Use the [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API) instead. ## Basic concepts To write content to file, create a FileWriter object by calling [`createWriter()`](#createwriter). ## Method overview <table class="standard-table"> <tbody> <tr> <td> <code>FileWriterSync <a href="#createreader" title="#createWriter">createWriter</a> ()); </code> </td> </tr> <tr> <td> <code>File <a href="#file">file</a> ());</code> </td> </tr> </tbody> </table> ## Instance methods ### createWriter() Creates a new `FileWriter` associated with the file that the `FileEntry` represents. ```webidl void createWriter(); ``` #### Parameter None. #### Returns A `FileWriterSync` object. #### Exceptions This method can raise a [DOMException](/en-US/docs/Web/API/DOMException) with the following codes: | Exception | Description | | ------------------- | ------------------------------------------------------------------------------ | | `NOT_FOUND_ERR` | The file does not exist. | | `INVALID_STATE_ERR` | The file is no longer valid for some reason other than it having been deleted. | ### file() Returns a File that represents the current state of the file that this `FileEntry` represents. ```webidl void file(); ``` #### Parameter None. #### Returns A `File` object. #### Exceptions This method can raise a [DOMException](/en-US/docs/Web/API/DOMException) with the following codes: | Exception | Description | | ------------------- | ------------------------------------------------------------------------------ | | `NOT_FOUND_ERR` | The file does not exist. | | `INVALID_STATE_ERR` | The file is no longer valid for some reason other than it having been deleted. | ## Specifications This feature is not part of any specification anymore. It is no longer on track to become a standard. ## Browser compatibility {{Compat}} ## See also - [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction) - [Basic Concepts About the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/contactsmanager/index.md
--- title: ContactsManager slug: Web/API/ContactsManager page-type: web-api-interface status: - experimental browser-compat: api.ContactsManager --- {{securecontext_header}}{{APIRef("Contact Picker API")}}{{SeeCompatTable}} The **`ContactsManager`** interface of the {{domxref('Contact Picker API')}} allows users to select entries from their contact list and share limited details of the selected entries with a website or application. The `ContactsManager` is available through the global {{domxref('navigator.contacts')}} property. ## Instance methods - {{domxref('ContactsManager.select','select()')}} {{Experimental_Inline}} - : Returns a {{jsxref('Promise')}} which, when resolved, presents the user with a contact picker which allows them to select contact(s) they wish to share. - {{domxref('ContactsManager.getProperties()','getProperties()')}} {{Experimental_Inline}} - : Returns a {{jsxref('Promise')}} which resolves with an {{jsxref('Array')}} of {{jsxref('String','strings')}} indicating which contact properties are available. ## Examples ### Feature Detection The following code checks whether the Contact Picker API is supported. ```js const supported = "contacts" in navigator && "ContactsManager" in window; ``` ### Checking for Supported Properties The following asynchronous function uses the `getProperties` method to check for supported properties. ```js async function checkProperties() { const supportedProperties = await navigator.contacts.getProperties(); if (supportedProperties.includes("name")) { // run code for name support } if (supportedProperties.includes("email")) { // run code for email support } if (supportedProperties.includes("tel")) { // run code for telephone number support } if (supportedProperties.includes("address")) { // run code for address support } if (supportedProperties.includes("icon")) { // run code for avatar support } } ``` ### Selecting Contacts The following example sets an array of properties to be retrieved for each contact, as well as setting an options object to allow for multiple contacts to be selected. An asynchronous function is then defined which uses the `select()` method to present the user with a contact picker interface and handle the chosen results. ```js const props = ["name", "email", "tel", "address", "icon"]; const opts = { multiple: true }; async function getContacts() { try { const contacts = await navigator.contacts.select(props, opts); handleResults(contacts); } catch (ex) { // Handle any errors here. } } ``` `handleResults()` is a developer defined function. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [A Contact Picker for the Web](https://developer.chrome.com/docs/capabilities/web-apis/contact-picker) - [A Contact Picker demo on glitch](https://contact-picker.glitch.me/)
0
data/mdn-content/files/en-us/web/api/contactsmanager
data/mdn-content/files/en-us/web/api/contactsmanager/select/index.md
--- title: "ContactsManager: select() method" short-title: select() slug: Web/API/ContactsManager/select page-type: web-api-instance-method status: - experimental browser-compat: api.ContactsManager.select --- {{securecontext_header}}{{APIRef("Contact Picker API")}}{{SeeCompatTable}} The **`select()`** method of the {{domxref("ContactsManager")}} interface returns a {{jsxref('Promise')}} which, when resolved, presents the user with a contact picker which allows them to select contact(s) they wish to share. This method requires a user gesture for the {{jsxref('Promise')}} to resolve. ## Syntax ```js-nolint select(properties) select(properties, options) ``` ### Parameters - `properties` - : An array of {{jsxref('String', 'strings')}} defining what information to retrieve from a contact. Allowed values are as follows: - `'name'`: The contact's name. - `'tel'`: The telephone number(s) of the contact. - `'email'`: The email address of the contact. - `'address'`: The contact's postal address. - `'icon'`: The avatar of the contact. - `options` {{optional_inline}} - : Options are as follows: - `multiple` - : A Boolean that allows multiple contacts to be selected. The default is `false`. ### Return value Returns a {{jsxref('Promise')}} that resolves with an array of objects containing contact information. Each object represents a single contact may contain the following properties: - `address` - : An {{jsxref("Array")}} of {{domxref("ContactAddress")}} objects, each containing specifics of a unique physical address. - `email` - : An array of strings containing email addresses. - `icon` - : An array of {{domxref("Blob")}} objects containing images of an individual. - `name` - : An array strings, each containing a unique name of an individual. - `tel` - : An array strings, each containing a unique phone number of an individual. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Returned if the browsing context is not top-level, if the contact picker shows a flag that denotes an already existing contact picker since only one picker can exist at any time, or if launching a contact picker failed. - `SecurityError` {{domxref("DOMException")}} - : Returned if the method is not triggered by [user activation](/en-US/docs/Web/Security/User_activation). - {{jsxref("TypeError")}} - : Returned if `properties` is empty, or if any of the specified properties are not supported. ## Security {{Glossary("Transient activation")}} is required. The user has to interact with the page or a UI element in order for this feature to work. ## Examples ### Basic Example The following example sets an array of properties to be retrieved for each contact, as well as setting an options object to allow for multiple contacts to be selected. An asynchronous function is then defined which uses the `select()` method to present the user with a contact picker interface and handle the chosen results. `handleResults()` is a developer defined function. ```js const props = ["name", "email", "tel", "address", "icon"]; const opts = { multiple: true }; async function getContacts() { try { const contacts = await navigator.contacts.select(props, opts); handleResults(contacts); } catch (ex) { // Handle any errors here. } } ``` ### Select Using Only Supported Properties The following example uses {{domxref("ContactsManager.getProperties", "getProperties()")}} to ensure that only supported properties are passed. Otherwise, `select()` might throw a {{jsxref("TypeError")}}. `handleResults()` is a developer defined function. ```js const supportedProperties = await navigator.contacts.getProperties(); async function getContacts() { try { const contacts = await navigator.contacts.select(supportedProperties); handleResults(contacts); } catch (ex) { // Handle any errors here. } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/contactsmanager
data/mdn-content/files/en-us/web/api/contactsmanager/getproperties/index.md
--- title: "ContactsManager: getProperties() method" short-title: getProperties() slug: Web/API/ContactsManager/getProperties page-type: web-api-instance-method status: - experimental browser-compat: api.ContactsManager.getProperties --- {{securecontext_header}}{{APIRef("Contact Picker API")}}{{SeeCompatTable}} The **`getProperties()`** method of the {{domxref("ContactsManager")}} interface returns a {{jsxref('Promise')}} which resolves with an {{jsxref('Array')}} of {{jsxref('String','strings')}} indicating which contact properties are available. ## Syntax ```js-nolint getProperties() ``` ### Parameters This method receives no parameters. ### Return value Returns a {{jsxref('Promise')}} that resolves with an {{jsxref('Array')}} of {{jsxref('String','strings')}} naming the contact properties that can be returned by the current system. Properties can include the following: - `'name'`: The contact's name. - `'tel'`: The telephone number(s) of the contact. - `'email'`: The email address of the contact. - `'address'`: The contact's postal address. - `'icon'`: The avatar of the contact. ### Exceptions No exceptions are thrown. ## Examples ### Verify Property Support The following asynchronous function uses the `getProperties()` method to check whether the current system supports the `icon` property. ```js async function checkProperties() { const supportedProperties = await navigator.contacts.getProperties(); if (!supportedProperties.includes("icon")) { console.log("Your system does not support getting icons."); } } ``` ### Select Using Only Supported Properties The following example is similar to one for the {{domxref("ContactsManager.select", "select()")}} method. Instead of hard-coding the properties passed to `select()`, it uses `getProperties()` to ensure that only supported properties are passed. Otherwise, `select()` might throw a {{jsxref("TypeError")}}. `handleResults()` is a developer defined function. ```js const supportedProperties = await navigator.contacts.getProperties(); async function getContacts() { try { const contacts = await navigator.contacts.select(supportedProperties); handleResults(contacts); } catch (ex) { // Handle any errors here. } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/window/index.md
--- title: Window slug: Web/API/Window page-type: web-api-interface browser-compat: api.Window --- {{APIRef("DOM")}} The **`Window`** interface represents a window containing a {{glossary("DOM")}} document; the `document` property points to the [DOM document](/en-US/docs/Web/API/Document) loaded in that window. A window for a given document can be obtained using the {{domxref("document.defaultView")}} property. A global variable, `window`, representing the window in which the script is running, is exposed to JavaScript code. The `Window` interface is home to a variety of functions, namespaces, objects, and constructors which are not necessarily directly associated with the concept of a user interface window. However, the `Window` interface is a suitable place to include these items that need to be globally available. Many of these are documented in the [JavaScript Reference](/en-US/docs/Web/JavaScript/Reference) and the [DOM Reference](/en-US/docs/Web/API/Document_Object_Model). In a tabbed browser, each tab is represented by its own `Window` object; the global `window` seen by JavaScript code running within a given tab always represents the tab in which the code is running. That said, even in a tabbed browser, some properties and methods still apply to the overall window that contains the tab, such as {{Domxref("Window.resizeTo", "resizeTo()")}} and {{Domxref("Window.innerHeight", "innerHeight")}}. Generally, anything that can't reasonably pertain to a tab pertains to the window instead. {{InheritanceDiagram}} ## Instance properties _This interface inherits properties from the {{domxref("EventTarget")}} interface._ Note that properties which are objects (e.g., for overriding the prototype of built-in elements) are listed in a separate section below. - {{domxref("caches", "Window.caches")}} {{ReadOnlyInline}} - : Returns the {{domxref("CacheStorage")}} object associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests. - {{domxref("Window.navigator", "Window.clientInformation")}} {{ReadOnlyInline}} - : An alias for {{domxref("Window.navigator")}}. - {{domxref("Window.closed")}} {{ReadOnlyInline}} - : This property indicates whether the current window is closed or not. - {{domxref("Window.console")}} {{ReadOnlyInline}} - : Returns a reference to the console object which provides access to the browser's debugging console. - {{domxref("Window.cookieStore")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a reference to the {{domxref("CookieStore")}} object for the current document context. - {{domxref("Window.credentialless")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a boolean that indicates whether the current document was loaded inside a credentialless {{htmlelement("iframe")}}. See [IFrame credentialless](/en-US/docs/Web/Security/IFrame_credentialless) for more details. - {{domxref("crossOriginIsolated", "Window.crossOriginIsolated")}} {{ReadOnlyInline}} - : Returns a boolean value that indicates whether the website is in a cross-origin isolation state. - {{domxref("crypto_property", "Window.crypto")}} {{ReadOnlyInline}} - : Returns the browser crypto object. - {{domxref("Window.customElements")}} {{ReadOnlyInline}} - : Returns a reference to the {{domxref("CustomElementRegistry")}} object, which can be used to register new [custom elements](/en-US/docs/Web/API/Web_components/Using_custom_elements) and get information about previously registered custom elements. - {{domxref("Window.devicePixelRatio")}} {{ReadOnlyInline}} - : Returns the ratio between physical pixels and device independent pixels in the current display. - {{domxref("Window.document")}} {{ReadOnlyInline}} - : Returns a reference to the document that the window contains. - {{domxref("Window.documentPictureInPicture")}} {{ReadOnlyInline}} {{experimental_inline}} - : Returns a reference to the [document Picture-in-Picture](/en-US/docs/Web/API/Document_Picture-in-Picture_API) window for the current document context. - {{domxref("Window.frameElement")}} {{ReadOnlyInline}} - : Returns the element in which the window is embedded, or null if the window is not embedded. - {{domxref("Window.frames")}} {{ReadOnlyInline}} - : Returns an array of the subframes in the current window. - {{domxref("Window.fullScreen")}} {{Non-standard_Inline}} - : This property indicates whether the window is displayed in full screen or not. - {{domxref("Window.history")}} {{ReadOnlyInline}} - : Returns a reference to the history object. - {{domxref("indexedDB", "Window.indexedDB")}} {{ReadOnlyInline}} - : Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an {{domxref("IDBFactory")}} object. - {{domxref("Window.innerHeight")}} {{ReadOnlyInline}} - : Gets the height of the content area of the browser window including, if rendered, the horizontal scrollbar. - {{domxref("Window.innerWidth")}} {{ReadOnlyInline}} - : Gets the width of the content area of the browser window including, if rendered, the vertical scrollbar. - {{domxref("isSecureContext", "Window.isSecureContext")}} {{ReadOnlyInline}} - : Returns a boolean indicating whether the current context is secure (`true`) or not (`false`). - {{domxref("Window.launchQueue")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : When a [progressive web app](/en-US/docs/Web/Progressive_web_apps) (PWA) is launched with a [`launch_handler`](/en-US/docs/Web/Manifest/launch_handler) `client_mode` value of `focus-existing`, `navigate-new`, or `navigate-existing`, the `launchQueue` provides access to the {{domxref("LaunchQueue")}} class, which allows custom launch navigation handling to be implemented for the PWA. - {{domxref("Window.length")}} {{ReadOnlyInline}} - : Returns the number of frames in the window. See also {{domxref("window.frames")}}. - {{domxref("Window.localStorage")}} {{ReadOnlyInline}} - : Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it. - {{domxref("Window.location")}} - : Gets/sets the location, or current URL, of the window object. - {{domxref("Window.locationbar")}} {{ReadOnlyInline}} - : Returns the locationbar object. - {{domxref("Window.menubar")}} {{ReadOnlyInline}} - : Returns the menubar object. - {{domxref("Window.mozInnerScreenX")}} {{ReadOnlyInline}} {{Non-standard_Inline}} - : Returns the horizontal (X) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See `mozScreenPixelsPerCSSPixel` in `nsIDOMWindowUtils` for a conversion factor to adapt to screen pixels if needed. - {{domxref("Window.mozInnerScreenY")}} {{ReadOnlyInline}} {{Non-standard_Inline}} - : Returns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See `mozScreenPixelsPerCSSPixel` for a conversion factor to adapt to screen pixels if needed. - {{domxref("Window.name")}} - : Gets/sets the name of the window. - {{domxref("Window.navigation")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the current `window`'s associated {{domxref("Navigation")}} object. The entry point for the {{domxref("Navigation API")}}. - {{domxref("Window.navigator")}} {{ReadOnlyInline}} - : Returns a reference to the navigator object. - {{domxref("Window.opener")}} - : Returns a reference to the window that opened this current window. - {{domxref("origin", "Window.origin")}} {{ReadOnlyInline}} - : Returns the global object's origin, serialized as a string. - {{domxref("Window.originAgentCluster")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns `true` if this window belongs to an origin-keyed agent cluster. - {{domxref("Window.outerHeight")}} {{ReadOnlyInline}} - : Gets the height of the outside of the browser window. - {{domxref("Window.outerWidth")}} {{ReadOnlyInline}} - : Gets the width of the outside of the browser window. - {{domxref("Window.scrollX","Window.pageXOffset")}} {{ReadOnlyInline}} - : An alias for {{domxref("window.scrollX")}}. - {{domxref("Window.scrollY","Window.pageYOffset")}} {{ReadOnlyInline}} - : An alias for {{domxref("window.scrollY")}}. - {{domxref("Window.parent")}} {{ReadOnlyInline}} - : Returns a reference to the parent of the current window or subframe. - {{domxref("performance_property", "Window.performance")}} {{ReadOnlyInline}} - : Returns a {{domxref("Performance")}} object, which includes the {{domxref("Performance.timing", "timing")}} and {{domxref("Performance.navigation", "navigation")}} attributes, each of which is an object providing [performance-related](/en-US/docs/Web/API/Performance_API/Navigation_timing) data. See also [Using Navigation Timing](/en-US/docs/Web/API/Performance_API/Navigation_timing) for additional information and examples. - {{domxref("Window.personalbar")}} {{ReadOnlyInline}} - : Returns the personalbar object. - {{domxref("scheduler_property", "Window.scheduler")}} {{ReadOnlyInline}} - : Returns the {{domxref("Scheduler")}} object associated with the current context. This is the entry point for using the [Prioritized Task Scheduling API](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API). - {{domxref("Window.screen")}} {{ReadOnlyInline}} - : Returns a reference to the screen object associated with the window. - {{domxref("Window.screenX")}} and {{domxref("Window.screenLeft")}} {{ReadOnlyInline}} - : Both properties return the horizontal distance from the left border of the user's browser viewport to the left side of the screen. - {{domxref("Window.screenY")}} and {{domxref("Window.screenTop")}} {{ReadOnlyInline}} - : Both properties return the vertical distance from the top border of the user's browser viewport to the top side of the screen. - {{domxref("Window.scrollbars")}} {{ReadOnlyInline}} - : Returns the scrollbars object. - {{domxref("Window.scrollMaxX")}} {{Non-standard_Inline}} {{ReadOnlyInline}} - : The maximum offset that the window can be scrolled to horizontally, that is the document width minus the viewport width. - {{domxref("Window.scrollMaxY")}} {{Non-standard_Inline}} {{ReadOnlyInline}} - : The maximum offset that the window can be scrolled to vertically (i.e., the document height minus the viewport height). - {{domxref("Window.scrollX")}} {{ReadOnlyInline}} - : Returns the number of pixels that the document has already been scrolled horizontally. - {{domxref("Window.scrollY")}} {{ReadOnlyInline}} - : Returns the number of pixels that the document has already been scrolled vertically. - {{domxref("Window.self")}} {{ReadOnlyInline}} - : Returns an object reference to the window object itself. - {{domxref("Window.sessionStorage")}} - : Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it. - {{domxref("Window.sharedStorage")}} {{ReadOnlyInline}} {{experimental_inline}} - : Returns the {{domxref("WindowSharedStorage")}} object for the current origin. This is the main entry point for writing data to shared storage using the [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API). - {{domxref("Window.speechSynthesis")}} {{ReadOnlyInline}} - : Returns a {{domxref("SpeechSynthesis")}} object, which is the entry point into using [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) speech synthesis functionality. - {{domxref("Window.statusbar")}} {{ReadOnlyInline}} - : Returns the statusbar object. - {{domxref("Window.toolbar")}} {{ReadOnlyInline}} - : Returns the toolbar object. - {{domxref("Window.top")}} {{ReadOnlyInline}} - : Returns a reference to the topmost window in the window hierarchy. This property is read only. - {{domxref("Window.visualViewport")}} {{ReadOnlyInline}} - : Returns a {{domxref("VisualViewport")}} object which represents the visual viewport for a given window. - {{domxref("Window.window")}} {{ReadOnlyInline}} - : Returns a reference to the current window. - `window[0]`, `window[1]`, etc. - : Returns a reference to the `window` object in the frames. See {{domxref("Window.frames")}} for more details. ### Deprecated properties - {{domxref("Window.event")}} {{Deprecated_Inline}} {{ReadOnlyInline}} - : Returns the **current event**, which is the event currently being handled by the JavaScript code's context, or `undefined` if no event is currently being handled. The {{domxref("Event")}} object passed directly to event handlers should be used instead whenever possible. - {{domxref("Window.external")}} {{Deprecated_Inline}} {{ReadOnlyInline}} - : Returns an object with functions for adding external search providers to the browser. - {{domxref("Window.orientation")}} {{Deprecated_Inline}} {{ReadOnlyInline}} - : Returns the orientation in degrees (in 90 degree increments) of the viewport relative to the device's natural orientation. - {{domxref("Window.sidebar")}} {{Deprecated_Inline}} {{Non-standard_Inline}} {{ReadOnlyInline}} - : Returns a reference to the window object of the sidebar - {{domxref("Window.status")}} {{Deprecated_Inline}} - : Gets/sets the text in the statusbar at the bottom of the browser. ## Instance methods _This interface inherits methods from the {{domxref("EventTarget")}} interface._ - {{domxref("atob", "Window.atob()")}} - : Decodes a string of data which has been encoded using base-64 encoding. - {{domxref("Window.alert()")}} - : Displays an alert dialog. - {{domxref("Window.blur()")}} - : Sets focus away from the window. - {{domxref("btoa", "Window.btoa()")}} - : Creates a base-64 encoded ASCII string from a string of binary data. - {{domxref("Window.cancelAnimationFrame()")}} - : Enables you to cancel a callback previously scheduled with {{domxref("Window.requestAnimationFrame")}}. - {{domxref("Window.cancelIdleCallback()")}} - : Enables you to cancel a callback previously scheduled with {{domxref("Window.requestIdleCallback")}}. - {{domxref("clearInterval", "Window.clearInterval()")}} - : Cancels the repeated execution set using {{domxref("setInterval()")}}. - {{domxref("clearTimeout()", "Window.clearTimeout()")}} - : Cancels the delayed execution set using {{domxref("setTimeout()")}}. - {{domxref("Window.close()")}} - : Closes the current window. - {{domxref("Window.confirm()")}} - : Displays a dialog with a message that the user needs to respond to. - {{domxref("createImageBitmap", "Window.createImageBitmap()")}} - : Accepts a variety of different image sources, and returns a {{jsxref("Promise")}} which resolves to an {{domxref("ImageBitmap")}}. Optionally the source is cropped to the rectangle of pixels originating at _(sx, sy)_ with width sw, and height sh. - {{domxref("Window.dump()")}} {{Non-standard_Inline}} - : Writes a message to the console. - {{domxref("fetch", "Window.fetch()")}} - : Starts the process of fetching a resource from the network. - {{domxref("Window.find()")}} {{Non-standard_Inline}} - : Searches for a given string in a window. - {{domxref("Window.focus()")}} - : Sets focus on the current window. - {{domxref("Window.getComputedStyle()")}} - : Gets computed style for the specified element. Computed style indicates the computed values of all CSS properties of the element. - {{domxref("Window.getDefaultComputedStyle()")}} {{Non-standard_Inline}} - : Gets default computed style for the specified element, ignoring author stylesheets. - {{domxref("Window.getScreenDetails()")}} {{experimental_inline}} {{securecontext_inline}} - : Returns a {{jsxref("Promise")}} that fulfills with a {{domxref("ScreenDetails")}} object instance representing the details of all the screens available to the user's device. - {{domxref("Window.getSelection()")}} - : Returns the selection object representing the selected item(s). - {{domxref("Window.matchMedia()")}} - : Returns a {{domxref("MediaQueryList")}} object representing the specified media query string. - {{domxref("Window.moveBy()")}} - : Moves the current window by a specified amount. - {{domxref("Window.moveTo()")}} - : Moves the window to the specified coordinates. - {{domxref("Window.open()")}} - : Opens a new window. - {{domxref("Window.postMessage()")}} - : Provides a secure means for one window to send a string of data to another window, which need not be within the same domain as the first. - {{domxref("Window.print()")}} - : Opens the Print Dialog to print the current document. - {{domxref("Window.prompt()")}} - : Returns the text entered by the user in a prompt dialog. - {{DOMxRef("Window.queryLocalFonts()")}} {{Experimental_Inline}} - : Returns a {{jsxref("Promise")}} that fulfills with an array of {{domxref("FontData")}} objects representing the font faces available locally. - {{domxref("queueMicrotask", "Window.queueMicrotask()")}} - : Queues a microtask to be executed at a safe time prior to control returning to the browser's event loop. - {{domxref("reportError", "Window.reportError()")}} - : Reports an error in a script, emulating an unhandled exception. - {{domxref("Window.requestAnimationFrame()")}} - : Tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame. - {{domxref("Window.requestIdleCallback()")}} - : Enables the scheduling of tasks during a browser's idle periods. - {{domxref("Window.resizeBy()")}} - : Resizes the current window by a certain amount. - {{domxref("Window.resizeTo()")}} - : Dynamically resizes window. - {{domxref("Window.scroll()")}} - : Scrolls the window to a particular place in the document. - {{domxref("Window.scrollBy()")}} - : Scrolls the document in the window by the given amount. - {{domxref("Window.scrollByLines()")}} {{Non-standard_Inline}} - : Scrolls the document by the given number of lines. - {{domxref("Window.scrollByPages()")}} {{Non-standard_Inline}} - : Scrolls the current document by the specified number of pages. - {{domxref("Window.scrollTo()")}} - : Scrolls to a particular set of coordinates in the document. - {{domxref("setInterval", "Window.setInterval()")}} - : Schedules a function to execute every time a given number of milliseconds elapses. - {{domxref("setTimeout()", "Window.setTimeout()")}} - : Schedules a function to execute in a given amount of time. - {{domxref("Window.showDirectoryPicker()")}} {{Experimental_Inline}} - : Displays a directory picker which allows the user to select a directory. - {{domxref("Window.showOpenFilePicker()")}} {{Experimental_Inline}} - : Shows a file picker that allows a user to select a file or multiple files. - {{domxref("Window.showSaveFilePicker()")}} {{Experimental_Inline}} - : Shows a file picker that allows a user to save a file. - {{domxref("Window.sizeToContent()")}} {{Non-standard_Inline}} - : Sizes the window according to its content. - {{domxref("Window.stop()")}} - : This method stops window loading. - {{domxref("structuredClone", "Window.structuredClone()")}} - : Creates a [deep clone](/en-US/docs/Glossary/Deep_copy) of a given value using the [structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). - {{domxref("Window.updateCommands()")}} {{Non-standard_Inline}} - : Updates the state of commands of the current chrome window (UI). ### Deprecated methods - {{domxref("Window.back()")}} {{Non-standard_Inline}} {{Deprecated_Inline}} - : Moves back one in the window history. This method is deprecated; you should instead use {{domxref("History.back", "history.back()")}}. - {{domxref("Window.captureEvents()")}} {{Deprecated_Inline}} - : Registers the window to capture all events of the specified type. - {{domxref("Window.clearImmediate()")}} {{Non-standard_Inline}} {{Deprecated_Inline}} - : Cancels the repeated execution set using `setImmediate()`. - {{domxref("Window.forward()")}} {{Non-standard_Inline}} {{Deprecated_Inline}} - : Moves the window one document forward in the history. This method is deprecated; you should instead use {{domxref("History.forward", "history.forward()")}}. - {{domxref("Window.releaseEvents()")}} {{Deprecated_Inline}} - : Releases the window from trapping events of a specific type. - {{domxref("Window.requestFileSystem()")}} {{Non-standard_Inline}} {{Deprecated_Inline}} - : Lets a website or app gain access to a sandboxed file system for its own use. - {{domxref("Window.setImmediate()")}} {{Non-standard_Inline}} {{Deprecated_Inline}} - : Executes a function after the browser has finished other heavy tasks. - {{domxref("Window.setResizable()")}} {{Non-standard_Inline}} - : Does nothing (no-op). Kept for backward compatibility with Netscape 4.x. - {{domxref("Window.showModalDialog()")}} {{Non-standard_Inline}} {{Deprecated_Inline}} - : Displays a modal dialog. - {{domxref("Window.webkitConvertPointFromNodeToPage()")}} {{Non-standard_Inline}} {{Deprecated_Inline}} - : Transforms a {{domxref("WebKitPoint")}} from the node's coordinate system to the page's coordinate system. - {{domxref("Window.webkitConvertPointFromPageToNode()")}} {{Non-standard_Inline}} {{Deprecated_Inline}} - : Transforms a {{domxref("WebKitPoint")}} from the page's coordinate system to the node's coordinate system. ## Events Listen to these events using [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener) or by assigning an event listener to the `oneventname` property of this interface. In addition to the events listed below, many events can bubble from the {{domxref("Document")}} contained in the window object. - {{domxref("Window/error_event", "error")}} - : Fired when a resource failed to load, or can't be used. For example, if a script has an execution error or an image can't be found or is invalid. - {{domxref("Window/languagechange_event", "languagechange")}} - : Fired at the global scope object when the user's preferred language changes. - {{domxref("Window/resize_event", "resize")}} - : Fired when the window has been resized. - {{domxref("Window/storage_event", "storage")}} - : Fired when a storage area (`localStorage` or `sessionStorage`) has been modified in the context of another document. ### Clipboard events - {{domxref("Window/copy_event", "copy")}} - : Fired when the user initiates a copy action through the browser's user interface. Also available via the {{domxref("HTMLElement/copy_event", "oncopy")}} property. - {{domxref("Window/cut_event", "cut")}} - : Fired when the user initiates a cut action through the browser's user interface. Also available via the {{domxref("HTMLElement/cut_event", "oncut")}} property. - {{domxref("Window/paste_event", "paste")}} - : Fired when the user initiates a paste action through the browser's user interface. Also available via the {{domxref("HTMLElement/paste_event", "onpaste")}} property. ### Connection events - {{domxref("Window/offline_event", "offline")}} - : Fired when the browser has lost access to the network and the value of `navigator.onLine` has switched to `false`. - {{domxref("Window/online_event", "online")}} - : Fired when the browser has gained access to the network and the value of `navigator.onLine` has switched to `true`. ### Device orientation events - {{domxref("Window.devicemotion_event", "devicemotion")}} - : Fired at a regular interval, indicating the amount of physical force of acceleration the device is receiving and the rate of rotation, if available. - {{domxref("Window.deviceorientation_event", "deviceorientation")}} - : Fired when fresh data is available from the magnetometer orientation sensor about the current orientation of the device as compared to the Earth coordinate frame. - {{domxref("Window.deviceorientationabsolute_event", "deviceorientationabsolute")}} - : Fired when fresh data is available from the magnetometer orientation sensor about the current absolute orientation of the device as compared to the Earth coordinate frame. ### Focus events - {{domxref("Window/blur_event", "blur")}} - : Fired when an element has lost focus. - {{domxref("Window/focus_event", "focus")}} - : Fired when an element has gained focus. ### Gamepad events - {{domxref("Window/gamepadconnected_event", "gamepadconnected")}} - : Fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used. - {{domxref("Window/gamepaddisconnected_event", "gamepaddisconnected")}} - : Fired when the browser detects that a gamepad has been disconnected. ### History events - {{domxref("Window/hashchange_event", "hashchange")}} - : Fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the `#` symbol). - {{domxref("Window/pagehide_event", "pagehide")}} - : Sent when the browser hides the current document while in the process of switching to displaying in its place a different document from the session's history. This happens, for example, when the user clicks the Back button or when they click the Forward button to move ahead in session history. - {{domxref("Window/pageshow_event", "pageshow")}} - : Sent when the browser makes the document visible due to navigation tasks, including not only when the page is first loaded, but also situations such as the user navigating back to the page after having navigated to another within the same tab. - {{domxref("Window/popstate_event", "popstate")}} - : Fired when the active history entry changes. ### Load & unload events - {{domxref("Window/beforeunload_event", "beforeunload")}} - : Fired when the window, the document and its resources are about to be unloaded. - {{domxref("Window/load_event", "load")}} - : Fired when the whole page has loaded, including all dependent resources such as stylesheets images. - {{domxref("Window/unload_event", "unload")}} {{deprecated_inline}} - : Fired when the document or a child resource is being unloaded. ### Manifest events - {{domxref("Window/appinstalled_event", "appinstalled")}} - : Fired when the browser has successfully installed a page as an application. - {{domxref("Window/beforeinstallprompt_event", "beforeinstallprompt")}} - : Fired when a user is about to be prompted to install a web application. ### Messaging events - {{domxref("Window/message_event", "message")}} - : Fired when the window receives a message, for example from a call to {{domxref("Window/postMessage", "Window.postMessage()")}} from another browsing context. - {{domxref("Window/messageerror_event", "messageerror")}} - : Fired when a `Window` object receives a message that can't be deserialized. ### Print events - {{domxref("Window/afterprint_event", "afterprint")}} - : Fired after the associated document has started printing or the print preview has been closed. - {{domxref("Window/beforeprint_event", "beforeprint")}} - : Fired when the associated document is about to be printed or previewed for printing. ### Promise rejection events - {{domxref("Window/rejectionhandled_event", "rejectionhandled")}} - : Sent every time a JavaScript {{jsxref("Promise")}} is rejected, regardless of whether or not there is a handler in place to catch the rejection. - {{domxref("Window/unhandledrejection_event", "unhandledrejection")}} - : Sent when a JavaScript {{jsxref("Promise")}} is rejected but there is no handler in place to catch the rejection. ### Deprecated events - {{domxref("Window/orientationchange_event", "orientationchange")}} {{Deprecated_Inline}} - : Fired when the orientation of the device has changed. - {{domxref("Window/vrdisplayactivate_event", "vrdisplayactivate")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Fired when a display is able to be presented to. - {{domxref("Window/vrdisplayconnect_event", "vrdisplayconnect")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Fired when a compatible VR device has been connected to the computer. - {{domxref("Window/vrdisplaydisconnect_event", "vrdisplaydisconnect")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Fired when a compatible VR device has been disconnected from the computer. - {{domxref("Window/vrdisplaydeactivate_event", "vrdisplaydeactivate")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Fired when a display can no longer be presented to. - {{domxref("Window/vrdisplaypresentchange_event", "vrdisplaypresentchange")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Fired when the presenting state of a VR device changes β€” i.e. goes from presenting to not presenting, or vice versa. ## Interfaces See [DOM Reference](/en-US/docs/Web/API/Document_Object_Model). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/getcomputedstyle/index.md
--- title: "Window: getComputedStyle() method" short-title: getComputedStyle() slug: Web/API/Window/getComputedStyle page-type: web-api-instance-method browser-compat: api.Window.getComputedStyle --- {{APIRef("CSSOM")}} The **`Window.getComputedStyle()`** method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain. Individual CSS property values are accessed through APIs provided by the object, or by indexing with CSS property names. ## Syntax ```js-nolint getComputedStyle(element) getComputedStyle(element, pseudoElt) ``` ### Parameters - `element` - : The {{DOMxRef("Element")}} for which to get the computed style. - `pseudoElt` {{optional_inline}} - : A string specifying the pseudo-element to match. Omitted (or `null`) for real elements. ### Return value A _live_ {{DOMxRef("CSSStyleDeclaration")}} object, which updates automatically when the element's styles are changed. ### Exceptions - {{JSxRef("TypeError")}} - : If the passed object is not an {{DOMxRef("Element")}} or the `pseudoElt` is not a valid pseudo-element selector or is {{CSSxRef("::part", "::part()")}} or {{CSSxRef("::slotted", "::slotted()")}}. > **Note:** Valid pseudo-element selector refers to syntactic > validity, e.g. `::unsupported` is considered valid, even though the > pseudo-element itself is not supported. Additionally, the latest W3 standard [explicitly supports](https://www.w3.org/TR/cssom-1/#dom-window-getcomputedstyle) only `::before` and `::after`, while the CSS > WG draft [does not restrict this value](https://drafts.csswg.org/cssom/#dom-window-getcomputedstyle). Browser compatibility may vary. ## Examples In this example we style a {{HTMLElement("p")}} element, then retrieve those styles using `getComputedStyle()`, and print them into the text content of the `<p>`. ### HTML ```html <p>Hello</p> ``` ### CSS ```css p { width: 400px; margin: 0 auto; padding: 20px; font: 2rem/2 sans-serif; text-align: center; background: purple; color: white; } ``` ### JavaScript ```js const para = document.querySelector("p"); const compStyles = window.getComputedStyle(para); para.textContent = `My computed font-size is ${compStyles.getPropertyValue("font-size")},\n` + `and my computed line-height is ${compStyles.getPropertyValue( "line-height", )}.`; ``` ### Result {{EmbedLiveSample('Examples', '100%', '240px')}} ## Description The returned object is the same {{DOMxRef("CSSStyleDeclaration")}} type as the object returned from the element's {{DOMxRef("HTMLElement/style", "style")}} property. However, the two objects have different purposes: - The object from `getComputedStyle` is read-only, and should be used to inspect the element's style β€” including those set by a `<style>` element or an external stylesheet. - The `element.style` object should be used to **set** styles on that element, or inspect styles directly added to it from JavaScript manipulation or the global `style` attribute. The first argument must be an {{domxref("Element")}}. Non-elements, like a {{DOMxRef("Text")}} node, will throw an error. ## defaultView In many code samples, `getComputedStyle` is used from the {{DOMxRef("document.defaultView")}} object. In nearly all cases, this is needless, as `getComputedStyle` exists on the `window` object as well. It's likely the `defaultView` pattern was a combination of folks not wanting to write a testing spec for `window` and making an API that was also usable in Java. ## Use with pseudo-elements `getComputedStyle` can pull style info from pseudo-elements (such as `::after`, `::before`, `::marker`, `::line-marker` β€” see [the pseudo-element spec](https://www.w3.org/TR/css-pseudo-4/)). ```html <style> h3::after { content: " rocks!"; } </style> <h3>Generated content</h3> <script> const h3 = document.querySelector("h3"); const result = getComputedStyle(h3, ":after").content; console.log("the generated content is: ", result); // returns ' rocks!' </script> ``` ## Notes - The returned {{DOMxRef("CSSStyleDeclaration")}} object contains active values for CSS property **_longhand_** names as well as shorthand names. For example, the returned object contains entries for {{cssxref("border-bottom-width")}} in addition to the {{cssxref("border-width")}} and {{cssxref("border")}} [shorthand property names](/en-US/docs/Web/CSS/Shorthand_properties). You can query values with longhand names like {{cssxref("font-size")}} as well as shorthand names like {{cssxref("font")}}. - CSS property values may be accessed using the {{DOMxRef("CSSStyleDeclaration.getPropertyValue", "getPropertyValue(propName)")}} method or by indexing directly into the object using array or [dot notation](/en-US/docs/Learn/JavaScript/Objects/Basics#dot_notation) such as `obj['z-index']` or `obj.zIndex`. - The values returned by `getComputedStyle` are {{CSSxRef("resolved_value", "resolved values", "", 1)}}. These are usually the same as CSS 2.1's {{CSSxRef("computed_value","computed values", "", 1)}}, but for some older properties like `width`, `height`, or `padding`, they are instead the same as {{CSSxRef("used_value","used values", "", 1)}}. Originally, CSS 2.0 defined the _computed values_ as the "ready to be used" final values of properties after cascading and inheritance, but CSS 2.1 redefined them as pre-layout, and _used values_ as post-layout. For CSS 2.0 properties, `getComputedStyle` returns the old meaning of computed values, now called **used values**. An example difference between pre- and post-layout values includes the resolution of percentages for `width` or `height`, as those will be replaced by their pixel equivalent only for _used values_. - Returned values are sometimes deliberately inaccurate. To avoid the "CSS History Leak" security issue, browsers may lie about the computed styles for a visited link, returning values as if the user never visited the linked URL. See [Plugging the CSS history leak](https://blog.mozilla.org/security/2010/03/31/plugging-the-css-history-leak/) and [Privacy-related changes coming to CSS `:visited`](https://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/) for examples of how this is implemented. - During [CSS transitions](/en-US/docs/Web/CSS/CSS_transitions), `getComputedStyle` returns the original property value in Firefox, but the final property value in WebKit. - In Firefox, properties with the value `auto` return the used value, not the value `auto`. So if you apply `top:auto` and `bottom:0` on an element with `height:30px` and a containing block of `height:100px`, Firefox's computed style for `top` returns `70px`, as 100 βˆ’ 30 = 70. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("window.getDefaultComputedStyle()")}} - {{DOMxRef("CSSStyleDeclaration.getPropertyValue", "getPropertyValue()")}} - {{CSSxRef("resolved_value", "Resolved Value")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/name/index.md
--- title: "Window: name property" short-title: name slug: Web/API/Window/name page-type: web-api-instance-property browser-compat: api.Window.name --- {{APIRef}} The `Window.name` property gets/sets the name of the window's browsing context. ## Value A string. ## Description The name of the window is used primarily for setting targets for hyperlinks and forms. Browsing contexts do not need to have names. Modern browsers will reset `Window.name` to an empty string if a tab loads a page from a different domain, and restore the name if the original page is reloaded (e.g. by selecting the "back" button). This prevents an untrusted page from accessing any information that the previous page might have stored in the property (potentially the new page might also modify such data, which might then be read by the original page if it was reloaded). `Window.name` has also been used in some frameworks for providing cross-domain messaging as a more secure alternative to JSONP. Modern web applications hosting sensitive data should, however, not rely on `window.name` for cross-domain messaging β€” that is not its intended purpose and there are safer/better ways of sharing information between windows. [`Window.postMessage()`](/en-US/docs/Web/API/Window/postMessage) is the recommended mechanism. > **Note:** `window.name` converts all stored values to their > string representations using the `toString` method. ## Examples ```html <script> // Open a tab with a specific browsing context name const otherTab = window.open("url1", "_blank"); if (otherTab) otherTab.name = "other-tab"; </script> <a href="url2" target="other-tab">This link will be opened in the other tab.</a> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/screeny/index.md
--- title: "Window: screenY property" short-title: screenY slug: Web/API/Window/screenY page-type: web-api-instance-property browser-compat: api.Window.screenY --- {{APIRef}} The **`Window.screenY`** read-only property returns the vertical distance, in CSS pixels, of the top border of the user's browser viewport to the top edge of the screen. > **Note:** An alias of `screenY` was implemented across modern browsers in more recent times β€” {{domxref("Window.screenTop")}}. This was originally supported only in IE but was introduced everywhere due to popularity. ## Value A number equal to the number of CSS pixels from the top edge of the browser viewport to the top edge of the screen. ## Examples In our [screenleft-screentop](https://mdn.github.io/dom-examples/screenleft-screentop/) example, you'll see a canvas onto which has been drawn a circle. In this example we are using {{domxref("Window.screenLeft")}}/{{domxref("Window.screenTop")}} plus {{domxref("Window.requestAnimationFrame()")}} to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ```js initialLeft = window.screenLeft + canvasElem.offsetLeft; initialTop = window.screenTop + canvasElem.offsetTop; function positionElem() { let newLeft = window.screenLeft + canvasElem.offsetLeft; let newTop = window.screenTop + canvasElem.offsetTop; let leftUpdate = initialLeft - newLeft; let topUpdate = initialTop - newTop; ctx.fillStyle = "rgb(0 0 0)"; ctx.fillRect(0, 0, width, height); ctx.fillStyle = "rgb(0 0 255)"; ctx.beginPath(); ctx.arc( leftUpdate + width / 2, topUpdate + height / 2 + 35, 50, degToRad(0), degToRad(360), false, ); ctx.fill(); pElem.textContent = `Window.screenLeft: ${window.screenLeft}, Window.screenTop: ${window.screenTop}`; window.requestAnimationFrame(positionElem); } window.requestAnimationFrame(positionElem); ``` These work in exactly the same way as `screenX`/`screenY`. Also in the code we include a snippet that detects whether `screenLeft` is supported, and if not, polyfills in `screenLeft`/`screenTop` using `screenX`/`screenY`. ```js if (!window.screenLeft) { window.screenLeft = window.screenX; window.screenTop = window.screenY; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.screenTop")}} - {{domxref("window.screenX")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/closed/index.md
--- title: "Window: closed property" short-title: closed slug: Web/API/Window/closed page-type: web-api-instance-property browser-compat: api.Window.closed --- {{APIRef}} The **`Window.closed`** read-only property indicates whether the referenced window is closed or not. ## Value A boolean value. Possible values: - `true`: The window has been closed. - `false`: The window is open. ## Examples ### Change the URL of a window from a popup The following example demonstrates how a popup window can change the URL of the window that opened it. Before attempting to change the URL, it checks that the current window has an opener using the {{domxref("window.opener")}} property and that the opener isn't closed: ```js // Check that an opener exists and is not closed if (window.opener && !window.opener.closed) { window.opener.location.href = "http://www.mozilla.org"; } ``` Note that popups can only access the window that opened them. ### Refreshing a previously opened popup In this example the function `refreshPopupWindow()` calls the `reload()` method of the popup's location object to refresh its data. If the popup hasn't been opened yet or the user has closed it a new window is opened. ```js let popupWindow = null; function refreshPopupWindow() { if (popupWindow && !popupWindow.closed) { // popupWindow is open, refresh it popupWindow.location.reload(true); } else { // Open a new popup window popupWindow = window.open("popup.html", "dataWindow"); } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/focus/index.md
--- title: "Window: focus() method" short-title: focus() slug: Web/API/Window/focus page-type: web-api-instance-method browser-compat: api.Window.focus --- {{APIRef}} Makes a request to bring the window to the front. It may fail due to user settings and the window isn't guaranteed to be frontmost before this method returns. ## Syntax ```js-nolint focus() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js if (clicked) { window.focus(); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/statusbar/index.md
--- title: "Window: statusbar property" short-title: statusbar slug: Web/API/Window/statusbar page-type: web-api-instance-property browser-compat: api.Window.statusbar --- {{APIRef}} Returns the `statusbar` object. This is one of a group of `Window` properties that contain a boolean `visible` property, that used to represent whether or not a particular part of a web browser's user interface was visible. For privacy and interoperability reasons, the value of the `visible` property is now `false` if this `Window` is a popup, and `true` otherwise. ## Value An object containing a single property: - `visible` {{ReadOnlyInline}} - : A boolean property, `false` if this `Window` is a popup, and `true` otherwise. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.locationbar")}} - {{domxref("window.menubar")}} - {{domxref("window.personalbar")}} - {{domxref("window.scrollbars")}} - {{domxref("window.toolbar")}}
0