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/navigator
data/mdn-content/files/en-us/web/api/navigator/getgamepads/index.md
--- title: "Navigator: getGamepads() method" short-title: getGamepads() slug: Web/API/Navigator/getGamepads page-type: web-api-instance-method browser-compat: api.Navigator.getGamepads --- {{APIRef("Gamepad API")}}{{securecontext_header}} The **`Navigator.getGamepads()`** method returns an array of {{domxref("Gamepad")}} objects, one for each gamepad connected to the device. Elements in the array may be `null` if a gamepad disconnects during a session, so that the remaining gamepads retain the same index. ## Syntax ```js-nolint getGamepads() ``` ### Parameters None. ### Return value An {{jsxref("Array")}} of {{domxref("Gamepad")}} objects, eventually empty. ### Exceptions - `SecurityError` {{domxref("DOMException")}} - : Use of this feature was blocked by a [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy). ## Examples ```js window.addEventListener("gamepadconnected", (e) => { const gp = navigator.getGamepads()[e.gamepad.index]; console.log( `Gamepad connected at index ${gp.index}: ${gp.id} with ${gp.buttons.length} buttons, ${gp.axes.length} axes.`, ); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Gamepad API](/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API) - [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/getbattery/index.md
--- title: "Navigator: getBattery() method" short-title: getBattery() slug: Web/API/Navigator/getBattery page-type: web-api-instance-method browser-compat: api.Navigator.getBattery --- {{ApiRef("Battery API")}}{{securecontext_header}} The **`getBattery()`** method provides information about the system's battery. It returns a battery promise, which resolves with a {{domxref("BatteryManager")}} object providing some properties to get the battery status also some events you can handle to monitor the battery status. This implements the {{domxref("Battery Status API", "", "", "nocode")}}; see that documentation for additional details, a guide to using the API, and sample code. Since Chrome 103, the `Navigator.getBattery()` method of {{domxref("Battery Status API", "", "", "nocode")}} only expose to secure context. > **Note:** Access to this feature may be controlled by the {{HTTPHeader("Permissions-Policy")}} directive {{HTTPHeader("Permissions-Policy/battery", "battery")}}. ## Syntax ```js-nolint getBattery() ``` ### Parameters None. ### Return value A {{JSxRef("Promise")}} that fulfills with a {{DOMxRef("BatteryManager")}} object which you can use to get information about the battery's state. ### Exceptions - `NotAllowedError` {{domxref("DOMException")}} - : Use of this feature was blocked by a [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy). - `SecurityError` {{domxref("DOMException")}} - : The User Agent does not expose battery information to insecure contexts and this method was called from an insecure context. ## Examples This example fetches the current charging state of the battery and establishes a handler for the {{domxref("BatteryManager/chargingchange_event", "chargingchange")}} event, so that the charging state is recorded whenever it changes. ```js let batteryIsCharging = false; navigator.getBattery().then((battery) => { batteryIsCharging = battery.charging; battery.addEventListener("chargingchange", () => { batteryIsCharging = battery.charging; }); }); ``` For more examples and details, see {{domxref("Battery Status API", "", "", "nocode")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Battery Status API", "", "", "nocode")}} - {{HTTPHeader("Permissions-Policy")}} {{HTTPHeader("Permissions-Policy/battery", "battery")}} directive
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/productsub/index.md
--- title: "Navigator: productSub property" short-title: productSub slug: Web/API/Navigator/productSub page-type: web-api-instance-property status: - deprecated browser-compat: api.Navigator.productSub --- {{ ApiRef("HTML DOM") }} {{Deprecated_Header}} The **`Navigator.productSub`** read-only property returns the build number of the current browser. ## Value A string. ## Examples ```js document.body.textContent = `productSub: ${navigator.productSub}`; ``` {{ EmbedLiveSample("Examples") }} ## Notes On IE, this property returns undefined. On Apple Safari and Google Chrome this property always returns `20030107`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/plugins/index.md
--- title: "Navigator: plugins property" short-title: plugins slug: Web/API/Navigator/plugins page-type: web-api-instance-property status: - deprecated browser-compat: api.Navigator.plugins --- {{APIRef("HTML DOM")}}{{deprecated_header}} Returns a {{DOMxRef("PluginArray")}} object, listing the {{DOMxRef("Plugin")}} objects describing the plugins installed in the application. Named properties of the returned object are not enumerable (except in very old browser versions). Recent versions of the specification hard-code the returned list. If inline viewing of PDF files is supported the property lists five standard plugins. If inline PDF viewing is not supported then an empty list is returned. > **Note:** Use {{domxref("Navigator.pdfViewerEnabled")}} to determine if inline viewing of PDF files is supported. Do not infer it from this property. > > The "five standard plugins" are those that developers have most commonly used to feature detect inline PDF viewing. > Returning these ensures that legacy code can more reliably determine whether inline viewing is supported. > However this approach is not recommended for new code because this property may eventually be removed. Legacy browser versions also list plugins for Adobe Flash and PDF viewer extensions. ## Value `plugins` is a {{DOMxRef("PluginArray")}} object used to access {{DOMxRef("Plugin")}} objects either by name or as a list of items. The returned value is not a JavaScript array, but has the `length` property and supports accessing individual items using bracket notation (`plugins[2]`), as well as via `item(index)` and `namedItem("name")` methods. If PDF inline viewing is supported this will contain entries for the following plugins: - "PDF Viewer" - "Chrome PDF Viewer" - "Chromium PDF Viewer" - "Microsoft Edge PDF Viewer" - "WebKit built-in PDF" If inline viewing of PDFs is not supported then an empty object is returned. ## Examples This code shows how to check if PDF files can be displayed inline: ```js if ("PDF Viewer" in navigator.plugins) { // browser supports inline viewing of PDF files. } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/devicememory/index.md
--- title: "Navigator: deviceMemory property" short-title: deviceMemory slug: Web/API/Navigator/deviceMemory page-type: web-api-instance-property browser-compat: api.Navigator.deviceMemory --- {{APIRef("Device Memory API")}}{{securecontext_header}} The **`deviceMemory`** read-only property of the {{domxref("Navigator")}} interface returns the approximate amount of device memory in gigabytes. The reported value is imprecise to curtail {{glossary("fingerprinting")}}. It's approximated by rounding down to the nearest power of 2, then dividing that number by 1024. It is then clamped within lower and upper bounds to protect the privacy of owners of very low-memory or high-memory devices. ## Value A floating point number; one of `0.25`, `0.5`, `1`, `2`, `4`, `8`. ## Examples ```js const memory = navigator.deviceMemory; console.log(`This device has at least ${memory}GiB of RAM.`); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTTPHeader("Device-Memory")}} HTTP header
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/sendbeacon/index.md
--- title: "Navigator: sendBeacon() method" short-title: sendBeacon() slug: Web/API/Navigator/sendBeacon page-type: web-api-instance-method browser-compat: api.Navigator.sendBeacon --- {{APIRef("HTML DOM")}} The **`navigator.sendBeacon()`** method {{glossary("Asynchronous", "asynchronously")}} sends an [HTTP POST](/en-US/docs/Web/HTTP/Methods/POST) request containing a small amount of data to a web server. It's intended to be used for sending analytics data to a web server, and avoids some of the problems with legacy techniques for sending analytics, such as the use of {{domxref("XMLHttpRequest","XMLHttpRequest")}}. > **Note:** For use cases that need the ability to send requests with methods other than `POST`, or to change any request properties, or that need access to the server response, instead use the [`fetch()`](/en-US/docs/Web/API/fetch) method with [`keepalive`](/en-US/docs/Web/API/fetch#keepalive) set to true. ## Syntax ```js-nolint sendBeacon(url) sendBeacon(url, data) ``` ### Parameters - `url` - : The URL that will receive the _data_. Can be relative or absolute. - `data` {{Optional_inline}} - : An {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, a {{jsxref("DataView")}}, a {{domxref("Blob")}}, a string literal or object, a {{domxref("FormData")}} or a {{domxref("URLSearchParams")}} object containing the data to send. ### Return values The **`sendBeacon()`** method returns `true` if the {{glossary("user agent")}} successfully queued the `data` for transfer. Otherwise, it returns `false`. ## Description This method is intended for analytics and diagnostics code to send data to a server. A problem with sending analytics is that a site often wants to send analytics when the user has finished with a page: for example, when the user navigates to another page. In this situation the browser may be about to unload the page, and in that case the browser may choose not to send asynchronous {{domxref("XMLHttpRequest")}} requests. In the past, web pages have tried to delay page unload long enough to send data. To do this they have used workarounds such as: - Submitting the data with a blocking synchronous `XMLHttpRequest` call. - Creating an {{HTMLElement("img")}} element and setting its `src`. Most user agents will delay the unload to load the image. - Creating a no-op loop for several seconds. All these methods block unloading the document, which slows down navigation to the next page. There's nothing the next page can do to avoid this, so the new page seems slow, even though it's the fault of the previous page. With the `sendBeacon()` method, the data is transmitted asynchronously when the user agent has an opportunity to do so, without delaying unload or the next navigation. This means: - The data is sent reliably - It's sent asynchronously - It doesn't impact the loading of the next page The data is sent as an [HTTP POST](/en-US/docs/Web/HTTP/Methods/POST) request. ### Sending analytics at the end of a session Websites often want to send analytics or diagnostics to the server when the user has finished with the page. The most reliable way to do this is to send the data on the [`visibilitychange`](/en-US/docs/Web/API/Document/visibilitychange_event) event: ```js document.addEventListener("visibilitychange", function logData() { if (document.visibilityState === "hidden") { navigator.sendBeacon("/log", analyticsData); } }); ``` #### Avoid unload and beforeunload In the past, many websites have used the [`unload`](/en-US/docs/Web/API/Window/unload_event) or [`beforeunload`](/en-US/docs/Web/API/Window/beforeunload_event) events to send analytics at the end of a session. However, this is extremely unreliable. In many situations, especially on mobile, the browser will not fire the `unload`, `beforeunload`, or `pagehide` events. For example, these events will not fire in the following situation: 1. The user loads the page and interacts with it. 2. When they are finished, they switch to a different app, instead of closing the tab. 3. Later, they close the browser app using the phone's app manager. Additionally, the `unload` event is incompatible with the back/forward cache ([bfcache](https://web.dev/articles/bfcache)) implemented in modern browsers. Some browsers, such as Firefox, handle this incompatibility by excluding pages from the bfcache if they contain unload handlers, thus hurting performance. Others, such as Safari and Chrome on Android, handle it by not firing the `unload` event when the user navigates to another page in the same tab. Firefox will also exclude pages from the bfcache if they contain `beforeunload` handlers. #### Use pagehide as a fallback To support browsers which don't implement `visibilitychange`, use the [`pagehide`](/en-US/docs/Web/API/Window/pagehide_event) event. Like `beforeunload` and `unload`, this event is not reliably fired, especially on mobile. However, it is compatible with the bfcache. ## Examples The following example specifies a handler for the {{domxref("document.visibilitychange_event", "visibilitychange")}} event. The handler calls `sendBeacon()` to send analytics. ```js document.addEventListener("visibilitychange", function logData() { if (document.visibilityState === "hidden") { navigator.sendBeacon("/log", analyticsData); } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [`visibilitychange`](/en-US/docs/Web/API/Document/visibilitychange_event) event. - {{domxref("Beacon_API","Beacon API", "", "true")}} overview page. - [Don't lose user and app state, use Page Visibility](https://www.igvita.com/2015/11/20/dont-lose-user-and-app-state-use-page-visibility/) explains in detail why you should use `visibilitychange`, not `beforeunload`/`unload`. - [Page Lifecycle API](https://developer.chrome.com/blog/page-lifecycle-api/#developer-recommendations-for-each-state) gives best-practices guidance on handling page lifecycle behavior in your web applications. - [PageLifecycle.js](https://github.com/GoogleChromeLabs/page-lifecycle): a JavaScript library that deals with cross-browser inconsistencies in page lifecycle behavior. - [Back/forward cache](https://web.dev/articles/bfcache) explains what the back/forward cache is, and its implications for various page lifecycle events.
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/clearappbadge/index.md
--- title: "Navigator: clearAppBadge() method" short-title: clearAppBadge() slug: Web/API/Navigator/clearAppBadge page-type: web-api-instance-method browser-compat: api.Navigator.clearAppBadge --- {{APIRef("Badging API")}}{{securecontext_header}} The **`clearAppBadge()`** method of the {{domxref("Navigator")}} interface clears a badge on the current app's icon by setting it to `nothing`. The value `nothing` indicates that no badge is currently set, and the status of the badge is _cleared_. ## Syntax ```js-nolint clearAppBadge() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that resolves with {{jsxref("undefined")}}. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the document is not fully active. - `SecurityError` {{domxref("DOMException")}} - : Thrown if the call was blocked by the [same-origin policy](/en-US/docs/Web/Security/Same-origin_policy). - `NotAllowedError` {{domxref("DOMException")}} - : Thrown if {{domxref('PermissionStatus.state')}} is not `granted`. ## Examples Once all messages in an application have been read, call `clearAppBadge()` to clear the badge and remove the notification. ```js navigator.clearAppBadge(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Badging for app icons](https://developer.chrome.com/docs/capabilities/web-apis/badging-api/)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/usb/index.md
--- title: "Navigator: usb property" short-title: usb slug: Web/API/Navigator/usb page-type: web-api-instance-property browser-compat: api.Navigator.usb --- {{APIRef("WebUSB API")}}{{SecureContext_Header}} The **`usb`** read-only property of the {{domxref("Navigator")}} interface returns a {{domxref("USB")}} object for the current document, providing access to [WebUSB API](/en-US/docs/Web/API/WebUSB_API) functionality. ## Value A {{domxref('USB')}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebUSB API](/en-US/docs/Web/API/WebUSB_API)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/online/index.md
--- title: "Navigator: onLine property" short-title: onLine slug: Web/API/Navigator/onLine page-type: web-api-instance-property browser-compat: api.Navigator.onLine --- {{ApiRef("HTML DOM")}} Returns the online status of the browser. The property returns a boolean value, with `true` meaning online and `false` meaning offline. The property sends updates whenever the browser's ability to connect to the network changes. The update occurs when the user follows links or when a script requests a remote page. For example, the property should return `false` when users click links soon after they lose internet connection. Browsers implement this property differently. In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return `true`. So while you can assume that the browser is offline when it returns a `false` value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking. In Firefox, switching the browser to offline mode sends a `false` value. Until Firefox 41, all other conditions returned a `true` value; testing actual behavior on Nightly 68 on Windows shows that it only looks for LAN connection like Chrome and Safari giving false positives. You can see changes in the network state by listening to the [`online`](/en-US/docs/Web/API/Window/online_event) and [`offline`](/en-US/docs/Web/API/Window/offline_event) events. ## Value A boolean. ## Examples ### Basic usage To check if you are online, query `window.navigator.onLine`, as in the following example: ```js if (navigator.onLine) { console.log("online"); } else { console.log("offline"); } ``` If the browser doesn't support `navigator.onLine` the above example will always come out as `false`/`undefined`. ### Listening for changes in network status To see changes in the network state, use [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) to listen for the events on `window.online` and `window.offline`, as in the following example: ```js window.addEventListener("offline", (e) => { console.log("offline"); }); window.addEventListener("online", (e) => { console.log("online"); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/mediasession/index.md
--- title: "Navigator: mediaSession property" short-title: mediaSession slug: Web/API/Navigator/mediaSession page-type: web-api-instance-property browser-compat: api.Navigator.mediaSession --- {{APIRef("Media Session API")}} The **`mediaSession`** read-only property of the {{domxref("Navigator")}} interface returns a {{domxref("MediaSession")}} object that can be used to share with the browser metadata and other information about the current playback state of media being handled by a document. This information may, in turn, be shared with the device and/or operating system in order to a device's standard media control user experience to describe and control the playback of the media. In addition, the `MediaSession` interface provides the {{domxref("MediaSession.setActionHandler", "setActionHandler()")}} method, which lets you receive events when the user engages device controls such as either onscreen or physical play, pause, seek, and other similar controls. An internet radio app, for example, can use `setActionHandler()` to let the media controls on a keyboard or elsewhere on the user's device be used to control the app's media playback. ## Value A {{domxref("MediaSession")}} object the current document can use to share information about media it's playing and its current playback status. This information can include typical metadata such as the title, artist, and album name of the song being played as well as potentially one or more images containing things like album art, artist photos, and so forth. ## Examples In this example, metadata is submitted to the `mediaSession` object. Note that the code begins by ensuring that the {{domxref("navigator.mediaSession")}} property is available before attempting to use it. ```js if ("mediaSession" in navigator) { navigator.mediaSession.metadata = new MediaMetadata({ title: "Podcast Episode Title", artist: "Podcast Host", album: "Podcast Name", artwork: [{ src: "podcast.jpg" }], }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/geolocation/index.md
--- title: "Navigator: geolocation property" short-title: geolocation slug: Web/API/Navigator/geolocation page-type: web-api-instance-property browser-compat: api.Navigator.geolocation --- {{securecontext_header}}{{APIRef("Geolocation API")}} The **`Navigator.geolocation`** read-only property returns a {{domxref("Geolocation")}} object that gives Web content access to the location of the device. This allows a website or app to offer customized results based on the user's location. > **Note:** For security reasons, when a web page tries to access location > information, the user is notified and asked to grant permission. Be aware that each > browser has its own policies and methods for requesting this permission. ## Value A {{domxref("Geolocation")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Geolocation API](/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/useractivation/index.md
--- title: "Navigator: userActivation property" short-title: userActivation slug: Web/API/Navigator/userActivation page-type: web-api-instance-property browser-compat: api.Navigator.userActivation --- {{APIRef("HTML DOM")}} The read-only **`userActivation`** property of the {{domxref("Navigator")}} interface returns a {{domxref("UserActivation")}} object which contains information about the current window's user activation state. ## Value A {{domxref("UserActivation")}} object. ## Examples ### Checking if a user gesture was recently performed Use {{domxref("UserActivation.isActive")}} to check whether the user is currently interacting with the page ({{Glossary("Transient activation")}}). ```js if (navigator.userActivation.isActive) { // proceed to request playing media, for example } ``` ### Checking if a user gesture was ever performed Use {{domxref("UserActivation.hasBeenActive")}} to check whether the user has ever interacted with the page ({{Glossary("Sticky activation")}}). ```js if (navigator.userActivation.hasBeenActive) { // proceed with auto-playing an animation, for example } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("UserActivation")}} - {{domxref("UserActivation.hasBeenActive")}} - {{domxref("UserActivation.isActive")}} - [Features gated by user activation](/en-US/docs/Web/Security/User_activation)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/performanceservertiming/index.md
--- title: PerformanceServerTiming slug: Web/API/PerformanceServerTiming page-type: web-api-interface browser-compat: api.PerformanceServerTiming --- {{APIRef("Performance API")}} {{AvailableInWorkers}} {{securecontext_header}} The **`PerformanceServerTiming`** interface surfaces server metrics that are sent with the response in the {{HTTPHeader("Server-Timing")}} HTTP header. This interface is restricted to the same origin, but you can use the {{HTTPHeader("Timing-Allow-Origin")}} header to specify the domains that are allowed to access the server metrics. Note that this interface is only available in secure contexts (HTTPS) in some browsers. ## Instance properties - {{domxref('PerformanceServerTiming.description')}} {{ReadOnlyInline}} - : A string value of the server-specified metric description, or an empty string. - {{domxref('PerformanceServerTiming.duration')}} {{ReadOnlyInline}} - : A double that contains the server-specified metric duration, or value `0.0`. - {{domxref('PerformanceServerTiming.name')}} {{ReadOnlyInline}} - : A string value of the server-specified metric name. ## Instance methods - {{domxref('PerformanceServerTiming.toJSON()')}} - : Returns a JSON representation of the `PerformanceServerTiming` object. ## Example Given a server that sends the {{HTTPHeader("Server-Timing")}} header, for example a Node.js server like this: ```js const http = require("http"); function requestHandler(request, response) { const headers = { "Server-Timing": ` cache;desc="Cache Read";dur=23.2, db;dur=53, app;dur=47.2 `.replace(/\n/g, ""), }; response.writeHead(200, headers); response.write(""); return setTimeout(() => { response.end(); }, 1000); } http.createServer(requestHandler).listen(3000).on("error", console.error); ``` The `PerformanceServerTiming` entries are now observable from JavaScript via the {{domxref("PerformanceResourceTiming.serverTiming")}} property and live on `navigation` and `resource` entries. Example using a {{domxref("PerformanceObserver")}}, which notifies of new `navigation` and `resource` performance entries as they are recorded in the browser's performance timeline. Use the `buffered` option to access entries from before the observer creation. ```js const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { entry.serverTiming.forEach((serverEntry) => { console.log( `${serverEntry.name} (${serverEntry.description}) duration: ${serverEntry.duration}`, ); // Logs "cache (Cache Read) duration: 23.2" // Logs "db () duration: 53" // Logs "app () duration: 47.2" }); }); }); ["navigation", "resource"].forEach((type) => observer.observe({ type, buffered: true }), ); ``` Example using {{domxref("Performance.getEntriesByType()")}}, which only shows `navigation` and `resource` performance entries present in the browser's performance timeline at the time you call this method: ```js for (const entryType of ["navigation", "resource"]) { for (const { name: url, serverTiming } of performance.getEntriesByType( entryType, )) { if (serverTiming) { for (const { name, description, duration } of serverTiming) { console.log(`${name} (${description}) duration: ${duration}`); // Logs "cache (Cache Read) duration: 23.2" // Logs "db () duration: 53" // Logs "app () duration: 47.2" } } } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTTPHeader("Server-Timing")}} - {{domxref("PerformanceResourceTiming.serverTiming")}}
0
data/mdn-content/files/en-us/web/api/performanceservertiming
data/mdn-content/files/en-us/web/api/performanceservertiming/name/index.md
--- title: "PerformanceServerTiming: name property" short-title: name slug: Web/API/PerformanceServerTiming/name page-type: web-api-instance-property browser-compat: api.PerformanceServerTiming.name --- {{APIRef("Performance API")}} The **`name`** read-only property returns a string value of the server-specified metric name. ## Value A string. ## Examples ### Logging server timing entries Server timing metrics require the server to send the {{HTTPHeader("Server-Timing")}} header. For example: ```http Server-Timing: cache;desc="Cache Read";dur=23.2 ``` The `serverTiming` entries can live on `navigation` and `resource` entries. Example using a {{domxref("PerformanceObserver")}}, which notifies of new `navigation` and `resource` performance entries as they are recorded in the browser's performance timeline. Use the `buffered` option to access entries from before the observer creation. ```js const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { entry.serverTiming.forEach((serverEntry) => { console.log( `${serverEntry.name} (${serverEntry.description}) duration: ${serverEntry.duration}`, ); // Logs "cache (Cache Read) duration: 23.2" }); }); }); ["navigation", "resource"].forEach((type) => observer.observe({ type, buffered: true }), ); ``` Example using {{domxref("Performance.getEntriesByType()")}}, which only shows `navigation` and `resource` performance entries present in the browser's performance timeline at the time you call this method: ```js for (const entryType of ["navigation", "resource"]) { for (const { name: url, serverTiming } of performance.getEntriesByType( entryType, )) { if (serverTiming) { for (const { name, description, duration } of serverTiming) { console.log(`${name} (${description}) duration: ${duration}`); // Logs "cache (Cache Read) duration: 23.2" } } } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("PerformanceServerTiming")}} - {{HTTPHeader("Server-Timing")}}
0
data/mdn-content/files/en-us/web/api/performanceservertiming
data/mdn-content/files/en-us/web/api/performanceservertiming/description/index.md
--- title: "PerformanceServerTiming: description property" short-title: description slug: Web/API/PerformanceServerTiming/description page-type: web-api-instance-property browser-compat: api.PerformanceServerTiming.description --- {{APIRef("Performance API")}} The **`description`** read-only property returns a string value of the server-specified metric description, or an empty string. ## Value A string. ## Examples ### Logging server timing entries Server timing metrics require the server to send the {{HTTPHeader("Server-Timing")}} header. For example: ```http Server-Timing: cache;desc="Cache Read";dur=23.2 ``` The `serverTiming` entries can live on `navigation` and `resource` entries. Example using a {{domxref("PerformanceObserver")}}, which notifies of new `navigation` and `resource` performance entries as they are recorded in the browser's performance timeline. Use the `buffered` option to access entries from before the observer creation. ```js const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { entry.serverTiming.forEach((serverEntry) => { console.log( `${serverEntry.name} (${serverEntry.description}) duration: ${serverEntry.duration}`, ); // Logs "cache (Cache Read) duration: 23.2" }); }); }); ["navigation", "resource"].forEach((type) => observer.observe({ type, buffered: true }), ); ``` Example using {{domxref("Performance.getEntriesByType()")}}, which only shows `navigation` and `resource` performance entries present in the browser's performance timeline at the time you call this method: ```js for (const entryType of ["navigation", "resource"]) { for (const { name: url, serverTiming } of performance.getEntriesByType( entryType, )) { if (serverTiming) { for (const { name, description, duration } of serverTiming) { console.log(`${name} (${description}) duration: ${duration}`); // Logs "cache (Cache Read) duration: 23.2" } } } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("PerformanceServerTiming")}} - {{HTTPHeader("Server-Timing")}}
0
data/mdn-content/files/en-us/web/api/performanceservertiming
data/mdn-content/files/en-us/web/api/performanceservertiming/duration/index.md
--- title: "PerformanceServerTiming: duration property" short-title: duration slug: Web/API/PerformanceServerTiming/duration page-type: web-api-instance-property browser-compat: api.PerformanceServerTiming.duration --- {{APIRef("Performance API")}} The **`duration`** read-only property returns a double that contains the server-specified metric duration, or the value `0.0`. ## Value A number. ## Examples ### Logging server timing entries Server timing metrics require the server to send the {{HTTPHeader("Server-Timing")}} header. For example: ```http Server-Timing: cache;desc="Cache Read";dur=23.2 ``` The `serverTiming` entries can live on `navigation` and `resource` entries. Example using a {{domxref("PerformanceObserver")}}, which notifies of new `navigation` and `resource` performance entries as they are recorded in the browser's performance timeline. Use the `buffered` option to access entries from before the observer creation. ```js const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { entry.serverTiming.forEach((serverEntry) => { console.log( `${serverEntry.name} (${serverEntry.description}) duration: ${serverEntry.duration}`, ); // Logs "cache (Cache Read) duration: 23.2" }); }); }); ["navigation", "resource"].forEach((type) => observer.observe({ type, buffered: true }), ); ``` Example using {{domxref("Performance.getEntriesByType()")}}, which only shows `navigation` and `resource` performance entries present in the browser's performance timeline at the time you call this method: ```js for (const entryType of ["navigation", "resource"]) { for (const { name: url, serverTiming } of performance.getEntriesByType( entryType, )) { if (serverTiming) { for (const { name, description, duration } of serverTiming) { console.log(`${name} (${description}) duration: ${duration}`); // Logs "cache (Cache Read) duration: 23.2" } } } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("PerformanceServerTiming")}} - {{HTTPHeader("Server-Timing")}}
0
data/mdn-content/files/en-us/web/api/performanceservertiming
data/mdn-content/files/en-us/web/api/performanceservertiming/tojson/index.md
--- title: "PerformanceServerTiming: toJSON() method" short-title: toJSON() slug: Web/API/PerformanceServerTiming/toJSON page-type: web-api-instance-method browser-compat: api.PerformanceServerTiming.toJSON --- {{APIRef("Performance API")}} The **`toJSON()`** method of the {{domxref("PerformanceServerTiming")}} interface is a {{Glossary("Serialization","serializer")}}; it returns a JSON representation of the {{domxref("PerformanceServerTiming")}} object. ## Syntax ```js-nolint toJSON() ``` ### Parameters None. ### Return value A {{jsxref("JSON")}} object that is the serialization of the {{domxref("PerformanceServerTiming")}} object. ## Examples ### Logging server timing entries Server timing metrics require the server to send the {{HTTPHeader("Server-Timing")}} header. For example: ```http Server-Timing: cache;desc="Cache Read";dur=23.2 ``` The `serverTiming` entries can live on `navigation` and `resource` entries. Example using a {{domxref("PerformanceObserver")}}, which notifies of new `navigation` and `resource` performance entries as they are recorded in the browser's performance timeline. Use the `buffered` option to access entries from before the observer creation. ```js const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { entry.serverTiming.forEach((serverEntry) => { console.log(serverEntry.toJSON()); }); }); }); ["navigation", "resource"].forEach((type) => observer.observe({ type, buffered: true }), ); ``` This would log a JSON object like so: ```json { "name": "cache", "duration": 23.2, "description": "Cache Read" } ``` To get a JSON string, you can use [`JSON.stringify(serverEntry)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) directly; it will call `toJSON()` automatically. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svganimatednumber/index.md
--- title: SVGAnimatedNumber slug: Web/API/SVGAnimatedNumber page-type: web-api-interface browser-compat: api.SVGAnimatedNumber --- {{APIRef("SVG")}} ## SVG animated number interface The `SVGAnimatedNumber` interface is used for attributes of basic type [\<Number>](/en-US/docs/Web/SVG/Content_type#number) which can be animated. ### Interface overview <table class="no-markdown"> <tbody> <tr> <th scope="row">Also implement</th> <td><em>None</em></td> </tr> <tr> <th scope="row">Methods</th> <td><em>None</em></td> </tr> <tr> <th scope="row">Properties</th> <td> <ul> <li>float <code>baseVal</code></li> <li>readonly float <code>animVal</code></li> </ul> </td> </tr> <tr> <th scope="row">Normative document</th> <td> <a href="https://www.w3.org/TR/SVG11/types.html#InterfaceSVGAnimatedNumber" >SVG 1.1 (2nd Edition)</a > </td> </tr> </tbody> </table> ## Instance properties <table class="no-markdown"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>baseVal</code></td> <td>float</td> <td> The base value of the given attribute before applying any animations. </td> </tr> <tr> <td><code>animVal</code></td> <td>float</td> <td> If the given attribute or property is being animated, contains the current animated value of the attribute or property. If the given attribute or property is not currently being animated, contains the same value as <code>baseVal</code>. </td> </tr> </tbody> </table> ## Instance methods The `SVGAnimatedNumber` interface do not provide any specific methods. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/navigatorlogin/index.md
--- title: NavigatorLogin slug: Web/API/NavigatorLogin page-type: web-api-interface status: - experimental browser-compat: api.NavigatorLogin --- {{securecontext_header}}{{APIRef("FedCM API")}}{{SeeCompatTable}} The **`NavigatorLogin`** interface of the [Federated Credential Management (FedCM) API](/en-US/docs/Web/API/FedCM_API) defines login functionality for federated identity providers (IdPs). Specifically, it enables a federated identity provider (IdP) to set its login status when a user signs into or out of the IdP. See [Update login status using the Login Status API](/en-US/docs/Web/API/FedCM_API/IDP_integration#update_login_status_using_the_login_status_api) for more details of how this is used. `NavigatorLogin` is accessed via the {{domxref("Navigator.login")}} property. {{InheritanceDiagram}} ## Instance methods - {{domxref("NavigatorLogin.setStatus", "setStatus()")}} {{Experimental_Inline}} - : Sets the login status of a federated identity provider (IdP), when called from the IdP's origin. By "login status", we mean "whether any users are logged into the IdP on the current browser or not". ## Examples ```js /* Set logged-in status */ navigator.login.setStatus("logged-in"); /* Set logged-out status */ navigator.login.setStatus("logged-out"); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Federated Credential Management (FedCM) API](/en-US/docs/Web/API/FedCM_API)
0
data/mdn-content/files/en-us/web/api/navigatorlogin
data/mdn-content/files/en-us/web/api/navigatorlogin/setstatus/index.md
--- title: "NavigatorLogin: setStatus() method" short-title: setStatus() slug: Web/API/NavigatorLogin/setStatus page-type: web-api-instance-method status: - experimental browser-compat: api.NavigatorLogin.setStatus --- {{securecontext_header}}{{APIRef("FedCM API")}}{{SeeCompatTable}} The **`setStatus()`** method of the {{domxref("NavigatorLogin")}} interface sets the login status of a federated identity provider (IdP), when called from the IdP's origin. By this, we mean "whether any users are logged into the IdP on the current browser or not". This should be called by the IdP site following a user login or logout. The browser stores this state for each IdP; the [FedCM API](/en-US/docs/Web/API/FedCM_API) API then uses it to reduce the number of requests it makes to the IdP (because it does not need to waste time requesting accounts when there are no users logged in to the IdP). It also mitigates [potential timing attacks](https://github.com/fedidcg/FedCM/issues/447). See [Update login status using the Login Status API](/en-US/docs/Web/API/FedCM_API/IDP_integration#update_login_status_using_the_login_status_api) for more information about FedCM login status. ## Syntax ```js-nolint setStatus(status) ``` ### Parameters - `status` - : A string representing the login status to set for the IdP. Possible values are: - `"logged-in"`: The IdP has at least one user account signed in. - `"logged-out"`: All IdP user accounts are currently signed out. ### Return value A {{jsxref("Promise")}} that fulfills with `undefined`. ### Exceptions - `SecurityError` {{domxref("DOMException")}} - : Thrown if the calling domain is not in a frame where all of the nesting hierarchy is same-origin. Whether called from the main frame, an {{htmlelement("iframe")}} nested inside the main frame, or another `<iframe>` nested one or more levels deep inside the first `<iframe>`, _all_ levels of the nesting hierarchy must be same-origin for the call to be successful. ## Examples ```js /* Set logged-in status */ navigator.login.setStatus("logged-in"); /* Set logged-out status */ navigator.login.setStatus("logged-out"); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Federated Credential Management (FedCM) API](/en-US/docs/Web/API/FedCM_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/trustedtypes/index.md
--- title: trustedTypes global property short-title: trustedTypes slug: Web/API/trustedTypes page-type: web-api-global-property browser-compat: api.trustedTypes --- {{APIRef("Trusted Types API")}}{{AvailableInWorkers}} The global **`trustedTypes`** read-only property returns the {{domxref("TrustedTypePolicyFactory")}} object associated with the global object, providing the entry point for using the {{domxref("Trusted Types API", "", "", "nocode")}}. ## Value An {{domxref("TrustedTypePolicyFactory")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgdescelement/index.md
--- title: SVGDescElement slug: Web/API/SVGDescElement page-type: web-api-interface browser-compat: api.SVGDescElement --- {{APIRef("SVG")}} The **`SVGDescElement`** interface corresponds to the {{SVGElement("desc")}} element. {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties from its parent, {{domxref("SVGGeometryElement")}}._ ## Instance methods _This interface has no methods but inherits methods from its parent, {{domxref("SVGGeometryElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{SVGElement("desc")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/sharedstorageworkletglobalscope/index.md
--- title: SharedStorageWorkletGlobalScope slug: Web/API/SharedStorageWorkletGlobalScope page-type: web-api-interface status: - experimental browser-compat: api.SharedStorageWorkletGlobalScope --- {{APIRef("Shared Storage API")}}{{SeeCompatTable}} The **`SharedStorageWorkletGlobalScope`** interface of the {{domxref("Shared Storage API", "Shared Storage API", "", "nocode")}} represents the global scope of a {{domxref("SharedStorageWorklet")}} module. {{InheritanceDiagram}} ## Instance properties - {{domxref("SharedStorageWorkletGlobalScope.sharedStorage", "sharedStorage")}} {{Experimental_Inline}} - : Contains an instance of the {{domxref("WorkletSharedStorage")}} object, representing the shared storage for a particular origin as exposed in a worklet context. ## Instance methods - {{domxref("SharedStorageWorkletGlobalScope.register", "register()")}} {{Experimental_Inline}} - : Registers an {{domxref("SharedStorageOperation", "operation", "", "nocode")}} defined inside the current worklet module. ## Examples ```js // ab-testing-worklet.js class SelectURLOperation { async run(urls, data) { // Read the user's experiment group from shared storage const experimentGroup = await this.sharedStorage.get("ab-testing-group"); // Return the group number return experimentGroup; } } register("ab-testing", SelectURLOperation); ``` See the [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API) landing page for a walkthrough of this example and links to other examples. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API)
0
data/mdn-content/files/en-us/web/api/sharedstorageworkletglobalscope
data/mdn-content/files/en-us/web/api/sharedstorageworkletglobalscope/register/index.md
--- title: "SharedStorageWorkletGlobalScope: register() method" short-title: register() slug: Web/API/SharedStorageWorkletGlobalScope/register page-type: web-api-instance-method status: - experimental browser-compat: api.SharedStorageWorkletGlobalScope.register --- {{APIRef("Shared Storage API")}}{{SeeCompatTable}} The **`register()`** method of the {{domxref("SharedStorageWorkletGlobalScope")}} interface registers an {{domxref("SharedStorageOperation", "operation", "", "nocode")}} defined inside the current worklet module. ## Syntax ```js-nolint register(name, operationCtor) ``` ### Parameters - `name` - : A string representing the name with which you want to register the operation. When the operation is invoked (say via {{domxref("WindowSharedStorage.run()")}} or {{domxref("WindowSharedStorage.selectURL()")}}), this name is used to identify the operation you want to run. - `operationCtor` - : A string representing the class name of the operation to be registered. This is the class constructor that is invoked when the operation is run. ### Return value None (`undefined`). ### Exceptions - {{jsxref("TypeError")}} - : Thrown if: - An operation has already been registered with the specified name. - The `operationCtor` is not a valid constructor. - The class does not contain a valid `run()` method. - The worklet module has not been added with {{domxref("Worklet.addModule", "SharedStorageWorklet.addModule()")}}. ## Examples ```js // ab-testing-worklet.js class SelectURLOperation { async run(urls, data) { // Read the user's experiment group from shared storage const experimentGroup = await this.sharedStorage.get("ab-testing-group"); // Return the group number return experimentGroup; } } register("ab-testing", SelectURLOperation); ``` See the [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API) landing page for a walkthrough of this example and for links to other examples. > **Note:** It is possible to define and register multiple operations in the same shared storage worklet module script with different names; see {{domxref("SharedStorageOperation")}} for an example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API)
0
data/mdn-content/files/en-us/web/api/sharedstorageworkletglobalscope
data/mdn-content/files/en-us/web/api/sharedstorageworkletglobalscope/sharedstorage/index.md
--- title: "SharedStorageWorkletGlobalScope: sharedStorage property" short-title: sharedStorage slug: Web/API/SharedStorageWorkletGlobalScope/sharedStorage page-type: web-api-instance-property status: - experimental browser-compat: api.SharedStorageWorkletGlobalScope.sharedStorage --- {{APIRef("Shared Storage API")}}{{SeeCompatTable}} The **`context`** read-only property of the {{domxref("SharedStorageWorkletGlobalScope")}} interface contains a {{domxref("WorkletSharedStorage")}} object instance, which represents the shared storage for a particular origin as exposed to a worklet context. ## Value A {{domxref("WorkletSharedStorage")}} object instance. ## Examples ```js // ab-testing-worklet.js class SelectURLOperation { async run(urls, data) { // Read the user's experiment group from shared storage const experimentGroup = await this.sharedStorage.get("ab-testing-group"); // Return the group number return experimentGroup; } } register("ab-testing", SelectURLOperation); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgfontfacenameelement/index.md
--- title: SVGFontFaceNameElement slug: Web/API/SVGFontFaceNameElement page-type: web-api-interface status: - deprecated browser-compat: api.SVGFontFaceNameElement --- {{APIRef("SVG")}}{{deprecated_header}} The **`SVGFontFaceNameElement`** interface corresponds to the {{SVGElement("font-face-name")}} elements. Object-oriented access to the attributes of the {{SVGElement("font-face-name")}} 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-name")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/cssrotate/index.md
--- title: CSSRotate slug: Web/API/CSSRotate page-type: web-api-interface browser-compat: api.CSSRotate --- {{APIRef("CSS Typed Object Model API")}} The **`CSSRotate`** interface of the {{domxref('CSS_Object_Model#css_typed_object_model','','',' ')}} represents the rotate value of the individual {{CSSXRef('transform')}} property in CSS. It inherits properties and methods from its parent {{domxref('CSSTransformValue')}}. {{InheritanceDiagram}} ## Constructor - {{domxref("CSSRotate.CSSRotate", "CSSRotate()")}} - : Creates a new `CSSRotate` object. ## Instance properties - {{domxref('CSSRotate.x','x')}} - : Returns or sets the x-axis value. - {{domxref('CSSRotate.y','y')}} - : Returns or sets the y-axis value. - {{domxref('CSSRotate.z','z')}} - : Returns or sets the z-axis value. - {{domxref('CSSRotate.angle','angle')}} - : Returns or sets the angle value. ## Examples To do. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssrotate
data/mdn-content/files/en-us/web/api/cssrotate/z/index.md
--- title: "CSSRotate: z property" short-title: z slug: Web/API/CSSRotate/z page-type: web-api-instance-property browser-compat: api.CSSRotate.z --- {{APIRef("CSS Typed OM")}} The **`z`** property of the {{domxref("CSSRotate")}} interface representing the z-component of the translating vector. A positive value moves the element towards the viewer, and a negative value farther away. ## Value A double integer or a {{domxref("CSSNumericValue")}} ## Examples To Do ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssrotate
data/mdn-content/files/en-us/web/api/cssrotate/y/index.md
--- title: "CSSRotate: y property" short-title: "y" slug: Web/API/CSSRotate/y page-type: web-api-instance-property browser-compat: api.CSSRotate.y --- {{APIRef("CSS Typed OM")}} The **`y`** property of the {{domxref("CSSRotate")}} interface gets and sets the ordinate or y-axis of the translating vector. ## Value A double integer or a {{domxref("CSSNumericValue")}} ## Examples To Do ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssrotate
data/mdn-content/files/en-us/web/api/cssrotate/x/index.md
--- title: "CSSRotate: x property" short-title: x slug: Web/API/CSSRotate/x page-type: web-api-instance-property browser-compat: api.CSSRotate.x --- {{APIRef("CSS Typed OM")}} The **`x`** property of the {{domxref("CSSRotate")}} interface gets and sets the abscissa or x-axis of the translating vector. ## Value A double integer or a {{domxref("CSSNumericValue")}} ## Examples To Do ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssrotate
data/mdn-content/files/en-us/web/api/cssrotate/cssrotate/index.md
--- title: "CSSRotate: CSSRotate() constructor" short-title: CSSRotate() slug: Web/API/CSSRotate/CSSRotate page-type: web-api-constructor browser-compat: api.CSSRotate.CSSRotate --- {{APIRef("CSS Typed OM")}} The **`CSSRotate()`** constructor creates a new {{domxref("CSSRotate")}} object representing the [rotate()](/en-US/docs/Web/CSS/transform-function/rotate) value of the individual {{CSSXref('transform')}} property in CSS. ## Syntax ```js-nolint new CSSRotate(x, y, z, angle) ``` ### Parameters - {{domxref('CSSRotate.x','x')}} - : A value for the x-axis of the {{domxref('CSSRotate')}} object to be constructed. This must either be a double integer or a {{domxref('CSSNumericValue')}}. - {{domxref('CSSRotate.y','y')}} - : A value for the y-axis of the {{domxref('CSSRotate')}} object to be constructed. This must either be a double integer or a {{domxref('CSSNumericValue')}}. - {{domxref('CSSRotate.z','z')}} - : A value for the z-axis of the {{domxref('CSSRotate')}} object to be constructed. This must either be a double integer or a {{domxref('CSSNumericValue')}}. - {{domxref('CSSRotate.angle','angle')}} - : A value for the angle of the {{domxref('CSSRotate')}} object to be constructed. This must be a {{domxref('CSSNumericValue')}}. ### Exceptions - [`TypeError`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) - : Raised if the value of `CSSRotate.angle` is not an [\<angle>](/en-US/docs/Web/CSS/angle) value or `CSSRotate.x`, `CSSRotate.y`, `CSSRotate.z` are not [\<number>](/en-US/docs/Web/CSS/number) values. ## Examples To do ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssrotate
data/mdn-content/files/en-us/web/api/cssrotate/angle/index.md
--- title: "CSSRotate: angle property" short-title: angle slug: Web/API/CSSRotate/angle page-type: web-api-instance-property browser-compat: api.CSSRotate.angle --- {{APIRef("CSS Typed OM")}} The **`angle`** property of the {{domxref("CSSRotate")}} interface gets and sets the angle of rotation. A positive angle denotes a clockwise rotation, a negative angle a counter-clockwise one. ## Value A {{domxref("CSSNumericValue")}} ## Examples To Do ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmldocument/index.md
--- title: HTMLDocument slug: Web/API/HTMLDocument page-type: web-api-interface browser-compat: api.HTMLDocument --- {{APIRef("HTML DOM")}} For historical reasons, {{domxref("Window")}} objects have a `window.HTMLDocument` property whose value is the {{DOMxRef("Document")}} interface. So you can think of `HTMLDocument` as an alias for {{DOMxRef("Document")}}, and you can find documentation for `HTMLDocument` members under the documentation for the {{DOMxRef("Document")}} interface. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/pushmessagedata/index.md
--- title: PushMessageData slug: Web/API/PushMessageData page-type: web-api-interface browser-compat: api.PushMessageData --- {{APIRef("Push API")}}{{SecureContext_Header}} The **`PushMessageData`** interface of the [Push API](/en-US/docs/Web/API/Push_API) provides methods which let you retrieve the push data sent by a server in various formats. Unlike the similar methods in the [Fetch API](/en-US/docs/Web/API/Fetch_API), which only allow the method to be invoked once, these methods can be called multiple times. Messages received through the Push API are sent encrypted by push services and then automatically decrypted by browsers before they are made accessible through the methods of the `PushMessageData` interface. ## Instance properties None. ## Instance methods - {{domxref("PushMessageData.arrayBuffer()")}} - : Extracts the data as an {{jsxref("ArrayBuffer")}} object. - {{domxref("PushMessageData.blob()")}} - : Extracts the data as a {{domxref("Blob")}} object. - {{domxref("PushMessageData.json()")}} - : Extracts the data as a [JSON](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) object. - {{domxref("PushMessageData.text()")}} - : Extracts the data as a plain text string. ## Examples ```js self.addEventListener("push", (event) => { const obj = event.data.json(); if (obj.action === "subscribe" || obj.action === "unsubscribe") { fireNotification(obj, event); port.postMessage(obj); } else if (obj.action === "init" || obj.action === "chatMsg") { port.postMessage(obj); } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/pushmessagedata
data/mdn-content/files/en-us/web/api/pushmessagedata/json/index.md
--- title: "PushMessageData: json() method" short-title: json() slug: Web/API/PushMessageData/json page-type: web-api-instance-method browser-compat: api.PushMessageData.json --- {{APIRef("Push API")}}{{SecureContext_Header}} The **`json()`** method of the {{domxref("PushMessageData")}} interface extracts push message data by parsing it as a [JSON](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) string and returning the result. ## Syntax ```js-nolint json() ``` ### Parameters None. ### Return value The result of parsing push event data as JSON. This could be anything that can be represented by JSON — an object, an array, a string, a number… ## Examples ```js self.addEventListener("push", (event) => { const myData = event.data.json(); // do something with your data }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/pushmessagedata
data/mdn-content/files/en-us/web/api/pushmessagedata/blob/index.md
--- title: "PushMessageData: blob() method" short-title: blob() slug: Web/API/PushMessageData/blob page-type: web-api-instance-method browser-compat: api.PushMessageData.blob --- {{APIRef("Push API")}}{{SecureContext_Header}} The **`blob()`** method of the {{domxref("PushMessageData")}} interface extracts push message data as a {{domxref("Blob")}} object. ## Syntax ```js-nolint blob() ``` ### Parameters None. ### Return value A {{domxref("Blob")}}. ## Examples ```js self.addEventListener("push", (event) => { const blob = event.data.blob(); // do something with your Blob }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/pushmessagedata
data/mdn-content/files/en-us/web/api/pushmessagedata/arraybuffer/index.md
--- title: "PushMessageData: arrayBuffer() method" short-title: arrayBuffer() slug: Web/API/PushMessageData/arrayBuffer page-type: web-api-instance-method browser-compat: api.PushMessageData.arrayBuffer --- {{APIRef("Push API")}}{{SecureContext_Header}} The **`arrayBuffer()`** method of the {{domxref("PushMessageData")}} interface extracts push message data as an {{jsxref("ArrayBuffer")}} object. ## Syntax ```js-nolint arrayBuffer() ``` ### Parameters None. ### Return value An {{jsxref("ArrayBuffer")}}. ## Examples ```js self.addEventListener("push", (event) => { const buffer = event.data.arrayBuffer(); // do something with your array buffer }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/pushmessagedata
data/mdn-content/files/en-us/web/api/pushmessagedata/text/index.md
--- title: "PushMessageData: text() method" short-title: text() slug: Web/API/PushMessageData/text page-type: web-api-instance-method browser-compat: api.PushMessageData.text --- {{APIRef("Push API")}}{{SecureContext_Header}} The **`text()`** method of the {{domxref("PushMessageData")}} interface extracts push message data as a plain text string. ## Syntax ```js-nolint text() ``` ### Parameters None. ### Return value A string. ## Examples ```js self.addEventListener("push", (event) => { const textObj = event.data.text(); // do something with your text }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/gpurenderbundle/index.md
--- title: GPURenderBundle slug: Web/API/GPURenderBundle page-type: web-api-interface status: - experimental browser-compat: api.GPURenderBundle --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`GPURenderBundle`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} represents a container for pre-recorded bundles of commands. The command bundles are encoded using a {{domxref("GPURenderBundleEncoder")}}; once the desired commands have been encoded, they are recorded into a `GPURenderBundle` object instance using the {{domxref("GPURenderBundleEncoder.finish()")}} method. These command bundles can then be reused across multiple render passes by passing the `GPURenderBundle` objects into {{domxref("GPURenderPassEncoder.executeBundles()")}} calls. Reusing pre-recoded commands can significantly improve app performance in situations where JavaScript draw call overhead is a bottleneck. Render bundles are most effective in situations where a batch of objects will be drawn the same way across multiple views or frames, with the only differences being the buffer content being used (such as updated matrix uniforms). A good example is VR rendering. Recording the rendering as a render bundle and then tweaking the view matrix and replaying it for each eye is a more efficient way to issue draw calls for both renderings of the scene. {{InheritanceDiagram}} ## Instance properties - {{domxref("GPUComputePassEncoder.label", "label")}} {{Experimental_Inline}} - : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. ## Examples In the WebGPU Samples [Animometer example](https://webgpu.github.io/webgpu-samples/samples/animometer), a lot of like operations are done on many different objects simultaneously. A render bundle is encoded using the following function: ```js function recordRenderPass( passEncoder: GPURenderBundleEncoder | GPURenderPassEncoder ) { if (settings.dynamicOffsets) { passEncoder.setPipeline(dynamicPipeline); } else { passEncoder.setPipeline(pipeline); } passEncoder.setVertexBuffer(0, vertexBuffer); passEncoder.setBindGroup(0, timeBindGroup); const dynamicOffsets = [0]; for (let i = 0; i < numTriangles; ++i) { if (settings.dynamicOffsets) { dynamicOffsets[0] = i * alignedUniformBytes; passEncoder.setBindGroup(1, dynamicBindGroup, dynamicOffsets); } else { passEncoder.setBindGroup(1, bindGroups[i]); } passEncoder.draw(3, 1, 0, 0); } } ``` Later on, a {{domxref("GPURenderBundleEncoder")}} is created, the function is invoked, and the render bundle is recorded using {{domxref("GPURenderBundleEncoder.finish()")}}: ```js const renderBundleEncoder = device.createRenderBundleEncoder({ colorFormats: [presentationFormat], }); recordRenderPass(renderBundleEncoder); const renderBundle = renderBundleEncoder.finish(); ``` {{domxref("GPURenderPassEncoder.executeBundles()")}} is then used to reuse the work across multiple render passes to improve performance. Study the example code listing for the full context. ```js // ... return function doDraw(timestamp) { if (startTime === undefined) { startTime = timestamp; } uniformTime[0] = (timestamp - startTime) / 1000; device.queue.writeBuffer(uniformBuffer, timeOffset, uniformTime.buffer); renderPassDescriptor.colorAttachments[0].view = context .getCurrentTexture() .createView(); const commandEncoder = device.createCommandEncoder(); const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor); if (settings.renderBundles) { passEncoder.executeBundles([renderBundle]); } else { recordRenderPass(passEncoder); } passEncoder.end(); device.queue.submit([commandEncoder.finish()]); }; // ... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpurenderbundle
data/mdn-content/files/en-us/web/api/gpurenderbundle/label/index.md
--- title: "GPURenderBundle: label property" short-title: label slug: Web/API/GPURenderBundle/label page-type: web-api-instance-property status: - experimental browser-compat: api.GPURenderBundle.label --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`label`** read-only property of the {{domxref("GPURenderBundle")}} interface is a string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. This can be set by providing a `label` property in the descriptor object passed into the originating {{domxref("GPURenderBundleEncoder.finish()")}} call, or you can get and set it directly on the `GPURenderBundle` object. ## Value A string. If no label value has previously been set, getting the label returns an empty string. ## Examples Setting and getting a label via `GPURenderBundle.label`: ```js const renderBundle = renderBundleEncoder.finish(); renderBundle.label = "myrenderbundle"; console.log(renderBundle.label); // "myrenderbundle" ``` Setting a label via the originating {{domxref("GPURenderBundleEncoder.finish()")}} call, and then getting it via `GPURenderBundle.label`: ```js const renderBundle = renderBundleEncoder.finish({ label: "myrenderbundle", }); console.log(renderBundle.label); // "myrenderbundle" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/houdini_apis/index.md
--- title: Houdini APIs slug: Web/API/Houdini_APIs page-type: guide --- {{DefaultAPISidebar("Houdini API")}} Houdini is a set of low-level APIs that exposes parts of the CSS engine, giving developers the power to extend CSS by hooking into the styling and layout process of a browser's rendering engine. Houdini is a group of APIs that give developers direct access to the [CSS Object Model](/en-US/docs/Web/API/CSS_Object_Model) (CSSOM), enabling developers to write code the browser can parse as CSS, thereby creating new CSS features without waiting for them to be implemented natively in browsers. ## Advantages of Houdini Houdini enables faster parse times than using JavaScript {{domxref("HTMLElement.style")}} for style changes. Browsers parse the CSSOM — including layout, paint, and composite processes — before applying any style updates found in scripts. In addition, layout, paint, and composite processes are repeated for JavaScript style updates. Houdini code doesn't wait for that first rendering cycle to be complete. Rather, it is included in that first cycle — creating renderable, understandable styles. Houdini provides an object-based API for working with CSS values in JavaScript. Houdini's [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API) is a CSS Object Model with types and methods, exposing values as JavaScript objects making for more intuitive CSS manipulation than previous string based {{domxref("HTMLElement.style")}} manipulations. Every element and style sheet rule has a style map which is accessible via its {{domxref("StylePropertyMap")}}. A feature of CSS Houdini is the {{domxref("Worklet")}}. With worklets, you can create modular CSS, requiring a single line of JavaScript to import configurable components: no pre-processors, post-processors or JavaScript frameworks needed. ```js CSS.paintWorklet.addModule("csscomponent.js"); ``` This added module contains {{domxref("PaintWorkletGlobalScope.registerPaint")}} functions, which register completely configurable worklets. > **Note:** You can write your own worklets, or install components created by other people. > The [Houdini.how](https://houdini.how/) website is a collection of worklets, > with [instructions on how to use them](https://houdini.how/usage/). The CSS `paint()` function is an additional function supported by the {{cssxref("image")}} type. It takes parameters that include the name of the worklet, plus additional parameters needed by the worklet. The worklet also has access to the element's custom properties: they don't need to be passed as function arguments. In the following example the `paint()` function is passed a worklet called `myComponent`. ```css li { background-image: paint(myComponent, stroke, 10px); --highlights: blue; --lowlights: green; } ``` > **Note:** With great power comes great responsibility! > With Houdini you _could_ invent your own masonry, grid, or regions implementation, > but doing so is not necessarily the best idea. > The CSS Working group does a lot of work to ensure every feature is performant, > handles all edge cases, and considers security, privacy, and accessibility. > As you extend CSS with Houdini, make sure to keep these considerations in mind, > and start small before moving on to more ambitious projects. ## The Houdini APIs Below you can find links to the main reference pages covering the APIs that fall under the Houdini umbrella, along with links to guides to help you if you need guidance in learning how to use them. ### CSS Properties and Values API Defines an API for registering new CSS properties. Properties registered using this API are provided with a parse syntax that defines a type, inheritance behavior, and an initial value. - [CSS Properties and Values API reference](/en-US/docs/Web/API/CSS_Properties_and_Values_API) - [CSS Properties and Values API guide](/en-US/docs/Web/API/CSS_Properties_and_Values_API/guide) - [Smarter custom properties with Houdini's new API](https://web.dev/articles/css-props-and-vals) ### CSS Typed OM Converting CSSOM value strings into meaningfully typed JavaScript representations and back can incur a significant performance overhead. The CSS Typed OM exposes CSS values as typed JavaScript objects to allow their performant manipulation. - [CSS Typed OM reference](/en-US/docs/Web/API/CSS_Typed_OM_API) - [CSS Typed OM guide](/en-US/docs/Web/API/CSS_Typed_OM_API/Guide) - [Working with the new CSS Typed Object Model](https://developer.chrome.com/blog/cssom/) ### CSS Painting API Developed to improve the extensibility of CSS, the Painting API allows developers to write JavaScript functions that can draw directly into an element's background, border, or content via the `paint()` CSS function. - [CSS Painting API reference](/en-US/docs/Web/API/CSS_Painting_API) - [CSS Painting API guide](/en-US/docs/Web/API/CSS_Painting_API/Guide) - [CSS Paint API](https://developer.chrome.com/blog/paintapi/) - [The CSS Paint API](https://css-tricks.com/the-css-paint-api/) - [Simulating Drop Shadows with the CSS Paint API](https://css-tricks.com/simulating-drop-shadows-with-the-css-paint-api/) - [CSS Paint API Being predictably random](https://jakearchibald.com/2020/css-paint-predictably-random/) ### Worklets An API for running scripts in various stages of the rendering pipeline independent of the main JavaScript execution environment. Worklets are conceptually similar to [Web Workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers), and are called by and extend the rendering engine. - [Worklets reference](/en-US/docs/Web/API/Worklet) ### CSS Layout API Designed to improve the extensibility of CSS, this API enables developers to write their own layout algorithms, like masonry or line snapping. _This API has some partial support in Chrome Canary. It is not yet documented on MDN._ ### CSS Parser API An API exposing the CSS parser more directly, for parsing arbitrary CSS-like languages into a mildly typed representation. _This API is currently a proposal, and has no browser implementations or documentation on MDN._ - [Proposal](https://github.com/WICG/css-parser-api) ### Font Metrics API An API exposing font metrics, giving access to typographic layout results. _This API is currently a proposal, and has no browser implementations or documentation on MDN._ - [Proposal](https://github.com/w3c/css-houdini-drafts/blob/main/font-metrics-api/README.md) ## See also - The [Worklet library](https://houdini.how/) for examples and code. - [Interactive introduction to Houdini](https://houdini.glitch.me/) - [Is Houdini Ready Yet?](https://houdini.glitch.me/)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/rtcdatachannel/index.md
--- title: RTCDataChannel slug: Web/API/RTCDataChannel page-type: web-api-interface browser-compat: api.RTCDataChannel --- {{APIRef("WebRTC")}} The **`RTCDataChannel`** interface represents a network channel which can be used for bidirectional peer-to-peer transfers of arbitrary data. Every data channel is associated with an {{DOMxRef("RTCPeerConnection")}}, and each peer connection can have up to a theoretical maximum of 65,534 data channels (the actual limit may vary from browser to browser). To create a data channel and ask a remote peer to join you, call the {{DOMxRef("RTCPeerConnection")}}'s {{DOMxRef("RTCPeerConnection.createDataChannel", "createDataChannel()")}} method. The peer being invited to exchange data receives a {{DOMxRef("RTCPeerConnection.datachannel_event", "datachannel")}} event (which has type {{DOMxRef("RTCDataChannelEvent")}}) to let it know the data channel has been added to the connection. `RTCDataChannel` is a [transferable object](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects). {{InheritanceDiagram}} ## Instance properties _Also inherits properties from {{DOMxRef("EventTarget")}}._ - {{DOMxRef("RTCDataChannel.binaryType", "binaryType")}} - : A string specifying the type of object that should be used to represent binary data received on the `RTCDataChannel`. Values are the same as allowed on the {{DOMxRef("WebSocket.binaryType")}} property: `blob` if {{DOMxRef("Blob")}} objects are being used, or `arraybuffer` if {{jsxref("ArrayBuffer")}} objects are being used. The default is `blob`. - {{DOMxRef("RTCDataChannel.bufferedAmount", "bufferedAmount")}} {{ReadOnlyInline}} - : Returns the number of bytes of data currently queued to be sent over the data channel. - {{DOMxRef("RTCDataChannel.bufferedAmountLowThreshold", "bufferedAmountLowThreshold")}} - : Specifies the number of bytes of buffered outgoing data that is considered "low". The default value is 0. - {{DOMxRef("RTCDataChannel.id", "id")}} {{ReadOnlyInline}} - : Returns an ID number (between 0 and 65,534) which uniquely identifies the `RTCDataChannel`. - {{DOMxRef("RTCDataChannel.label", "label")}} {{ReadOnlyInline}} - : Returns a string that contains a name describing the data channel. These labels are not required to be unique. - {{DOMxRef("RTCDataChannel.maxPacketLifeTime", "maxPacketLifeTime")}} {{ReadOnlyInline}} - : Returns the amount of time, in milliseconds, the browser is allowed to take to attempt to transmit a message, as set when the data channel was created, or `null`. - {{DOMxRef("RTCDataChannel.maxRetransmits", "maxRetransmits")}} {{ReadOnlyInline}} - : Returns the maximum number of times the browser should try to retransmit a message before giving up, as set when the data channel was created, or `null`, which indicates that there is no maximum. - {{DOMxRef("RTCDataChannel.negotiated", "negotiated")}} {{ReadOnlyInline}} - : Indicates whether the `RTCDataChannel`'s connection was negotiated by the Web app (`true`) or by the WebRTC layer (`false`). The default is `false`. - {{DOMxRef("RTCDataChannel.ordered", "ordered")}} {{ReadOnlyInline}} - : Indicates whether or not the data channel guarantees in-order delivery of messages; the default is `true`, which indicates that the data channel is indeed ordered. - {{DOMxRef("RTCDataChannel.protocol", "protocol")}} {{ReadOnlyInline}} - : Returns a string containing the name of the subprotocol in use. If no protocol was specified when the data channel was created, then this property's value is the empty string (`""`). - {{DOMxRef("RTCDataChannel.readyState", "readyState")}} {{ReadOnlyInline}} - : Returns a string which indicates the state of the data channel's underlying data connection. It can have one of the following values: `connecting`, `open`, `closing`, or `closed`. ### Obsolete properties - {{DOMxRef("RTCDataChannel.reliable", "reliable")}} {{ReadOnlyInline}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Indicates whether or not the data channel is _reliable_. ## Instance methods _Also inherits methods from {{DOMxRef("EventTarget")}}._ - {{DOMxRef("RTCDataChannel.close", "close()")}} - : Closes the {{domxref("RTCDataChannel")}}. Either peer is permitted to call this method to initiate closure of the channel. - {{DOMxRef("RTCDataChannel.send", "send()")}} - : Sends data across the data channel to the remote peer. ## Events - {{domxref("RTCDataChannel.bufferedamountlow_event", "bufferedamountlow")}} - : Sent when the number of bytes of data in the outgoing data buffer falls below the value specified by {{domxref("RTCDataChannel.bufferedAmountLowThreshold", "bufferedAmountLowThreshold")}}. - {{domxref("RTCDataChannel.close_event", "close")}} - : Sent when the underlying data transport closes. - {{domxref("RTCDataChannel.closing_event", "closing")}} - : Sent when the underlying data transport is about to start closing. - {{domxref("RTCDataChannel.error_event", "error")}} - : Sent when an error occurs on the data channel. - {{domxref("RTCDataChannel.message_event", "message")}} - : Sent when a message has been received from the remote peer. The message contents can be found in the event's {{domxref("MessageEvent.data", "data")}} property. - {{domxref("RTCDataChannel.open_event", "open")}} - : Sent when the data channel is first opened, or when an existing data channel's underlying connection re-opens. ## Data format The underlying data format is defined by the IEEE specification [SDP Offer/Answer Procedures for SCTP over DTLS Transport(RFC 8841)](https://datatracker.ietf.org/doc/rfc8841/). The current format specifies its protocol as either `"UDP/DTLS/SCTP"` (UDP carrying DTLS carrying SCTP) or `"TCP/DTLS/SCTP"` (TCP carrying DTLS carrying SCTP). Older browsers may only specify `"DTLS/SCTP"`. ## Example ```js const pc = new RTCPeerConnection(); const dc = pc.createDataChannel("my channel"); dc.onmessage = (event) => { console.log(`received: ${event.data}`); }; dc.onopen = () => { console.log("datachannel open"); }; dc.onclose = () => { console.log("datachannel close"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/binarytype/index.md
--- title: "RTCDataChannel: binaryType property" short-title: binaryType slug: Web/API/RTCDataChannel/binaryType page-type: web-api-instance-property browser-compat: api.RTCDataChannel.binaryType --- {{APIRef("WebRTC")}} The property **`binaryType`** on the {{domxref("RTCDataChannel")}} interface is a string which specifies the type of object which should be used to represent binary data received on the {{domxref("RTCDataChannel")}}. Values allowed by the {{domxref("WebSocket.binaryType")}} property are also permitted here: `blob` if {{domxref("Blob")}} objects are being used or `arraybuffer` if {{jsxref("ArrayBuffer")}} objects are being used. The default is `blob`. When a binary message is received on the data channel, the resulting {{DOMxRef("RTCDataChannel.message_event", "message")}} event's {{domxref("MessageEvent.data")}} property is an object of the type specified by the `binaryType`. ## Value A string that can have one of these values: - `"blob"` - : Received binary messages' contents will be contained in {{domxref("Blob")}} objects. - `"arraybuffer"` - : Received binary messages' contents will be contained in {{jsxref("ArrayBuffer")}} objects. ## Example This code configures a data channel to receive binary data in {{jsxref("ArrayBuffer")}} objects, and establishes a listener for {{DOMxRef("RTCDataChannel.message_event", "message")}} events which constructs a string representing the received data as a list of hexadecimal byte values. ```js const dc = peerConnection.createDataChannel("Binary"); dc.binaryType = "arraybuffer"; dc.onmessage = (event) => { const byteArray = new Uint8Array(event.data); let hexString = ""; byteArray.forEach((byte) => { hexString += `${byte.toString(16)} `; }); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - [Using WebRTC data channels](/en-US/docs/Web/API/WebRTC_API/Using_data_channels) - {{domxref("RTCDataChannel")}} - {{domxref("RTCDataChannel.send()")}}
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/reliable/index.md
--- title: "RTCDataChannel: reliable property" short-title: reliable slug: Web/API/RTCDataChannel/reliable page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.RTCDataChannel.reliable --- {{APIRef("WebRTC")}}{{Deprecated_Header}}{{Non-standard_Header}} The read-only `RTCDataChannel` property **`reliable`** indicates whether or not the data channel is reliable. > **Warning:** This property is obsolete. Use {{domxref("RTCDataChannel.ordered")}} instead in any > new code, and update existing code as soon as possible. ## Value `true` if the {{domxref("RTCDataChannel")}}'s connection is reliable; `false` if it isn't. ## Specifications No longer part of any specification. ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCDataChannel")}} - {{domxref("RTCDataChannel.ordered")}}
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/bufferedamountlowthreshold/index.md
--- title: "RTCDataChannel: bufferedAmountLowThreshold property" short-title: bufferedAmountLowThreshold slug: Web/API/RTCDataChannel/bufferedAmountLowThreshold page-type: web-api-instance-property browser-compat: api.RTCDataChannel.bufferedAmountLowThreshold --- {{APIRef("WebRTC")}} The `RTCDataChannel` property **`bufferedAmountLowThreshold`** is used to specify the number of bytes of buffered outgoing data that is considered "low." The default value is 0\. When the number of buffered outgoing bytes, as indicated by the {{domxref("RTCDataChannel.bufferedAmount", "bufferedAmount")}} property, falls to or below this value, a {{DOMxRef("RTCDataChannel.bufferedamountlow_event", "bufferedamountlow")}} event is fired. This event may be used, for example, to implement code which queues more messages to be sent whenever there's room to buffer them. Listeners may be added with {{domxref("RTCDataChannel.bufferedamountlow_event", "onbufferedamountlow")}} or {{domxref("EventTarget.addEventListener", "addEventListener()")}}. The user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event loop or truly asynchronously. As messages are actually sent, this value is reduced accordingly. > **Note:** `bufferedamountlow` events are not fired after the data channel is closed. ## Value The number of queued outgoing data bytes below which the buffer is considered to be "low." ## Example In this snippet of code, `bufferedAmountLowThreshold` is set to 64kB, and a handler for the {{DOMxRef("RTCDataChannel.bufferedamountlow_event", "bufferedamountlow")}} event is established by setting the {{domxref("RTCDataChannel.bufferedamountlow_event", "onbufferedamountlow")}} property to a function which should send more data into the buffer by calling {{domxref("RTCDataChannel.send", "send()")}}. ```js const dc = peerConnection.createDataChannel("File Transfer"); dc.bufferedAmountLowThreshold = 65535; dc.onbufferedamountlow = () => { /* use send() to queue more data to be sent */ }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - [Using WebRTC data channels](/en-US/docs/Web/API/WebRTC_API/Using_data_channels) - {{domxref("RTCDataChannel")}} - {{domxref("RTCDataChannel.bufferedAmount")}} - {{DOMxRef("RTCDataChannel.bufferedamountlow_event", "bufferedamountlow")}} event
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/open_event/index.md
--- title: "RTCDataChannel: open event" short-title: open slug: Web/API/RTCDataChannel/open_event page-type: web-api-event browser-compat: api.RTCDataChannel.open_event --- {{APIRef("WebRTC")}} The WebRTC **`open`** event is sent to an {{domxref("RTCDataChannel")}} object's `onopen` event handler when the underlying transport used to send and receive the data channel's messages is opened or reopened. 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("open", (event) => {}); onopen = (event) => {}; ``` ## Event type An {{domxref("RTCDataChannelEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("RTCDataChannelEvent")}} ## Event properties _Also inherits properties from its parent interface, {{DOMxRef("Event")}}._ - {{DOMxRef("RTCDataChannelEvent.channel", "channel")}} {{ReadOnlyInline}} - : Returns the {{domxref("RTCDataChannel")}} associated with the event. ## Examples This example adds to the {{domxref("RTCDataChannel")}} `dc` a handler for the `open` event that adjusts the user interface to indicate that a chat window is ready to be used after a connection has been established. It enables the message input box and send button as well as enabling the disconnect button and disabling the connect button. Finally, the message input box is focused so the user can immediately begin to type. ```js dc.addEventListener( "open", (ev) => { messageInputBox.disabled = false; sendMessageButton.disabled = false; disconnectButton.disabled = false; connectButton.disabled = true; messageInputBox.focus(); }, false, ); ``` This can also be done by directly setting the value of the channel's `onopen` event handler property. ```js dc.onopen = (ev) => { messageInputBox.disabled = false; sendMessageButton.disabled = false; disconnectButton.disabled = false; connectButton.disabled = true; messageInputBox.focus(); }; ``` ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - [A simple RTCDataChannel example](/en-US/docs/Web/API/WebRTC_API/Simple_RTCDataChannel_sample) - Related events: {{domxref("RTCDataChannel.message_event", "message")}}, {{domxref("RTCDataChannel.close_event", "close")}}, and {{domxref("RTCDataChannel.error_event", "error")}}
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/maxretransmits/index.md
--- title: "RTCDataChannel: maxRetransmits property" short-title: maxRetransmits slug: Web/API/RTCDataChannel/maxRetransmits page-type: web-api-instance-property browser-compat: api.RTCDataChannel.maxRetransmits --- {{APIRef("WebRTC")}} The read-only `RTCDataChannel` property **`maxRetransmits`** returns the maximum number of times the browser should try to retransmit a message before giving up, as set when the data channel was created, or `null`, which indicates that there is no maximum. This can only be set when the {{domxref("RTCDataChannel")}} is created by calling {{domxref("RTCPeerConnection.createDataChannel()")}}, using the `maxRetransmits` field in the specified `options`. ## Value The maximum number of times the browser will try to retransmit a message before giving up, or `null` if not set when {{domxref("RTCPeerConnection.createDataChannel()")}} was called. The default is `null`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCDataChannel")}} - {{domxref("RTCDataChannel.maxPacketLifetime")}} - {{domxref("RTCPeerConnection.createDataChannel()")}}
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/bufferedamountlow_event/index.md
--- title: "RTCDataChannel: bufferedamountlow event" short-title: bufferedamountlow slug: Web/API/RTCDataChannel/bufferedamountlow_event page-type: web-api-event browser-compat: api.RTCDataChannel.bufferedamountlow_event --- {{APIRef("WebRTC")}} A **`bufferedamountlow`** event is sent to an {{domxref("RTCDataChannel")}} when the number of bytes currently in the outbound data transfer buffer falls below the threshold specified in {{domxref("RTCDataChannel.bufferedAmountLowThreshold", "bufferedAmountLowThreshold")}}. `bufferedamountlow` events aren't sent if `bufferedAmountLowThreshold` is 0. 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("bufferedamountlow", (event) => {}); onbufferedamountlow = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples This example sets up a handler for `bufferedamountlow` to request more data any time the data channel's buffer falls below the number of bytes specified by {{domxref("RTCDataChannel.bufferedAmountLowThreshold", "bufferedAmountLowThreshold")}}, which we have set to 65536. In other words, we'll try to keep at least 64kB of data in the buffer, reading 64kB at a time from the source. ```js let pc = new RTCPeerConnection(); let dc = pc.createDataChannel("SendFile"); // source data object let source = (dc.bufferedAmountLowThreshold = 65536); pc.addEventListener( "bufferedamountlow", (ev) => { if (source.position <= source.length) { dc.send(source.readFile(65536)); } }, false, ); ``` After creating the `RTCPeerConnection`, this calls {{domxref("RTCPeerConnection.createDataChannel()")}} to create the data channel. Then a listener is created for `bufferedamountlow` to refill the incoming data buffer any time its contents fall below 65536 bytes. You can also set up a listener for `bufferedamountlow` using its event handler property, {{domxref("RTCDataChannel.bufferedamountlow_event", "onbufferedamountlow")}}: ```js pc.onbufferedamountlow = (ev) => { if (source.position <= source.length) { dc.send(source.readFile(65536)); } }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCDataChannel")}} - {{domxref("RTCDataChannel.bufferedAmountLowThreshold")}}
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/send/index.md
--- title: "RTCDataChannel: send() method" short-title: send() slug: Web/API/RTCDataChannel/send page-type: web-api-instance-method browser-compat: api.RTCDataChannel.send --- {{APIRef("WebRTC")}} The **`send()`** method of the {{domxref("RTCDataChannel")}} interface sends data across the data channel to the remote peer. This can be done any time except during the initial process of creating the underlying transport channel. Data sent before connecting is buffered if possible (or an error occurs if it's not possible), and is also buffered if sent while the connection is closing or closed. > **Note:** Different browsers have different limitations on the size of the message you can > send. Specifications exist to define how to automatically fragment large messages, but > not all browsers implement them, and those that do have various additional > restrictions. This will get less complicated over time, but for now, if you have > questions, see [Understanding message size limits](/en-US/docs/Web/API/WebRTC_API/Using_data_channels#understanding_message_size_limits). ## Syntax ```js-nolint send(data) ``` ### Parameters - `data` - : The data to transmit across the connection. This may be a string, a {{domxref("Blob")}}, an {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}} or a {{jsxref("DataView")}} object. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown when the data channel has not finished establishing its own connection (that is, its {{domxref("RTCDataChannel.readyState", "readyState")}} is `connecting`). The data channel must establish its own connection because it uses a transport channel separate from that of the media content. This error occurs without sending or buffering the `data`. - `NetworkError` {{domxref("DOMException")}} - : Thrown when the specified `data` would need to be buffered, and there isn't room for it in the buffer. In this scenario, the underlying transport is immediately closed. - {{jsxref("TypeError")}} - : Thrown if the specified `data` is too large for the other peer to receive. Since there are multiple techniques for breaking up large data into smaller pieces for transfer, it's possible to encounter scenarios in which the other peer does not support the same ones. For example, if one peer is a modern browser that supports using the `EOR` (End of Record) flag to indicate when a received message is the last piece of a multi-part object sent using `send()`. For more information about message size restrictions, see [Understanding message size limits](/en-US/docs/Web/API/WebRTC_API/Using_data_channels#understanding_message_size_limits). ## Examples In this example, a routine called `sendMessage()` is created; it accepts an object as input and sends to the remote peer, over the {{domxref("RTCDataChannel")}}, a JSON string with the specified object and a timestamp. ```js const pc = new RTCPeerConnection(); const dc = pc.createDataChannel("BackChannel"); function sendMessage(msg) { const obj = { message: msg, timestamp: new Date(), }; dc.send(JSON.stringify(obj)); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCDataChannel")}} - {{domxref("RTCDataChannel.readyState")}} - {{DOMxRef("RTCDataChannel.close_event", "close")}} event
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/close_event/index.md
--- title: "RTCDataChannel: close event" short-title: close slug: Web/API/RTCDataChannel/close_event page-type: web-api-event browser-compat: api.RTCDataChannel.close_event --- {{APIRef("WebRTC")}} The **`close`** event is sent to the {{domxref("RTCDataChannel.close_event", "onclose")}} event handler on an {{domxref("RTCDataChannel")}} instance when the data transport for the data channel has closed. Before any further data can be transferred using `RTCDataChannel`, a new 'RTCDataChannel' instance must be created. 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("close", (event) => {}); onclose = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples This example sets up a handler for the `close` event for the {{domxref("RTCDataChannel")}} named `dc`; its responsibility in this example is to update user interface elements to reflect that there is no longer an ongoing call, and to allow a new call to be started. ```js dc.addEventListener( "close", (ev) => { messageInputBox.disabled = true; sendButton.disabled = true; connectButton.disabled = false; disconnectButton.disabled = true; }, false, ); ``` All this code does in response to receiving the `close` event is to disable an input box and its "Send" button, and to enable the button used to start a call (while disabling the one that ends a call). You can also use the {{domxref("RTCDataChannel.close_event", "onclose")}} event handler property to set a handler for `close` events: ```js dc.onclose = (ev) => { messageInputBox.disabled = true; sendButton.disabled = true; connectButton.disabled = false; disconnectButton.disabled = true; }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - [A simple RTCDataChannel example](/en-US/docs/Web/API/WebRTC_API/Simple_RTCDataChannel_sample) - Related events: {{domxref("RTCDataChannel.open_event", "open")}}, {{domxref("RTCDataChannel.message_event", "message")}}, and {{domxref("RTCDataChannel.error_event", "error")}}
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/bufferedamount/index.md
--- title: "RTCDataChannel: bufferedAmount property" short-title: bufferedAmount slug: Web/API/RTCDataChannel/bufferedAmount page-type: web-api-instance-property browser-compat: api.RTCDataChannel.bufferedAmount --- {{APIRef("WebRTC")}} The read-only `RTCDataChannel` property **`bufferedAmount`** returns the number of bytes of data currently queued to be sent over the data channel. The queue may build up as a result of calls to the {{domxref("RTCDataChannel.send", "send()")}} method. This only includes data buffered by the user agent itself; it doesn't include any framing overhead or buffering done by the operating system or network hardware. The user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event loop or truly asynchronously. As messages are actually sent, this value is reduced accordingly. > **Note:** Closing the data channel doesn't reset this count, even though the user agent purges > the queued messages. However, even after closing the channel, attempts to send > messages continue to add to the `bufferedAmount` value, even though the > messages are neither sent nor buffered. Whenever this value decreases to fall to or below the value specified in the {{domxref("RTCDataChannel.bufferedAmountLowThreshold", "bufferedAmountLowThreshold")}} property, the user agent fires the {{DOMxRef("RTCDataChannel.bufferedamountlow_event", "bufferedamountlow")}} event. This event may be used, for example, to implement code which queues more messages to be sent whenever there's room to buffer them. ## Value The number of bytes of data currently queued to be sent over the data channel but have not yet been sent. ## Example The snippet below includes a function which changes the contents of a block with the ID "bufferSize" to a string indicating the number of bytes currently buffered on an {{domxref("RTCDataChannel")}}. ```js const dc = peerConnection.createDataChannel("File Transfer"); // … function showBufferedAmount(channel) { const el = document.getElementById("bufferSize"); el.innerText = `${channel.bufferedAmount} bytes`; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - [Using WebRTC data channels](/en-US/docs/Web/API/WebRTC_API/Using_data_channels) - {{domxref("RTCDataChannel")}} - {{domxref("RTCDataChannel.bufferedAmountLowThreshold")}} - {{DOMxRef("RTCDataChannel.bufferedamountlow_event", "bufferedamountlow")}} event
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/id/index.md
--- title: "RTCDataChannel: id property" short-title: id slug: Web/API/RTCDataChannel/id page-type: web-api-instance-property browser-compat: api.RTCDataChannel.id --- {{APIRef("WebRTC")}} The read-only `RTCDataChannel` property **`id`** returns an ID number (between 0 and 65,534) which uniquely identifies the {{domxref("RTCDataChannel")}}. This ID is set at the time the data channel is created, either by the user agent (if {{domxref("RTCDataChannel.negotiated")}} is `false`) or by the site or app script (if `negotiated` is `true`). Each {{domxref("RTCPeerConnection")}} can therefore have up to a theoretical maximum of 65,534 data channels on it, although the actual maximum may vary from browser to browser. ## Value An `unsigned short` value (that is, an integer between 0 and 65,535) which uniquely identifies the data channel. While the {{domxref("RTCDataChannel.label", "label")}} property doesn't have to be unique, this ID number is guaranteed to be unique among all data channels. Additionally, known implementations of WebRTC use the same ID on both peers. A unique ID makes it easier for your code to do its own out-of-band data channel-related signaling. This can be also useful for logging and debugging purposes. ## Example ```js const pc = new RTCPeerConnection(); const dc = pc.createDataChannel("my channel"); console.log(`Channel id: ${dc.id}`); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCDataChannel")}} - {{domxref("RTCPeerConnection.createDataChannel()")}}
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/readystate/index.md
--- title: "RTCDataChannel: readyState property" short-title: readyState slug: Web/API/RTCDataChannel/readyState page-type: web-api-instance-property browser-compat: api.RTCDataChannel.readyState --- {{APIRef("WebRTC")}} The read-only `RTCDataChannel` property **`readyState`** returns a string which indicates the state of the data channel's underlying data connection. ## Values A string indicating the current state of the underlying data transport, which is one of the following values: - `connecting` - : The user agent (browser) is in the process of creating the underlying data transport; this is the state of a new {{domxref("RTCDataChannel")}} after being created by {{domxref("RTCPeerConnection.createDataChannel()")}}, on the peer which started the connection process. - `open` - : The underlying data transport has been established and data can be transferred bidirectionally across it. This is the default state of a new {{domxref("RTCDataChannel")}} created by the WebRTC layer when the remote peer created the channel and delivered it to the site or app in a {{DOMxRef("RTCPeerConnection.datachannel_event", "datachannel")}} event. - `closing` - : The process of closing the underlying data transport has begun. It is no longer possible to queue new messages to be sent, but previously queued messages may still be send or received before entering the `closed` state. - `closed` - : The underlying data transport has closed, or the attempt to make the connection failed. ## Example ```js const dataChannel = peerConnection.createDataChannel("File Transfer"); const sendQueue = []; function sendMessage(msg) { switch (dataChannel.readyState) { case "connecting": console.log(`Connection not open; queueing: ${msg}`); sendQueue.push(msg); break; case "open": sendQueue.forEach((msg) => dataChannel.send(msg)); break; case "closing": console.log(`Attempted to send message while closing: ${msg}`); break; case "closed": console.log("Error! Attempt to send while connection closed."); break; } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - [Using WebRTC data channels](/en-US/docs/Web/API/WebRTC_API/Using_data_channels) - {{domxref("RTCDataChannel")}} - {{domxref("RTCPeerConnection.createDataChannel()")}}
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/closing_event/index.md
--- title: "RTCDataChannel: closing event" short-title: closing slug: Web/API/RTCDataChannel/closing_event page-type: web-api-event browser-compat: api.RTCDataChannel.closing_event --- {{APIRef("WebRTC")}} The **`closing`** event is sent to an {{domxref("RTCDataChannel")}} just before the channel begins the process of shutting down its underlying data transport. 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("closing", (event) => {}); onclosing = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Description While the `closing` event is sent to the channel just before beginning to close the channel's data transport, the {{domxref("RTCDataChannel.close_event", "close")}} event is sent once the closing process is complete. ## Examples This example updates a connection status interface when the `closing` event arrives. First, an example using {{domxref("EventTarget.addEventListener", "addEventListener()")}}: ```js dataChannel.addEventListener("closing", (ev) => { myConnectionStatus.icon = closingIcon; myConnectionStatus.text = "Connection closing"; }); ``` You can also set the {{domxref("RTCDataChannel.closing_event", "onclosing")}} event handler property directly: ```js pc.onclosing = (ev) => { myConnectionStatus.icon = closingIcon; myConnectionStatus.text = "Connection closing"; }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - [Signaling and video calling](/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling)
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/message_event/index.md
--- title: "RTCDataChannel: message event" short-title: message slug: Web/API/RTCDataChannel/message_event page-type: web-api-event browser-compat: api.RTCDataChannel.message_event --- {{APIRef("WebRTC")}} The WebRTC **`message`** event is sent to the {{domxref("RTCDataChannel.message_event", "onmessage")}} event handler on an {{domxref("RTCDataChannel")}} object when a message has been received from the remote peer. > **Note:** The `message` event uses as its event object type the {{domxref("MessageEvent")}} interface defined by the HTML specification. 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 A {{domxref("MessageEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("MessageEvent")}} ## Event properties _Also inherits properties from its parent interface, {{domxref("Event")}}._ - {{domxref("MessageEvent.data")}} {{ReadOnlyInline}} - : The data sent by the message emitter. - {{domxref("MessageEvent.origin")}} {{ReadOnlyInline}} - : A string representing the origin of the message emitter. - {{domxref("MessageEvent.lastEventId")}} {{ReadOnlyInline}} - : A string representing a unique ID for the event. - {{domxref("MessageEvent.source")}} {{ReadOnlyInline}} - : A reference to the message emitter, one of {{glossary("WindowProxy")}}, {{domxref("MessagePort")}}, or {{domxref("ServiceWorker")}}. - {{domxref("MessageEvent.ports")}} {{ReadOnlyInline}} - : An array of {{domxref("MessagePort")}} objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker). ## Examples For a given {{domxref("RTCDataChannel")}}, `dc`, created for a peer connection using its {{domxref("RTCPeerConnection.createDataChannel", "createDataChannel()")}} method, this code sets up a handler for incoming messages and acts on them by adding the data contained within the message to the current document as a new {{HTMLElement("p")}} (paragraph) element. ```js dc.addEventListener( "message", (event) => { let newParagraph = document.createElement("p"); let textNode = document.createTextNode(event.data); newParagraph.appendChild(textNode); document.body.appendChild(newParagraph); }, false, ); ``` Lines 2-4 create the new paragraph element and add the message data to it as a new text node. Line 6 appends the new paragraph to the end of the document's body. You can also use an `RTCDataChannel` object's {{domxref("RTCDataChannel.message_event", "onmessage")}} event handler property to set the event handler: ```js dc.onmessage = (event) => { let newParagraph = document.createElement("p"); let textNode = document.createTextNode(event.data); newParagraph.appendChild(textNode); document.body.appendChild(newParagraph); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - [A simple RTCDataChannel example](/en-US/docs/Web/API/WebRTC_API/Simple_RTCDataChannel_sample) - Related events: {{domxref("RTCDataChannel.open_event", "open")}}, {{domxref("RTCDataChannel.close_event", "close")}}, and {{domxref("RTCDataChannel.error_event", "error")}} - {{domxref("RTCDataChannel.send()")}}
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/label/index.md
--- title: "RTCDataChannel: label property" short-title: label slug: Web/API/RTCDataChannel/label page-type: web-api-instance-property browser-compat: api.RTCDataChannel.label --- {{APIRef("WebRTC")}} The read-only `RTCDataChannel` property **`label`** returns a string containing a name describing the data channel. These labels are not required to be unique. You may use the label as you wish; you could use it to identify all the channels that are being used for the same purpose, by giving them all the same name. Or you could give each channel a unique label for tracking purposes. It's entirely up to the design decisions made when building your site or app. A unique ID can be found in the {{domxref("RTCDataChannel.id", "id")}} property. > **Note:** A data channel's label is set when the channel is created by calling > {{domxref("RTCPeerConnection.createDataChannel()")}}. It cannot be changed after that. ## Value A string identifier assigned by the website or app when the data channel was created, as specified when {{domxref("RTCPeerConnection.createDataChannel()")}} was called to create the channel. ## Example This sample creates a data channel on an {{domxref("RTCPeerConnection")}}, then, some time later, sets the content of a UI element to display the channel's name. ```js const pc = new RTCPeerConnection(); const dc = pc.createDataChannel("my channel"); // … document.getElementById("channel-name").innerHTML = `<span class='channelName'>${dc.label}</span>`; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCDataChannel")}} - {{domxref("RTCDataChannel.id")}} - {{domxref("RTCPeerConnection.createDataChannel()")}}
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/protocol/index.md
--- title: "RTCDataChannel: protocol property" short-title: protocol slug: Web/API/RTCDataChannel/protocol page-type: web-api-instance-property browser-compat: api.RTCDataChannel.protocol --- {{APIRef("WebRTC")}} The read-only `RTCDataChannel` property **`protocol`** returns a string containing the name of the subprotocol in use. If no protocol was specified when the data channel was created, then this property's value is the empty string (`""`). > **Note:** The permitted values of this property are defined by the website or app using the > data channel. The ability for each channel to have a defined subprotocol lets your app, for example, use JSON objects as messages on one channel while another channel is plaintext and another is raw binary or even some other format. ## Value A string identifying the app-defined subprotocol being used for exchanging data on the channel. If none has been established, this is an empty string (""). ## Example ```js const pc = new RTCPeerConnection(); const dc = pc.createDataChannel("my channel", { protocol: "json", }); function handleChannelMessage(dataChannel, msg) { switch (dataChannel.protocol) { case "json": /* process JSON data */ break; case "raw": /* process raw binary data */ break; } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCDataChannel")}} - {{domxref("RTCPeerConnection.createDataChannel()")}}
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/maxpacketlifetime/index.md
--- title: "RTCDataChannel: maxPacketLifeTime property" short-title: maxPacketLifeTime slug: Web/API/RTCDataChannel/maxPacketLifeTime page-type: web-api-instance-property browser-compat: api.RTCDataChannel.maxPacketLifeTime --- {{APIRef("WebRTC")}} The read-only `RTCDataChannel` property **`maxPacketLifeTime`** returns the amount of time, in milliseconds, the browser is allowed to take to attempt to transmit a message, as set when the data channel was created, or `null`. This limits how long the browser can continue to attempt to transmit and retransmit the message before giving up. ## Value The number of milliseconds over which the browser may continue to attempt to transmit the message until it either succeeds or gives up. If not set when {{domxref("RTCPeerConnection.createDataChannel()")}} was called to create the data channel, this value is `null`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCDataChannel")}} - {{domxref("RTCDataChannel.maxRetransmits")}} - {{domxref("RTCPeerConnection.createDataChannel()")}}
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/negotiated/index.md
--- title: "RTCDataChannel: negotiated property" short-title: negotiated slug: Web/API/RTCDataChannel/negotiated page-type: web-api-instance-property browser-compat: api.RTCDataChannel.negotiated --- {{APIRef("WebRTC")}} The read-only `RTCDataChannel` property **`negotiated`** indicates whether the {{domxref("RTCDataChannel")}}'s connection was negotiated by the Web app (`true`) or by the WebRTC layer (`false`). **The default is `false`.** See [Creating a data channel](/en-US/docs/Web/API/WebRTC_API/Using_data_channels#creating_a_data_channel) for further information about this property. ## Value `true` if the {{domxref("RTCDataChannel")}}'s connection was negotiated by the Web app itself; `false` if the negotiation was handled by the WebRTC layer. The default is `false`. ## Example The code snippet below checks the value of `negotiated`; if it's `true`, a function called `shutdownRemoteChannel()` is called with the channel's {{domxref("RTCDataChannel.id", "id")}}; presumably this would be implemented to transmit a shutdown signal to the remote peer prior to terminating the connection. ```js if (dataChannel.negotiated) { shutdownRemoteChannel(dataChannel.id); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - [Using WebRTC data channels](/en-US/docs/Web/API/WebRTC_API/Using_data_channels) - {{domxref("RTCDataChannel")}} - {{domxref("RTCPeerConnection.createDataChannel()")}}
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/close/index.md
--- title: "RTCDataChannel: close() method" short-title: close() slug: Web/API/RTCDataChannel/close page-type: web-api-instance-method browser-compat: api.RTCDataChannel.close --- {{APIRef("WebRTC")}} The **`RTCDataChannel.close()`** method closes the {{domxref("RTCDataChannel")}}. Either peer is permitted to call this method to initiate closure of the channel. Closure of the data channel is not instantaneous. Most of the process of closing the connection is handled asynchronously; you can detect when the channel has finished closing by watching for a {{DOMxRef("RTCDataChannel.close_event", "close")}} event on the data channel. The sequence of events which occurs in response to this method being called: 1. {{domxref("RTCDataChannel.readyState")}} is set to `closing`. 2. A background task is established to handle the remainder of the steps below, and `close()` returns to the caller. 3. The transport layer deals with any buffered messages; the protocol layer decides whether to send them or discard them. 4. The underlying data transport is closed. 5. The {{domxref("RTCDataChannel.readyState")}} property is set to `closed`. 6. If the transport was closed with an error, the `RTCDataChannel` is sent an {{DOMxRef("RTCDataChannel.error_event", "error")}} event with its {{DOMxRef("DOMException.name", "name")}} set to `NetworkError`. 7. A {{domxref("RTCDataChannel.close_event", "close")}} event is sent to the channel. ## Syntax ```js-nolint close() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Return value `undefined`. ## Examples ```js const pc = new RTCPeerConnection(); const dc = pc.createDataChannel("my channel"); dc.onmessage = (event) => { console.log(`received: ${event.data}`); dc.close(); // We decided to close after the first received message }; dc.onopen = () => { console.log("datachannel open"); }; dc.onclose = () => { console.log("datachannel close"); }; // Now negotiate the connection and so forth… ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCDataChannel")}} - {{domxref("RTCDataChannel.readyState")}} - {{DOMxRef("RTCDataChannel.close_event", "close")}} event
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/error_event/index.md
--- title: "RTCDataChannel: error event" short-title: error slug: Web/API/RTCDataChannel/error_event page-type: web-api-event browser-compat: api.RTCDataChannel.error_event --- {{APIRef("WebRTC")}} A WebRTC {{domxref("RTCDataChannel.error_event", "error")}} event is sent to an {{domxref("RTCDataChannel")}} object's `onerror` event handler when an error occurs on the data channel. The {{domxref("RTCErrorEvent")}} object provides details about the error that occurred; see that article for details. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("error", (event) => {}); onerror = (event) => {}; ``` ## Event type An {{domxref("RTCErrorEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("RTCErrorEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("RTCErrorEvent.error", "error")}} {{ReadOnlyInline}} - : An {{domxref("RTCError")}} object specifying the error which occurred; this object includes the type of error that occurred, and information about where the error occurred (such as which line number in the {{Glossary("SDP")}} or what {{Glossary("SCTP")}} cause code was at issue). ## Examples ```js // Strings for each of the SCTP cause codes found in RFC // 4960, section 3.3.10: // https://datatracker.ietf.org/doc/html/rfc4960#section-3.3.10 const sctpCauseCodes = [ "No SCTP error", "Invalid stream identifier", "Missing mandatory parameter", "Stale cookie error", "Sender is out of resource (i.e., memory)", "Unable to resolve address", "Unrecognized SCTP chunk type received", "Invalid mandatory parameter", "Unrecognized parameters", "No user data (SCTP DATA chunk has no data)", "Cookie received while shutting down", "Restart of an association with new addresses", "User-initiated abort", "Protocol violation", ]; dc.addEventListener( "error", (ev) => { const err = ev.error; console.error("WebRTC error: ", err.message); // Handle specific error detail types switch (err.errorDetail) { case "sdp-syntax-error": console.error(" SDP syntax error in line ", err.sdpLineNumber); break; case "idp-load-failure": console.error( " Identity provider load failure: HTTP error ", err.httpRequestStatusCode, ); break; case "sctp-failure": if (err.sctpCauseCode < sctpCauseCodes.length) { console.error(" SCTP failure: ", err.sctpCauseCode); } else { console.error(" Unknown SCTP error"); } break; case "dtls-failure": if (err.receivedAlert) { console.error(" Received DLTS failure alert: ", err.receivedAlert); } if (err.sentAlert) { console.error(" Sent DLTS failure alert: ", err.receivedAlert); } break; } // Add source file name and line information console.error( " Error in file ", err.filename, " at line ", err.lineNumber, ", column ", err.columnNumber, ); }, false, ); ``` The received event provides details in an {{domxref("RTCError")}} object called {{domxref("RTCErrorEvent.error", "error")}}; `RTCError` is an extension of the {{domxref("DOMException")}} interface. The error's {{domxref("DOMException.name", "name")}} is `RTCError` and the {{domxref("DOMException.message", "message")}} is an error string specified by the WebRTC layer. Error information is output to the console using {{domxref("console/error_static", "console.error()")}}. The `message` string is always output, as is information about the source file's name, line number, and column number at which the error occurred. In addition, however, depending on the value of {{domxref("RTCError.errorDetail", "errorDetail")}}, additional information may be output. Each error type has a different set of information output. For example, an SDP syntax error displays the line number of the error within the SDP, and an SCTP error displays a message corresponding to the SCTP cause code. Other error types similarly output appropriate information. You can also set up an event handler for `error` events using the `RTCDataChannel` interface's {{domxref("RTCDataChannel.error_event", "onerror")}} event handler property: ```js dc.onerror = (ev) => { const err = ev.error; // … }; ``` > **Note:** Since `RTCError` is not one of the legacy errors, the value of {{domxref("DOMException.code", "RTCError.code")}} is always 0. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - [A simple RTCDataChannel example](/en-US/docs/Web/API/WebRTC_API/Simple_RTCDataChannel_sample) - Related events: {{domxref("RTCDataChannel.open_event", "open")}}, {{domxref("RTCDataChannel.message_event", "message")}}, and {{domxref("RTCDataChannel.close_event", "close")}}
0
data/mdn-content/files/en-us/web/api/rtcdatachannel
data/mdn-content/files/en-us/web/api/rtcdatachannel/ordered/index.md
--- title: "RTCDataChannel: ordered property" short-title: ordered slug: Web/API/RTCDataChannel/ordered page-type: web-api-instance-property browser-compat: api.RTCDataChannel.ordered --- {{APIRef("WebRTC")}} The read-only `RTCDataChannel` property **`ordered`** indicates whether or not the data channel guarantees in-order delivery of messages; the default is `true`, which indicates that the data channel is indeed ordered. This is set when the {{domxref("RTCDataChannel")}} is created, by setting the `ordered` property on the object passed as {{domxref("RTCPeerConnection.createDataChannel()")}}'s `options` parameter. ## Value A boolean value which is `true` if in-order delivery is guaranteed and is otherwise `false`. ## Example ```js const pc = new RTCPeerConnection(); const dc = pc.createDataChannel("my channel"); if (!dc.ordered) { // Handle unordered messaging } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCDataChannel")}} - {{domxref("RTCPeerConnection.createDataChannel()")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/gpuadapter/index.md
--- title: GPUAdapter slug: Web/API/GPUAdapter page-type: web-api-interface status: - experimental browser-compat: api.GPUAdapter --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`GPUAdapter`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} represents a GPU adapter. From this you can request a {{domxref("GPUDevice")}}, adapter info, features, and limits. A `GPUAdapter` object is requested using the {{domxref("GPU.requestAdapter()")}} method. {{InheritanceDiagram}} ## Instance properties - {{domxref("GPUAdapter.features", "features")}} {{Experimental_Inline}} {{ReadOnlyInline}} - : A {{domxref("GPUSupportedFeatures")}} object that describes additional functionality supported by the adapter. - {{domxref("GPUAdapter.isFallbackAdapter", "isFallbackAdapter")}} {{Experimental_Inline}} {{ReadOnlyInline}} - : A boolean value. Returns `true` if the adapter is a [fallback adapter](/en-US/docs/Web/API/GPU/requestAdapter#fallback_adapters), and `false` if not. - {{domxref("GPUAdapter.limits", "limits")}} {{Experimental_Inline}} {{ReadOnlyInline}} - : A {{domxref("GPUSupportedLimits")}} object that describes the limits supported by the adapter. ## Instance methods - {{domxref("GPUAdapter.requestAdapterInfo", "requestAdapterInfo()")}} {{Experimental_Inline}} - : Returns a {{jsxref("Promise")}} that fulfills with a {{domxref("GPUAdapterInfo")}} object containing identifying information about an adapter. - {{domxref("GPUAdapter.requestDevice", "requestDevice()")}} {{Experimental_Inline}} - : Returns a {{jsxref("Promise")}} that fulfills with a {{domxref("GPUDevice")}} object, which is the primary interface for communicating with the GPU. ## Examples ```js async function init() { if (!navigator.gpu) { throw Error("WebGPU not supported."); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw Error("Couldn't request WebGPU adapter."); } const device = await adapter.requestDevice(); //... } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpuadapter
data/mdn-content/files/en-us/web/api/gpuadapter/limits/index.md
--- title: "GPUAdapter: limits property" short-title: limits slug: Web/API/GPUAdapter/limits page-type: web-api-instance-property status: - experimental browser-compat: api.GPUAdapter.limits --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`limits`** read-only property of the {{domxref("GPUAdapter")}} interface returns a {{domxref("GPUSupportedLimits")}} object that describes the limits supported by the adapter. You should note that, rather than reporting the exact limits of each GPU, browsers will likely report different tier values of different limits to reduce the unique information available to drive-by fingerprinting. For example, the tiers of a certain limit might be 2048, 8192, and 32768. If your GPU's actual limit is 16384, the browser will still report 8192. Given that different browsers will handle this differently and the tier values may change over time, it is hard to provide an accurate account of what limit values to expect — thorough testing is advised. ## Value A {{domxref("GPUSupportedLimits")}} object instance. ## Examples In the following code we query the `GPUAdapter.limits` value of `maxBindGroups` to see if it is equal to or greater than 6. Our theoretical example app ideally needs 6 bind groups, so if the returned value is >= 6, we add a maximum limit of 6 to the `requiredLimits` object, and request a device with that limit requirement using {{domxref("GPUAdapter.requestDevice()")}}: ```js async function init() { if (!navigator.gpu) { throw Error("WebGPU not supported."); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw Error("Couldn't request WebGPU adapter."); } const requiredLimits = {}; // App ideally needs 6 bind groups, so we'll try to request what the app needs if (adapter.limits.maxBindGroups >= 6) { requiredLimits.maxBindGroups = 6; } const device = await adapter.requestDevice({ requiredLimits, }); // ... } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpuadapter
data/mdn-content/files/en-us/web/api/gpuadapter/features/index.md
--- title: "GPUAdapter: features property" short-title: features slug: Web/API/GPUAdapter/features page-type: web-api-instance-property status: - experimental browser-compat: api.GPUAdapter.features --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`features`** read-only property of the {{domxref("GPUAdapter")}} interface returns a {{domxref("GPUSupportedFeatures")}} object that describes additional functionality supported by the adapter. You should note that not all features will be available to WebGPU in all browsers that support it, even if the features are supported by the underlying hardware. This could be due to constraints in the underlying system, browser, or adapter. For example: - The underlying system might not be able to guarantee exposure of a feature in a way that is compatible with a certain browser. - The browser vendor might not have found a secure way to implement support for that feature, or might just not have gotten round to it yet. If you are hoping to take advantage of a specific additional feature in a WebGPU app, thorough testing is advised. ## Value A {{domxref("GPUSupportedFeatures")}} object instance. This is a [setlike](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) object. ## Examples In the following code we check whether a {{domxref("GPUAdapter")}} has the `texture-compression-astc` feature available. If so, we push it into the array of `requiredFeatures`, and request a device with that feature requirement using {{domxref("GPUAdapter.requestDevice()")}} ```js async function init() { if (!navigator.gpu) { throw Error("WebGPU not supported."); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw Error("Couldn't request WebGPU adapter."); } const requiredFeatures = []; if (adapter.features.has("texture-compression-astc")) { requiredFeatures.push("texture-compression-astc"); } const device = await adapter.requestDevice({ requiredFeatures, }); // ... } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpuadapter
data/mdn-content/files/en-us/web/api/gpuadapter/requestadapterinfo/index.md
--- title: "GPUAdapter: requestAdapterInfo() method" short-title: requestAdapterInfo() slug: Web/API/GPUAdapter/requestAdapterInfo page-type: web-api-instance-method status: - experimental browser-compat: api.GPUAdapter.requestAdapterInfo --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`requestAdapterInfo()`** method of the {{domxref("GPUAdapter")}} interface returns a {{jsxref("Promise")}} that fulfills with a {{domxref("GPUAdapterInfo")}} object containing identifying information about an adapter. The intention behind this method is to allow developers to request specific details about the user's GPU so that they can preemptively apply workarounds for GPU-specific bugs, or provide different codepaths to better suit different GPU architectures. Providing such information does present a security risk — it could be used for fingerprinting — therefore the information shared is to be kept at a minimum, and different browser vendors are likely to share different information types and granularities. > **Note:** The specification includes an `unmaskHints` parameter for `requestAdapterInfo()`, which is intended to mitigate the security risk mentioned above. Once it is supported, developers will be able to specify the values they really need to know, and users will be given a permission prompt asking them if they are OK to share this information when the method is invoked. Browser vendors are likely to share more useful information if it is guarded by a permissions prompt, as it makes the method a less viable target for fingerprinting. ## Syntax ```js-nolint requestAdapterInfo() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that fulfills with a {{domxref("GPUAdapterInfo")}} object instance. ## Examples ```js async function init() { if (!navigator.gpu) { throw Error("WebGPU not supported."); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw Error("Couldn't request WebGPU adapter."); } const adapterInfo = await adapter.requestAdapterInfo(); console.log(adapterInfo.vendor); console.log(adapterInfo.architecture); // ... } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpuadapter
data/mdn-content/files/en-us/web/api/gpuadapter/requestdevice/index.md
--- title: "GPUAdapter: requestDevice() method" short-title: requestDevice() slug: Web/API/GPUAdapter/requestDevice page-type: web-api-instance-method status: - experimental browser-compat: api.GPUAdapter.requestDevice --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`requestDevice()`** method of the {{domxref("GPUAdapter")}} interface returns a {{jsxref("Promise")}} that fulfills with a {{domxref("GPUDevice")}} object, which is the primary interface for communicating with the GPU. ## Syntax ```js-nolint requestDevice() requestDevice(descriptor) ``` ### Parameters - `descriptor` {{optional_inline}} - : An object containing the following properties: - `defaultQueue` {{optional_inline}} - : An object that provides information for the device's default {{domxref("GPUQueue")}} (as returned by {{domxref("GPUDevice.queue")}}). This object has a single property — `label` — which provides the default queue with a {{domxref("GPUQueue.label", "label")}} value. If no value is provided, this defaults to an empty object, and the default queue's label will be an empty string. - `label` {{optional_inline}} - : A string providing a label that can be used to identify the {{domxref("GPUDevice")}}, for example in {{domxref("GPUError")}} messages or console warnings. - `requiredFeatures` {{optional_inline}} - : An array of strings representing additional functionality that you want supported by the returned {{domxref("GPUDevice")}}. The `requestDevice()` call will fail if the `GPUAdapter` cannot provide these features. See {{domxref("GPUSupportedFeatures")}} for a full list of possible features. This defaults to an empty array if no value is provided. - `requiredLimits` {{optional_inline}} - : An object containing properties representing the limits that you want supported by the returned {{domxref("GPUDevice")}}. The `requestDevice()` call will fail if the `GPUAdapter` cannot provide these limits. Each key must be the name of a member of {{domxref("GPUSupportedLimits")}}. This defaults to an empty object if no value is provided. > **Note:** Not all features and limits will be available to WebGPU in all browsers that support it, even if they are supported by the underlying hardware. See the {{domxref("GPUAdapter.features", "features")}} and {{domxref("GPUAdapter.limits", "limits")}} pages for more information. ### Return value A {{jsxref("Promise")}} that fulfills with a {{domxref("GPUDevice")}} object instance. If you make a duplicate call, i.e. call `requestDevice()` on a {{domxref("GPUAdapter")}} that `requestDevice()` was already called on, the promise fulfills with a device that is immediately lost. You can then get information on how the device was lost via {{domxref("GPUDevice.lost")}}. ### Exceptions - `OperationError` {{domxref("DOMException")}} - : The promise rejects with an `OperationError` if the limits included in the `requiredLimits` property are not supported by the {{domxref("GPUAdapter")}}, either because they are not valid limits, or because their values are higher than the adapter's values for those limits. - `TypeError` {{domxref("DOMException")}} - : The promise rejects with a `TypeError` if the features included in the `requiredFeatures` property are not supported by the {{domxref("GPUAdapter")}}. ## Examples ### Basic example ```js async function init() { if (!navigator.gpu) { throw Error("WebGPU not supported."); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw Error("Couldn't request WebGPU adapter."); } const device = await adapter.requestDevice(); // ... } ``` ### Requesting specific features and limits In the following code we: 1. Check whether a {{domxref("GPUAdapter")}} has the `texture-compression-astc` feature available. If so, we push it into the array of `requiredFeatures`. 2. Query the `GPUAdapter.limits` value of `maxBindGroups` to see if it is equal to or greater than 6. Our theoretical example app ideally needs 6 bind groups, so if the returned value is >= 6, we add a maximum limit of 6 to the `requiredLimits` object. 3. Request a device with those feature and limit requirements, plus a `defaultQueue` label. ```js async function init() { if (!navigator.gpu) { throw Error("WebGPU not supported."); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw Error("Couldn't request WebGPU adapter."); } const requiredFeatures = []; if (adapter.features.has("texture-compression-astc")) { requiredFeatures.push("texture-compression-astc"); } const requiredLimits = {}; // App ideally needs 6 bind groups, so we'll try to request what the app needs if (adapter.limits.maxBindGroups >= 6) { requiredLimits.maxBindGroups = 6; } const device = await adapter.requestDevice({ defaultQueue: { label: "myqueue", }, requiredFeatures, requiredLimits, }); // ... } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpuadapter
data/mdn-content/files/en-us/web/api/gpuadapter/isfallbackadapter/index.md
--- title: "GPUAdapter: isFallbackAdapter property" short-title: isFallbackAdapter slug: Web/API/GPUAdapter/isFallbackAdapter page-type: web-api-instance-property status: - experimental browser-compat: api.GPUAdapter.isFallbackAdapter --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`isFallbackAdapter`** read-only property of the {{domxref("GPUAdapter")}} interface returns `true` if the adapter is a [fallback adapter](/en-US/docs/Web/API/GPU/requestAdapter#fallback_adapters), and `false` if not. ## Value A boolean. ## Examples ```js async function init() { if (!navigator.gpu) { throw Error('WebGPU not supported.'); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw Error('Couldn\'t request WebGPU adapter.'); } const fallback = adapter.isFallbackAdapter; console.log(fallback); // ... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmltimeelement/index.md
--- title: HTMLTimeElement slug: Web/API/HTMLTimeElement page-type: web-api-interface browser-compat: api.HTMLTimeElement --- {{ APIRef("HTML DOM") }} The **`HTMLTimeElement`** interface provides special properties (beyond the regular {{domxref("HTMLElement")}} interface it also has available to it by inheritance) for manipulating {{HTMLElement("time")}} elements. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLTimeElement.dateTime")}} - : A string that reflects the [`datetime`](/en-US/docs/Web/HTML/Element/time#datetime) HTML attribute, containing a machine-readable form of the element's date and time value. ## 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("time")}}.
0
data/mdn-content/files/en-us/web/api/htmltimeelement
data/mdn-content/files/en-us/web/api/htmltimeelement/datetime/index.md
--- title: "HTMLTimeElement: dateTime property" short-title: dateTime slug: Web/API/HTMLTimeElement/dateTime page-type: web-api-instance-property browser-compat: api.HTMLTimeElement.dateTime --- {{ APIRef("HTML DOM") }} The **`HTMLTimeElement.dateTime`** property is a string that reflects the [`datetime`](/en-US/docs/Web/HTML/Element/time#datetime) HTML attribute, containing a machine-readable form of the element's date and time value. The format of the string must follow one of the following HTML microsyntaxes: <table class="no-markdown"> <thead> <tr> <th scope="col">Microsyntax</th> <th scope="col">Description</th> <th scope="col">Examples</th> </tr> </thead> <tbody> <tr> <td>Valid month string</td> <td><em>YYYY</em><code>-</code><em>MM</em></td> <td><code>2011-11</code>, <code>2013-05</code></td> </tr> <tr> <td>Valid date string</td> <td><em>YYYY</em><code>-</code><em>MM</em><code>-</code><em>DD</em></td> <td><code>1887-12-01</code></td> </tr> <tr> <td>Valid yearless date string</td> <td><em>MM</em><code>-</code><em>DD</em></td> <td><code>11-12</code></td> </tr> <tr> <td>Valid time string</td> <td> <em>HH</em><code>:</code><em>MM</em><br /><em>HH</em><code>:</code ><em>MM</em><code>:</code><em>SS</em><br /><em>HH</em><code>:</code ><em>MM</em><code>:</code><em>SS</em><code>.</code><em>mmm</em> </td> <td> <code>23:59</code><br /><code>12:15:47</code><br /><code >12:15:52.998</code > </td> </tr> <tr> <td>Valid local date and time string</td> <td> <em>YYYY</em><code>-</code><em>MM</em><code>-</code><em>DD</em> <em>HH</em><code>:</code><em>MM</em><br /><em>YYYY</em><code>-</code ><em>MM</em><code>-</code><em>DD</em> <em>HH</em><code>:</code ><em>MM</em><code>:</code><em>SS</em><br /><em>YYYY</em><code>-</code ><em>MM</em><code>-</code><em>DD</em> <em>HH</em><code>:</code ><em>MM</em><code>:</code><em>SS</em><code>.</code><em>mmm</em><br /><em >YYYY</em ><code>-</code><em>MM</em><code>-</code><em>DD</em><code>T</code ><em>HH</em><code>:</code><em>MM</em><br /><em>YYYY</em><code>-</code ><em>MM</em><code>-</code><em>DD</em><code>T</code><em>HH</em ><code>:</code><em>MM</em><code>:</code><em>SS</em><br /><em>YYYY</em ><code>-</code><em>MM</em><code>-</code><em>DD</em><code>T</code ><em>HH</em><code>:</code><em>MM</em><code>:</code><em>SS</em ><code>.</code><em>mmm</em> </td> <td> <code >2013-12-25 11:12<br />1972-07-25 13:43:07<br />1941-03-15 07:06:23.678<br />2013-12-25T11:12<br />1972-07-25T13:43:07<br />1941-03-15T07:06:23.678</code > </td> </tr> <tr> <td>Valid time-zone offset string</td> <td> <code>Z</code><br /><code>+</code><em>HHMM</em><br /><code>+</code ><em>HH</em><code>:</code><em>MM</em><br /><code>-</code><em>HHMM</em ><br /><code>-</code><em>HH</em><code>:</code><em>MM</em> </td> <td> <code>Z<br />+0200<br />+04:30<br />-0300<br />-08:00</code> </td> </tr> <tr> <td>Valid global date and time string</td> <td> <em >Any combination of a valid local date and time string followed by a valid time-zone offset string</em > </td> <td> <code >2013-12-25 11:12+0200<br />1972-07-25 13:43:07+04:30<br />1941-03-15 07:06:23.678Z<br />2013-12-25T11:12-08:00</code > </td> </tr> <tr> <td>Valid week string</td> <td><em>YYYY</em><code>-W</code><em>WW</em></td> <td><code>2013-W46</code></td> </tr> <tr> <td>Four or more ASCII digits</td> <td><em>YYYY</em></td> <td><code>2013</code>, <code>0001</code></td> </tr> <tr> <td>Valid duration string</td> <td> <code>P</code><em>d</em><code>D</code><code>T</code><em>h</em ><code>H</code><em>m</em><code>M</code><em>s</em><code>S</code ><br /><code>P</code><em>d</em><code>D</code><code>T</code><em>h</em ><code>H</code><em>m</em><code>M</code><em>s</em><code>.</code>X<code >S</code ><br /><code>P</code><em>d</em><code>D</code><code>T</code><em>h</em ><code>H</code><em>m</em><code>M</code><em>s</em><code>.</code>XX<code >S</code ><br /><code>P</code><em>d</em><code>D</code><code>T</code><em>h</em ><code>H</code><em>m</em><code>M</code><em>s</em><code>.</code>XXX<code >S</code ><br /><code>P</code><code>T</code><em>h</em><code>H</code><em>m</em ><code>M</code><em>s</em><code>S</code><br /><code>P</code><code>T</code ><em>h</em><code>H</code><em>m</em><code>M</code><em>s</em ><code>.</code>X<code>S</code><br /><code>P</code><code>T</code ><em>h</em><code>H</code><em>m</em><code>M</code><em>s</em ><code>.</code>XX<code>S</code><br /><code>P</code><code>T</code ><em>h</em><code>H</code><em>m</em><code>M</code><em>s</em ><code>.</code>XXX<code>S</code><br /><em>w</em><code>w </code><em>d</em ><code>d </code><em>h</em><code>h </code><em>m</em><code>m </code ><em>s</em><code>s</code> </td> <td> <code >P12DT7H12M13S<br />P12DT7H12M13.3S<br />P12DT7H12M13.45S<br />P12DT7H12M13.455S<br />PT7H12M13S<br />PT7H12M13.2S<br />PT7H12M13.56S<br />PT7H12M13.999S<br />7d 5h 24m 13s</code > </td> </tr> </tbody> </table> ## Value A string. ## Examples ```js // Assumes there is <time id="t"> element in the HTML const t = document.getElementById("t"); t.dateTime = "6w 5h 34m 5s"; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{domxref("HTMLTimeElement")}} interface it belongs to.
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/sensorerrorevent/index.md
--- title: SensorErrorEvent slug: Web/API/SensorErrorEvent page-type: web-api-interface browser-compat: api.SensorErrorEvent --- {{securecontext_header}}{{APIRef("Sensor API")}} The **`SensorErrorEvent`** interface of the [Sensor APIs](/en-US/docs/Web/API/Sensor_APIs) provides information about errors thrown by a {{domxref('Sensor')}} or derived interface. {{InheritanceDiagram}} ## Constructor - {{domxref("SensorErrorEvent.SensorErrorEvent", "SensorErrorEvent()")}} - : Creates a new `SensorErrorEvent` object. ## Instance properties - {{domxref('SensorErrorEvent.error')}} {{ReadOnlyInline}} - : Returns the {{domxref('DOMException')}} object passed in the event's constructor. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/sensorerrorevent
data/mdn-content/files/en-us/web/api/sensorerrorevent/error/index.md
--- title: "SensorErrorEvent: error property" short-title: error slug: Web/API/SensorErrorEvent/error page-type: web-api-instance-property browser-compat: api.SensorErrorEvent.error --- {{securecontext_header}}{{APIRef("Sensor API")}} The **`error`** read-only property of the {{domxref("SensorErrorEvent")}} interface returns the {{domxref('DOMException')}} object passed in the event's constructor. ## Value A {{domxref('DOMException')}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/sensorerrorevent
data/mdn-content/files/en-us/web/api/sensorerrorevent/sensorerrorevent/index.md
--- title: "SensorErrorEvent: SensorErrorEvent() constructor" short-title: SensorErrorEvent() slug: Web/API/SensorErrorEvent/SensorErrorEvent page-type: web-api-constructor browser-compat: api.SensorErrorEvent.SensorErrorEvent --- {{securecontext_header}}{{APIRef("Sensor API")}} The **`SensorErrorEvent()`** constructor creates a new {{domxref("SensorErrorEvent")}} object which provides information about errors thrown by any of the interfaces based on {{domxref('Sensor')}}. ## Syntax ```js-nolint new SensorErrorEvent(type, options) ``` ### Parameters - `type` - : A string with the name of the event. It is case-sensitive and browsers always set it to `error`. - `options` - : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties: - `error` - : A {{domxref('DOMException')}} object describing the error. ### Return value A new {{domxref("SensorErrorEvent")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/keyboard/index.md
--- title: Keyboard slug: Web/API/Keyboard page-type: web-api-interface status: - experimental browser-compat: api.Keyboard --- {{SeeCompatTable}}{{APIRef("Keyboard API")}}{{securecontext_header}} The **`Keyboard`** interface of the {{domxref("Keyboard API", "", "", "nocode")}} provides functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard. A list of valid code values is found in the [UI Events KeyboardEvent code Values](https://www.w3.org/TR/uievents-code/#key-alphanumeric-writing-system) spec. {{InheritanceDiagram}} ## Instance properties _Also inherits properties from its parent interface, {{DOMxRef("EventTarget")}}._ ## Instance methods _Also inherits methods from its parent interface, {{DOMxRef("EventTarget")}}._ - {{domxref('Keyboard.getLayoutMap()')}} {{experimental_inline}} - : Returns a {{jsxref('Promise')}} that resolves with an instance of {{domxref('KeyboardLayoutMap')}} which is a map-like object with functions for retrieving the strings associated with specific physical keys. - {{domxref('Keyboard.lock()')}} {{experimental_inline}} - : Returns a {{jsxref('Promise')}} after enabling the capture of keypresses for any or all of the keys on the physical keyboard. - {{domxref('Keyboard.unlock()')}} {{experimental_inline}} - : Unlocks all keys captured by the `lock()` method and returns synchronously. ## Example ### Keyboard mapping The following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'W' key on an English QWERTY keyboard. ```js if (navigator.keyboard) { const keyboard = navigator.keyboard; keyboard.getLayoutMap().then((keyboardLayoutMap) => { const upKey = keyboardLayoutMap.get("KeyW"); window.alert(`Press ${upKey} to move up.`); }); } else { // Do something else. } ``` ### Keyboard locking The following example captures the <kbd>W</kbd>, <kbd>A</kbd>, <kbd>S</kbd>, and <kbd>D</kbd> keys, call `lock()` with a list that contains the key code attribute value for each of these keys: ```js navigator.keyboard.lock(["KeyW", "KeyA", "KeyS", "KeyD"]); ``` This captures these keys regardless of which modifiers are used with the key press. Assuming a standard United States QWERTY layout, registering `KeyW` ensures that <kbd>W</kbd>, <kbd>Shift+W</kbd>, <kbd>Control+W</kbd>, <kbd>Control+Shift+W</kbd>, and all other key modifier combinations with <kbd>W</kbd> are sent to the app. The same applies to for `KeyA`, `KeyS`, and `KeyD`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/keyboard
data/mdn-content/files/en-us/web/api/keyboard/unlock/index.md
--- title: "Keyboard: unlock() method" short-title: unlock() slug: Web/API/Keyboard/unlock page-type: web-api-instance-method status: - experimental browser-compat: api.Keyboard.unlock --- {{APIRef("Keyboard API")}}{{SeeCompatTable}}{{securecontext_header}} The **`unlock()`** method of the {{domxref("Keyboard")}} interface unlocks all keys captured by the {{domxref('Keyboard.lock()')}} method and returns synchronously. ## Syntax ```js-nolint unlock() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/keyboard
data/mdn-content/files/en-us/web/api/keyboard/getlayoutmap/index.md
--- title: "Keyboard: getLayoutMap() method" short-title: getLayoutMap() slug: Web/API/Keyboard/getLayoutMap page-type: web-api-instance-method status: - experimental browser-compat: api.Keyboard.getLayoutMap --- {{APIRef("Keyboard API")}}{{SeeCompatTable}}{{securecontext_header}} The **`getLayoutMap()`** method of the {{domxref("Keyboard")}} interface returns a {{jsxref('Promise')}} that resolves with an instance of {{domxref('KeyboardLayoutMap')}} which is a map-like object with functions for retrieving the strings associated with specific physical keys. ## Syntax ```js-nolint getLayoutMap() ``` ### Parameters None. ### Return value A {{jsxref('Promise')}} that resolves with an instance of {{domxref('KeyboardLayoutMap')}}. ### Exceptions - `SecurityError` {{domxref("DOMException")}} - : Thrown if the call is blocked by a [permission policy](/en-US/docs/Web/HTTP/Permissions_Policy). ## Examples The following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'W' key on an English QWERTY keyboard. ```js const keyboard = navigator.keyboard; keyboard.getLayoutMap().then((keyboardLayoutMap) => { const upKey = keyboardLayoutMap.get("KeyW"); window.alert(`Press ${upKey} to move up.`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/keyboard
data/mdn-content/files/en-us/web/api/keyboard/lock/index.md
--- title: "Keyboard: lock() method" short-title: lock() slug: Web/API/Keyboard/lock page-type: web-api-instance-method status: - experimental browser-compat: api.Keyboard.lock --- {{APIRef("Keyboard API")}}{{SeeCompatTable}}{{securecontext_header}} The **`lock()`** method of the {{domxref("Keyboard")}} interface returns a {{jsxref('Promise')}} after enabling the capture of keypresses for any or all of the keys on the physical keyboard. This method can only capture keys that are granted access by the underlying operating system. If `lock()` is called multiple times then only the key codes specified in the most recent call will be locked. Any keys locked by a previous call to `lock()` are unlocked. ## Syntax ```js-nolint lock() lock(keyCodes) ``` ### Parameters - `keyCodes` {{optional_inline}} - : An {{jsxref('Array')}} of one or more key codes to lock. If no keycodes are provided all keys will be locked. A list of valid code values is found in the [UI Events KeyboardEvent code Values](https://w3c.github.io/uievents-code/#key-alphanumeric-writing-system) spec. ### Return value A {{jsxref('Promise')}} that resolves with {{jsxref('undefined')}} when the lock was successful. ### Exceptions - `AbortError` {{domxref("DOMException")}} - : Thrown if a new call to `lock()` is made before the current one has finished. - `InvalidAccessError` {{domxref("DOMException")}} - : Thrown if any key in `keyCodes` is not a valid [key code attribute value](https://www.w3.org/TR/uievents-code/#key-code-attribute-value). - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if `lock()` is not called in an active top-level browsing context. ## 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 ### Capturing all keys The following example captures all keypresses. ```js navigator.keyboard.lock(); ``` ### Capturing specific keys The following example captures the "W", "A", "S", and "D" keys. It captures these keys regardless of which modifiers are used with the key press. Assuming a standard US QWERTY layout, registering `"KeyW"` ensures that "W", Shift+"W", Control+"W", Control+Shift+"W", and all other key modifier combinations with "W" are sent to the app. The same applies to for `"KeyA"`, `"KeyS"` and `"KeyD"`. ```js navigator.keyboard.lock(["KeyW", "KeyA", "KeyS", "KeyD"]); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/xrtransientinputhittestresult/index.md
--- title: XRTransientInputHitTestResult slug: Web/API/XRTransientInputHitTestResult page-type: web-api-interface status: - experimental browser-compat: api.XRTransientInputHitTestResult --- {{APIRef("WebXR Device API")}} {{secureContext_header}}{{SeeCompatTable}} The **`XRTransientInputHitTestResult`** interface of the [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API) contains an array of results of a hit test for transient input, grouped by input source. You can get an array of `XRHitTestResult` objects for a frame by calling {{domxref("XRFrame.getHitTestResultsForTransientInput()")}}. ## Instance properties - {{domxref("XRTransientInputHitTestResult.inputSource")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Represents the {{domxref("XRInputSource")}} that was used to compute the `results` array. - {{domxref("XRTransientInputHitTestResult.results")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Represents an array of {{domxref("XRHitTestResult")}} objects containing the hit test results for the input source, ordered by the distance along the ray used to perform the hit test, with the closest result at position 0. ## Instance methods None. ## Examples ### Accessing transient input hit test results Two arrays are used to access transient input hit test results. First, you get an array of `XRTransientInputHitTestResult` objects by calling {{domxref("XRFrame.getHitTestResultsForTransientInput()")}}. Second, to get to the actual {{domxref("XRHitTestResult")}} objects for an input source, you dereference the `results` property on one of the `XRTransientInputHitTestResult` objects. ```js // frame loop function onXRFrame(time, xrFrame) { let hitTestResults = xrFrame.getHitTestResultsForTransientInput( transientHitTestSource, ); hitTestResults.forEach((resultsPerInputSource) => { resultsPerInputSource.results.forEach((hitTest) => { // do something with the hit test hitTest.getPose(referenceSpace); }); }); } ``` ### Filtering input sources The {{domxref("XRTransientInputHitTestResult.inputSource", "inputSource")}} property allows you to filter hit test results by input source. ```js // frame loop function onXRFrame(time, xrFrame) { let hitTestResults = xrFrame.getHitTestResultsForTransientInput( transientHitTestSource, ); hitTestResults.forEach((resultsPerInputSource) => { if (resultsPerInputSource.inputSource === myPreferredInputSource) { // act on hit test results from the preferred input source } }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRHitTestResult")}} - {{domxref("XRInputSource")}}
0
data/mdn-content/files/en-us/web/api/xrtransientinputhittestresult
data/mdn-content/files/en-us/web/api/xrtransientinputhittestresult/inputsource/index.md
--- title: "XRTransientInputHitTestResult: inputSource property" short-title: inputSource slug: Web/API/XRTransientInputHitTestResult/inputSource page-type: web-api-instance-property status: - experimental browser-compat: api.XRTransientInputHitTestResult.inputSource --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}} The _read-only_ **`inputSource`** property of the {{DOMxRef("XRTransientInputHitTestResult")}} interface represents an {{domxref("XRInputSource")}} object that was used to compute the {{domxref("XRTransientInputHitTestResult.results", "results")}} array. ## Value An {{domxref("XRInputSource")}} object. ## Examples ### Filtering input sources The `inputSource` property allows you to filter hit test results by input source. ```js // frame loop function onXRFrame(time, xrFrame) { let hitTestResults = xrFrame.getHitTestResultsForTransientInput( transientHitTestSource, ); hitTestResults.forEach((resultsPerInputSource) => { if (resultsPerInputSource.inputSource === myPreferredInputSource) { // act on hit test results from the preferred input source } }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRInputSource")}}
0
data/mdn-content/files/en-us/web/api/xrtransientinputhittestresult
data/mdn-content/files/en-us/web/api/xrtransientinputhittestresult/results/index.md
--- title: "XRTransientInputHitTestResult: results property" short-title: results slug: Web/API/XRTransientInputHitTestResult/results page-type: web-api-instance-property status: - experimental browser-compat: api.XRTransientInputHitTestResult.results --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}} The _read-only_ **`results`** property of the {{DOMxRef("XRTransientInputHitTestResult")}} interface represents an array of {{domxref("XRHitTestResult")}} objects containing the hit test results for the input source, ordered by the distance along the ray used to perform the hit test, with the closest result at position 0. ## Value An array of {{domxref("XRHitTestResult")}} objects. ## Examples ### Accessing transient input hit test results Two arrays are used to access transient input hit test results. First, you get an array of `XRTransientInputHitTestResult` objects by calling {{domxref("XRFrame.getHitTestResultsForTransientInput()")}}. Second, to get to the actual {{domxref("XRHitTestResult")}} objects for an input source, you dereference the `results` property on one of the `XRTransientInputHitTestResult` objects. ```js // frame loop function onXRFrame(time, xrFrame) { let hitTestResults = xrFrame.getHitTestResultsForTransientInput( transientHitTestSource, ); hitTestResults.forEach((resultsPerInputSource) => { resultsPerInputSource.results.forEach((hitTest) => { // do something with the hit test hitTest.getPose(referenceSpace); }); }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRHitTestResult")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/cssvalue/index.md
--- title: CSSValue slug: Web/API/CSSValue page-type: web-api-interface status: - deprecated browser-compat: api.CSSValue --- {{APIRef("CSSOM")}}{{Deprecated_Header}} The **`CSSValue`** interface represents the current computed value of a CSS property. > **Note:** This interface was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do > not implement it. > > To achieve your purpose, you can use: > > - the untyped [CSS Object Model](/en-US/docs/Web/API/CSS_Object_Model), widely supported, or > - the modern [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API), less supported and considered experimental. ## Instance properties - {{DOMxRef("CSSValue.cssText")}} {{Deprecated_Inline}} - : A string representing the current value. - {{DOMxRef("CSSValue.cssValueType")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : An `unsigned short` representing a code defining the type of the value. Possible values are: | Constant | Description | | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `CSS_CUSTOM` | The value is a custom value. | | `CSS_INHERIT` | The value is inherited and the `cssText` contains `"inherit"`. | | `CSS_PRIMITIVE_VALUE` | The value is a primitive value and an instance of the {{DOMxRef("CSSPrimitiveValue")}} interface can be obtained by using binding-specific casting methods on this instance of the `CSSValue` interface. | | `CSS_VALUE_LIST` | The value is a `CSSValue` list and an instance of the {{DOMxRef("CSSValueList")}} interface can be obtained by using binding-specific casting methods on this instance of the `CSSValue` interface. | ## Specifications This feature was originally defined in the [DOM Style Level 2](https://www.w3.org/TR/DOM-Level-2-Style/) specification, but has been dropped from any standardization effort since then. It has been superseded by a modern, but incompatible, [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API) that is now on the standard track. ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("CSSPrimitiveValue")}} - {{DOMxRef("CSSValueList")}}
0
data/mdn-content/files/en-us/web/api/cssvalue
data/mdn-content/files/en-us/web/api/cssvalue/csstext/index.md
--- title: "CSSValue: cssText property" short-title: cssText slug: Web/API/CSSValue/cssText page-type: web-api-instance-property status: - deprecated browser-compat: api.CSSValue.cssText --- {{APIRef("CSSOM")}}{{Deprecated_header}} The **`cssText`** property of the {{domxref("CSSValue")}} interface represents the current computed CSS property value. > **Note:** This property was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do > not implement it. > > To achieve your purpose, you can use: > > - the untyped [CSS Object Model](/en-US/docs/Web/API/CSS_Object_Model), widely supported, or > - the modern [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API), less supported and considered experimental. ## Value A string representing the current CSS property value. ## Examples ```js const styleDeclaration = document.styleSheets[0].cssRules[0].style; const cssValue = styleDeclaration.getPropertyCSSValue("color"); console.log(cssValue.cssText); ``` ## Specifications This feature was originally defined in the [DOM Style Level 2](https://www.w3.org/TR/DOM-Level-2-Style/) specification, but has been dropped from any standardization effort since then. It has been superseded by a modern, but incompatible, [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API) that is now on the standard track. ## Browser compatibility This feature was originally defined in the [DOM Style Level 2](https://www.w3.org/TR/DOM-Level-2-Style/) specification, but has been dropped from any standardization effort since then. It has been superseded by a modern, but incompatible, [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API) that is now on the standard track. ## See also - {{domxref("CSSStyleDeclaration.getPropertyCSSValue()")}}
0
data/mdn-content/files/en-us/web/api/cssvalue
data/mdn-content/files/en-us/web/api/cssvalue/cssvaluetype/index.md
--- title: "CSSValue: cssValueType property" short-title: cssValueType slug: Web/API/CSSValue/cssValueType page-type: web-api-instance-property status: - deprecated browser-compat: api.CSSValue.cssValueType --- {{APIRef("CSSOM")}}{{Deprecated_header}} The **`cssValueType`** read-only property of the {{domxref("CSSValue")}} interface represents the type of the current computed CSS property value. > **Note:** This property was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do > not implement it. > > To achieve your purpose, you can use: > > - the untyped [CSS Object Model](/en-US/docs/Web/API/CSS_Object_Model), widely supported, or > - the modern [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API), less supported and considered experimental. ## Value An `unsigned short` representing a code defining the type of the value. Possible values are: <table class="no-markdown"> <thead> <tr> <th>Constant</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>CSS_CUSTOM</code></td> <td>The value is a custom value.</td> </tr> <tr> <td><code>CSS_INHERIT</code></td> <td> The value is inherited and the <code>cssText</code> contains <code>"inherit"</code>. </td> </tr> <tr> <td><code>CSS_PRIMITIVE_VALUE</code></td> <td> The value is a primitive value and an instance of the {{domxref("CSSPrimitiveValue")}} interface can be obtained by using binding-specific casting methods on this instance of the <code>CSSValue</code> interface. </td> </tr> <tr> <td><code>CSS_VALUE_LIST</code></td> <td> The value is a <code>CSSValue</code> list and an instance of the {{domxref("CSSValueList")}} interface can be obtained by using binding-specific casting methods on this instance of the <code>CSSValue</code> interface. </td> </tr> </tbody> </table> ## Examples ```js const styleDeclaration = document.styleSheets[0].cssRules[0].style; const cssValue = styleDeclaration.getPropertyCSSValue("color"); console.log(cssValue.cssValueType); ``` ## Specifications This feature was originally defined in the [DOM Style Level 2](https://www.w3.org/TR/DOM-Level-2-Style/) specification, but has been dropped from any standardization effort since then. It has been superseded by a modern, but incompatible, [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API) that is now on the standard track. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/pointer_lock_api/index.md
--- title: Pointer Lock API slug: Web/API/Pointer_Lock_API page-type: web-api-overview browser-compat: - api.Document.exitPointerLock - api.Element.requestPointerLock spec-urls: https://w3c.github.io/pointerlock/ --- {{DefaultAPISidebar("Pointer Lock API")}} The **Pointer Lock API** (formerly called _Mouse Lock API_) provides input methods based on the movement of the mouse over time (i.e., deltas), not just the absolute position of the mouse cursor in the viewport. It gives you access to raw mouse movement, locks the target of mouse events to a single element, eliminates limits on how far mouse movement can go in a single direction, and removes the cursor from view. It is ideal for first-person 3D games, for example. More than that, the API is useful for any applications that require significant mouse input to control movements, rotate objects, and change entries, for example allowing users to control the viewing angle by moving the mouse around without any button clicking. The buttons are then freed up for other actions. Other examples include apps for viewing maps or satellite imagery. Pointer lock lets you access mouse events even when the cursor goes past the boundary of the browser or screen. For example, your users can continue to rotate or manipulate a 3D model by moving the mouse without end. Without Pointer lock, the rotation or manipulation stops the moment the pointer reaches the edge of the browser or screen. Game players can now click buttons and swipe the mouse cursor back and forth without worrying about leaving the game play area and accidentally clicking another application that would take mouse focus away from the game. ## Basic concepts Pointer lock is related to [mouse capture](/en-US/docs/Web/API/Element/setCapture). Mouse capture provides continued delivery of events to a target element while a mouse is being dragged, but it stops when the mouse button is released. Pointer lock is different from mouse capture in the following ways: - It is persistent: Pointer lock does not release the mouse until an explicit API call is made or the user uses a specific release gesture. - It is not limited by browser or screen boundaries. - It continues to send events regardless of mouse button state. - It hides the cursor. ## Method/properties overview This section provides a brief description of each property and method related to the pointer lock specification. ### requestPointerLock() The Pointer lock API, similar to the [Fullscreen API](/en-US/docs/Web/API/Fullscreen_API), extends DOM elements by adding a new method, {{domxref("Element.requestPointerLock","requestPointerLock()")}}. The following example requests pointer lock on a {{htmlelement("canvas")}} element: ```js canvas.addEventListener("click", async () => { await canvas.requestPointerLock(); }); ``` > **Note:** If a user has exited pointer lock via the [default unlock gesture](https://w3c.github.io/pointerlock/#dfn-default-unlock-gesture), or pointer lock has not previously been entered for this document, an event generated as a result of an [engagement gesture](https://w3c.github.io/pointerlock/#dfn-engagement-gesture) must be received by the document before [`requestPointerLock`](https://w3c.github.io/pointerlock/#dom-element-requestpointerlock) will succeed. (from <https://w3c.github.io/pointerlock/#extensions-to-the-element-interface>) Operating systems enable mouse acceleration by default, which is useful when you sometimes want slow precise movement (think about you might use a graphics package), but also want to move great distances with a faster mouse movement (think about scrolling, and selecting several files). For some first-person perspective games however, raw mouse input data is preferred for controlling camera rotation — where the same distance movement, fast or slow, results in the same rotation. This results in a better gaming experience and higher accuracy, according to professional gamers. To disable OS-level mouse acceleration and access raw mouse input, you can set the `unadjustedMovement` to `true`: ```js canvas.addEventListener("click", async () => { await canvas.requestPointerLock({ unadjustedMovement: true, }); }); ``` ## Handling promise and non-promise versions of requestPointerLock() The above code snippet will still work in browsers that do not support the promise-based version of `requestPointerLock()` or the `unadjustedMovement` option — the [`await`](/en-US/docs/Web/JavaScript/Reference/Operators/await) operator is permitted in front of a function that does not return a promise, and the options object will just be ignored in non-supporting browsers. However, this could be confusing, and has other potential side-effects (for example, trying to use `requestPointerLock().then()` would throw an error in non-supporting browsers), so you may want to handle this explicitly using code along the following lines: ```js function requestPointerLockWithUnadjustedMovement() { const promise = myTargetElement.requestPointerLock({ unadjustedMovement: true, }); if (!promise) { console.log("disabling mouse acceleration is not supported"); return; } return promise .then(() => console.log("pointer is locked")) .catch((error) => { if (error.name === "NotSupportedError") { // Some platforms may not support unadjusted movement. // You can request again a regular pointer lock. return myTargetElement.requestPointerLock(); } }); } ``` ### pointerLockElement and exitPointerLock() The Pointer lock API also extends the {{domxref("Document")}} interface, adding a new property and a new method: - {{domxref("Document.pointerLockElement","pointerLockElement")}} is used for accessing the currently locked element (if any). - {{domxref("Document.exitPointerLock","exitPointerLock()")}} is used to exit the pointer lock. The {{domxref("Document.pointerLockElement","pointerLockElement")}} property is useful for determining if any element is currently pointer locked (e.g., for doing a boolean check) and also for obtaining a reference to the locked element, if any. Here is an example of using `pointerLockElement`: ```js if (document.pointerLockElement === canvas) { console.log("The pointer lock status is now locked"); } else { console.log("The pointer lock status is now unlocked"); } ``` The {{domxref("Document.exitPointerLock()")}} method is used to exit pointer lock, and like {{domxref("Element.requestPointerLock","requestPointerLock")}}, works asynchronously using the {{domxref("Document/pointerlockchange_event", "pointerlockchange")}} and {{domxref("Document/pointerlockerror_event", "pointerlockerror")}} events, which you'll see more about below. ```js document.exitPointerLock(); ``` ## pointerlockchange event When the Pointer lock state changes—for example, when calling {{domxref("Element.requestPointerLock","requestPointerLock()")}} or {{domxref("Document.exitPointerLock","exitPointerLock()")}}, the user pressing the ESC key, etc.—the {{domxref("Document/pointerlockchange_event", "pointerlockchange")}} event is dispatched to the `document`. This is a simple event containing no extra data. ```js document.addEventListener("pointerlockchange", lockChangeAlert, false); function lockChangeAlert() { if (document.pointerLockElement === canvas) { console.log("The pointer lock status is now locked"); // Do something useful in response } else { console.log("The pointer lock status is now unlocked"); // Do something useful in response } } ``` ## pointerlockerror event When there is an error caused by calling {{domxref("Element.requestPointerLock","requestPointerLock()")}} or {{domxref("Document.exitPointerLock","exitPointerLock()")}}, the {{domxref("Document/pointerlockerror_event", "pointerlockerror")}} event is dispatched to the `document`. This is a simple event containing no extra data. ```js document.addEventListener("pointerlockerror", lockError, false); function lockError(e) { alert("Pointer lock failed"); } ``` ## Extensions to mouse events The Pointer lock API extends the normal {{domxref("MouseEvent")}} interface with movement attributes. Two new attributes to mouse events—{{domxref("MouseEvent.movementX","movementX")}} and {{domxref("MouseEvent.movementY","movementY")}}—provide the change in mouse positions. The values of the parameters are the same as the difference between the values of {{domxref("MouseEvent")}} properties, {{domxref("MouseEvent.screenX","screenX")}} and {{domxref("MouseEvent.screenY","screenY")}}, which are stored in two subsequent {{domxref("Element/mousemove_event", "mousemove")}} events, `eNow` and `ePrevious`. In other words, the Pointer lock parameter `movementX = eNow.screenX - ePrevious.screenX`. ### Locked state When Pointer lock is enabled, the standard {{domxref("MouseEvent")}} properties {{domxref("MouseEvent.clientX","clientX")}}, {{domxref("MouseEvent.clientY","clientY")}}, {{domxref("MouseEvent.screenX","screenX")}}, and {{domxref("MouseEvent.screenY","screenY")}} are held constant, as if the mouse is not moving. The {{domxref("MouseEvent.movementX","movementX")}} and {{domxref("MouseEvent.movementY","movementY")}} properties continue to provide the mouse's change in position. There is no limit to {{domxref("MouseEvent.movementX","movementX")}} and {{domxref("MouseEvent.movementY","movementY")}} values if the mouse is continuously moving in a single direction. The concept of the mouse cursor does not exist and the cursor cannot move off the window or be clamped by a screen edge. ### Unlocked state The parameters {{domxref("MouseEvent.movementX","movementX")}} and {{domxref("MouseEvent.movementY","movementY")}} are valid regardless of the mouse lock state, and are available even when unlocked for convenience. When the mouse is unlocked, the system cursor can exit and re-enter the browser window. If that happens, {{domxref("MouseEvent.movementX","movementX")}} and {{domxref("MouseEvent.movementY","movementY")}} could be set to zero. ## Simple example walkthrough We've written a [pointer lock demo](https://mdn.github.io/dom-examples/pointer-lock/) ([see source code](https://github.com/mdn/dom-examples/tree/main/pointer-lock)) to show you how to use it to set up a simple control system. This demo uses JavaScript to draw a ball on top of an {{ htmlelement("canvas") }} element. When you click the canvas, pointer lock is then used to remove the mouse pointer and allow you to move the ball directly using the mouse. Let's see how this works. We set initial x and y positions on the canvas: ```js let x = 50; let y = 50; ``` Next we set up an event listener to run the `requestPointerLock()` method on the canvas when it is clicked, which initiates pointer lock. The `document.pointerLockElement` check is to see if there is already an active pointer lock — we don't want to keep calling `requestPointerLock()` on the canvas every time we click inside it if we already have pointer lock. ```js canvas.addEventListener("click", async () => { if (!document.pointerLockElement) { await canvas.requestPointerLock({ unadjustedMovement: true, }); } }); ``` > **Note:** The above snippet works in browsers that don't support the promise version of `requestPointerLock()`. See [Handling promise and non-promise versions of requestPointerLock()](#handling_promise_and_non-promise_versions_of_requestpointerlock) for an explanation. Now for the dedicated pointer lock event listener: `pointerlockchange`. When this occurs, we run a function called `lockChangeAlert()` to handle the change. ```js document.addEventListener("pointerlockchange", lockChangeAlert, false); ``` This function checks the `pointerLockElement` property to see if it is our canvas. If so, it attached an event listener to handle the mouse movements with the `updatePosition()` function. If not, it removes the event listener again. ```js function lockChangeAlert() { if (document.pointerLockElement === canvas) { console.log("The pointer lock status is now locked"); document.addEventListener("mousemove", updatePosition, false); } else { console.log("The pointer lock status is now unlocked"); document.removeEventListener("mousemove", updatePosition, false); } } ``` The `updatePosition()` function updates the position of the ball on the canvas (`x` and `y`), and also includes `if ()` statements to check whether the ball has gone off the edges of the canvas. If so, it makes the ball wrap around to the opposite edge. It also includes a check whether a [`requestAnimationFrame()`](/en-US/docs/Web/API/window/requestAnimationFrame) call has previously been made, and if so, calls it again as required, and calls the `canvasDraw()` function that updates the canvas scene. A tracker is also set up to write out the X and Y values to the screen, for reference. ```js const tracker = document.getElementById("tracker"); let animation; function updatePosition(e) { x += e.movementX; y += e.movementY; if (x > canvas.width + RADIUS) { x = -RADIUS; } if (y > canvas.height + RADIUS) { y = -RADIUS; } if (x < -RADIUS) { x = canvas.width + RADIUS; } if (y < -RADIUS) { y = canvas.height + RADIUS; } tracker.textContent = `X position: ${x}, Y position: ${y}`; if (!animation) { animation = requestAnimationFrame(() => { animation = null; canvasDraw(); }); } } ``` The `canvasDraw()` function draws the ball in the current `x` and `y` positions: ```js function canvasDraw() { ctx.fillStyle = "black"; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = "#f00"; ctx.beginPath(); ctx.arc(x, y, RADIUS, 0, degToRad(360), true); ctx.fill(); } ``` ## IFrame limitations Pointer lock can only lock one {{htmlelement("iframe")}} at a time. If you lock one `<iframe>`, you can't lock another one and transfer the target to it; pointer lock will error out. To avoid this limitation, first unlock the locked `<iframe>`, and then lock the other. While `<iframe>` work by default, "sandboxed" `<iframe>`s block Pointer lock. To avoid this limitation, use `<iframe sandbox="allow-pointer-lock">`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("MouseEvent")}} - {{domxref("Element.requestPointerLock()")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/gpuexternaltexture/index.md
--- title: GPUExternalTexture slug: Web/API/GPUExternalTexture page-type: web-api-interface status: - experimental browser-compat: api.GPUExternalTexture --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`GPUExternalTexture`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} represents a wrapper object containing an {{domxref("HTMLVideoElement")}} snapshot that can be used as a texture in GPU rendering operations. A `GPUExternalTexture` object instance is created using {{domxref("GPUDevice.importExternalTexture()")}}. {{InheritanceDiagram}} ## Instance properties - {{domxref("GPUExternalTexture.label", "label")}} {{Experimental_Inline}} - : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. ## Examples In the WebGPU samples [Video Uploading sample](https://webgpu.github.io/webgpu-samples/samples/videoUploading), a `GPUExternalTexture` object (created via a {{domxref("GPUDevice.importExternalTexture()")}} call) is used as the value of a bind group entry `resource`, specified when creating a {{domxref("GPUBindGroup")}} via a {{domxref("GPUDevice.createBindGroup()")}} call: ```js //... const uniformBindGroup = device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [ { binding: 1, resource: sampler, }, { binding: 2, resource: device.importExternalTexture({ source: video, }), }, ], }); //... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpuexternaltexture
data/mdn-content/files/en-us/web/api/gpuexternaltexture/label/index.md
--- title: "GPUExternalTexture: label property" short-title: label slug: Web/API/GPUExternalTexture/label page-type: web-api-instance-property status: - experimental browser-compat: api.GPUExternalTexture.label --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`label`** property of the {{domxref("GPUExternalTexture")}} interface provides a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. This can be set by providing a `label` property in the descriptor object passed into the originating {{domxref("GPUDevice.importExternalTexture()")}} call, or you can get and set it directly on the `GPUExternalTexture` object. ## Value A string. If this has not been previously set as described above, it will be an empty string. ## Examples Setting and getting a label via `GPUExternalTexture.label`: ```js // ... const externalTexture = device.importExternalTexture({ source: video, }); externalTexture.label = "myExtTexture"; console.log(externalTexture.label); // "myExtTexture" ``` Setting a label via the originating {{domxref("GPUDevice.importExternalTexture()")}} call, and then getting it via `GPUExternalTexture.label`: ```js // ... const externalTexture = device.importExternalTexture({ source: video, label: "myExtTexture", }); console.log(externalTexture.label); // "myExtTexture" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/rtctransportstats/index.md
--- title: RTCTransportStats slug: Web/API/RTCTransportStats page-type: web-api-interface browser-compat: api.RTCStatsReport.type_transport --- {{APIRef("WebRTC")}} The **`RTCTransportStats`** dictionary of the [WebRTC API](/en-US/docs/Web/API/WebRTC_API) provides information about the transport ({{domxref("RTCDtlsTransport")}} and its underlying {{domxref("RTCIceTransport")}}) used by a particular candidate pair. The _BUNDLE_ feature is an SDP extension that allows negotiation to use a single transport for sending and receiving media described by multiple SDP media descriptions. If the remote endpoint is aware of this feature, all {{domxref("MediaStreamTrack")}} and data channels are bundled onto a single transport at the completion of negotiation. This is true for current browsers, but if connecting to an older endpoint that is not BUNDLE-aware, then separate transports might be used for different media. The policy to use in the negotiation is configured in the [`RTCPeerConnection` constructor](/en-US/docs/Web/API/RTCPeerConnection/RTCPeerConnection). These statistics can be obtained by iterating the {{domxref("RTCStatsReport")}} returned by {{domxref("RTCPeerConnection.getStats()")}} until you find a report with the [`type`](#type) of `transport`. ## Instance properties - `bytesReceived` {{optional_inline}} - : The total number of payload bytes received on this transport (bytes received, not including headers, padding or ICE connectivity checks). - `bytesSent` {{optional_inline}} - : The total number of payload bytes sent on this transport (bytes sent, not including headers, padding or ICE connectivity checks). - `dtlsCipher` {{optional_inline}} - : A string indicating the name of the cipher suite used for the DTLS transport, as defined in the "Description" column of the [TLS Cipher Suites](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4) section in the _IANA cipher suite registry_. For example `"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"`. - `dtlsRole` {{optional_inline}} {{experimental_inline}} - : The DTLS role of the associated {{domxref("RTCPeerConnection")}}. This is one of: - `client` - `server` - `unknown` (before the DTLS negotiation starts). - `dtlsState` - : A string indicating the current {{domxref("RTCDtlsTransport.state","state")}} of the underlying {{domxref("RTCDtlsTransport")}}. This is one of: - [`new`](/en-US/docs/Web/API/RTCDtlsTransport/state#new) - [`connecting`](/en-US/docs/Web/API/RTCDtlsTransport/state#connecting) - [`connected`](/en-US/docs/Web/API/RTCDtlsTransport/state#connected) - [`closed`](/en-US/docs/Web/API/RTCDtlsTransport/state#closed) - [`failed`](/en-US/docs/Web/API/RTCDtlsTransport/state#failed) - `iceLocalUsernameFragment` {{optional_inline}} {{experimental_inline}} - : A string indicating the local username fragment used in message validation procedures for this transport. This is the same value as the local {{domxref("RTCIceCandidate.usernameFragment")}}, and will change if the connection is renegotiated. - `iceRole` {{optional_inline}} {{experimental_inline}} - : A string indicating the [ICE `role`](/en-US/docs/Web/API/RTCIceTransport/role) of the underlying {{domxref("RTCDtlsTransport.iceTransport")}}. This is one of: - [`controlled`](/en-US/docs/Web/API/RTCIceTransport/role#controlled) - [`controlling`](/en-US/docs/Web/API/RTCIceTransport/role#controlling) - [`unknown`](/en-US/docs/Web/API/RTCIceTransport/role#unknown) - `iceState` {{optional_inline}} {{experimental_inline}} - : A string indicating the current {{domxref("RTCIceTransport.state","state")}} of the underlying {{domxref("RTCIceTransport")}}. This is one of: - [`new`](/en-US/docs/Web/API/RTCIceTransport/state#new) - [`checking`](/en-US/docs/Web/API/RTCIceTransport/state#checking) - [`connected`](/en-US/docs/Web/API/RTCIceTransport/state#connected) - [`completed`](/en-US/docs/Web/API/RTCIceTransport/state#completed) - [`disconnected`](/en-US/docs/Web/API/RTCIceTransport/state#disconnected) - [`failed`](/en-US/docs/Web/API/RTCIceTransport/state#failed) - [`closed`](/en-US/docs/Web/API/RTCIceTransport/state#closed) - `selectedCandidatePairId` {{optional_inline}} - : A string containing the unique identifier for the object that was inspected to produce the {{domxref("RTCIceCandidatePairStats")}} associated with this transport. - `localCertificateId` {{optional_inline}} - : A string containing the id of the local certificate used by this transport. Only present for DTLS transports, and after DTLS has been negotiated. - `packetsSent` {{optional_inline}} {{experimental_inline}} - : The total number of packets sent over this transport. - `packetsReceived` {{optional_inline}} {{experimental_inline}} - : The total number of packets received on this transport. - `remoteCertificateId` {{optional_inline}} - : A string containing the id or the remote certificate used by this transport. Only present for DTLS transports, and after DTLS has been negotiated. - `selectedCandidatePairChanges` {{optional_inline}} - : The number of times that the selected candidate pair of this transport has changed. The value is initially zero and increases whenever a candidate pair selected or lost. - `srtpCipher` {{optional_inline}} - : A string indicating the descriptive name of the protection profile used for the [Secure Real-time Transport Protocol (SRTP)](/en-US/docs/Glossary/RTP) transport, as defined in the "Profile" column of the [IANA DTLS-SRTP protection profile registry](https://www.iana.org/assignments/srtp-protection/srtp-protection.xhtml#srtp-protection-1) and [RFC5764](https://www.rfc-editor.org/rfc/rfc5764.html#section-4.1.2). For example `"AES_CM_128_HMAC_SHA1_80"` specifies the following profile, where `maximum_lifetime` is the maximum number of packets that can be protected by a single set of keys. ```plain SRTP_AES128_CM_HMAC_SHA1_80 cipher: AES_128_CM cipher_key_length: 128 cipher_salt_length: 112 maximum_lifetime: 2^31 auth_function: HMAC-SHA1 auth_key_length: 160 auth_tag_length: 80 ``` - `tlsVersion` {{optional_inline}} - : A string containing the negotiated TLS version. This is present for DTLS transports, and only exists after DTLS has been negotiated. The value comes from the DTLS handshake `ServerHello.version`, and is represented as four upper case hexadecimal digits, where the digits represent the two bytes of the version. Note however that the bytes might not map directly to version numbers. For example, DTLS represents version 1.2 as `'FEFD'` which numerically is `{254, 253}`. ### Common instance properties The following properties are common to all WebRTC statistics objects. <!-- RTCStats --> - {{domxref("RTCTransportStats.id", "id")}} - : A string that uniquely identifies the object that is being monitored to produce this set of statistics. - {{domxref("RTCTransportStats.timestamp", "timestamp")}} - : A {{domxref("DOMHighResTimeStamp")}} object indicating the time at which the sample was taken for this statistics object. - {{domxref("RTCTransportStats.type", "type")}} - : A string with the value `"transport"`, indicating the type of statistics that the object contains. ## Examples This example shows a function to return the transport statistics, or `null` if no statistics are provided. The function waits for the result of a call to {{domxref("RTCPeerConnection.getStats()")}} and then iterates the returned {{domxref("RTCStatsReport")}} to get just the stats of type `"transport"`. It then returns the statistics, or `null`, using the data in the report. ```js async function numberOpenConnections (peerConnection) { const stats = await peerConnection.getStats(); let transportStats = null; stats.forEach((report) => { if (report.type === "transport") { transportStats = report; break; } }); return transportStats } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtctransportstats
data/mdn-content/files/en-us/web/api/rtctransportstats/id/index.md
--- title: "RTCTransportStats: id property" short-title: id slug: Web/API/RTCTransportStats/id page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_transport.id --- {{APIRef("WebRTC")}} The **`id`** property of the {{domxref("RTCTransportStats")}} dictionary is a string which uniquely identifies the object for which this object provides statistics. Using the `id`, you can correlate this statistics object with others, in order to monitor statistics over time for a given WebRTC object, such as an {{domxref("RTCDtlsTransport")}}, or an {{domxref("RTCPeerConnection")}}. ## Value A string that uniquely identifies the object for which this `RTCTransportStats` object provides statistics. The format of the ID string is not defined by the specification, so you cannot reliably make any assumptions about the contents of the string, or assume that the format of the string will remain unchanged for a given object type. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtctransportstats
data/mdn-content/files/en-us/web/api/rtctransportstats/type/index.md
--- title: "RTCTransportStats: type property" short-title: type slug: Web/API/RTCTransportStats/type page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_transport.type --- {{APIRef("WebRTC")}} The **`type`** property of the {{domxref("RTCTransportStats")}} dictionary is a string with the value `"transport"`. Different statistics are obtained by iterating the {{domxref("RTCStatsReport")}} object returned by a call to {{domxref("RTCPeerConnection.getStats()")}}. The type indicates the set of statistics available through the object in a particular iteration step. A value of `"transport"` indicates that the statistics available in the current step are those defined in {{domxref("RTCTransportStats")}}. ## Value A string with the value `"transport"`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtctransportstats
data/mdn-content/files/en-us/web/api/rtctransportstats/timestamp/index.md
--- title: "RTCTransportStats: timestamp property" short-title: timestamp slug: Web/API/RTCTransportStats/timestamp page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_transport.timestamp --- {{APIRef("WebRTC")}} The **`timestamp`** property of the {{domxref("RTCTransportStats")}} dictionary is a {{domxref("DOMHighResTimeStamp")}} object specifying the time at which the data in the object was sampled. ## Value A {{domxref("DOMHighResTimeStamp")}} value indicating the time at which the activity described by the statistics in this object was recorded, in milliseconds elapsed since the beginning of January 1, 1970, UTC. The value should be accurate to within a few milliseconds but may not be entirely precise, either because of hardware or operating system limitations or because of [fingerprinting](/en-US/docs/Glossary/Fingerprinting) protection in the form of reduced clock precision or accuracy. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/usbendpoint/index.md
--- title: USBEndpoint slug: Web/API/USBEndpoint page-type: web-api-interface status: - experimental browser-compat: api.USBEndpoint --- {{APIRef("WebUSB API")}}{{securecontext_header}}{{SeeCompatTable}} The `USBEndpoint` interface of the [WebUSB API](/en-US/docs/Web/API/WebUSB_API) provides information about an endpoint provided by the USB device. An endpoint represents a unidirectional data stream into or out of a device. ## Constructor - {{domxref("USBEndpoint.USBEndpoint", "USBEndpoint()")}} {{Experimental_Inline}} - : Creates a new `USBEndpoint` object which will be populated with information about the endpoint on the provided {{domxref('USBAlternateInterface')}} with the given endpoint number and transfer direction. ## Instance properties - {{domxref("USBEndpoint.endpointNumber")}} {{Experimental_Inline}} - : Returns this endpoint's "endpoint number" which is a value from 1 to 15 extracted from the `bEndpointAddress` field of the endpoint descriptor defining this endpoint. This value is used to identify the endpoint when calling methods on `USBDevice`. - {{domxref("USBEndpoint.direction")}} {{Experimental_Inline}} - : Returns the direction in which this endpoint transfers data, one of: - `"in"` - Data is transferred from device to host. - `"out"` - Data is transferred from host to device. - {{domxref("USBEndpoint.type")}} {{Experimental_Inline}} - : Returns the type of this endpoint, one of: - `"bulk"` - Provides reliable data transfer for large payloads. Data sent through a bulk endpoint is guaranteed to be delivered or generate an error but may be preempted by other data traffic. - `"interrupt"` - Provides reliable data transfer for small payloads. Data sent through an interrupt endpoint is guaranteed to be delivered or generate an error and is also given dedicated bus time for transmission. - `"isochronous"` - Provides unreliable data transfer for payloads that must be delivered periodically. They are given dedicated bus time but if a deadline is missed the data is dropped. - {{domxref("USBEndpoint.packetSize")}} {{Experimental_Inline}} - : Returns the size of the packets that data sent through this endpoint will be divided into. ## Examples While sometimes the developer knows ahead of time the exact layout of a device's endpoints there are cases where this must be discovered at runtime. For example, a USB serial device must provide bulk input and output endpoints but their endpoint numbers will depend on what other interfaces the device provides. This code identifies the correct endpoints by searching for the interface implementing the USB CDC interface class and then identifying the candidate endpoints based on their type and direction. ```js let inEndpoint = undefined; let outEndpoint = undefined; for (const { alternates } of device.configuration.interfaces) { // Only support devices with out multiple alternate interfaces. const alternate = alternates[0]; // Identify the interface implementing the USB CDC class. const USB_CDC_CLASS = 10; if (alternate.interfaceClass !== USB_CDC_CLASS) { continue; } for (const endpoint of alternate.endpoints) { // Identify the bulk transfer endpoints. if (endpoint.type !== "bulk") { continue; } if (endpoint.direction === "in") { inEndpoint = endpoint.endpointNumber; } else if (endpoint.direction === "out") { outEndpoint = endpoint.endpointNumber; } } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/audiosinkinfo/index.md
--- title: AudioSinkInfo slug: Web/API/AudioSinkInfo page-type: web-api-interface status: - experimental browser-compat: api.AudioSinkInfo --- {{APIRef("Web Audio API")}}{{SeeCompatTable}} The **`AudioSinkInfo`** interface of the {{domxref("Web Audio API", "Web Audio API", "", "nocode")}} represents information describing an {{domxref("AudioContext")}}'s sink ID, retrieved via {{domxref("AudioContext.sinkId")}}. {{InheritanceDiagram}} ## Instance properties - {{domxref("AudioSinkInfo.type", "type")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the type of the audio output device. ## Examples If a new {{domxref("AudioContext")}} is created with a `sinkId` value of `{ type: 'none' }`, calling {{domxref("AudioContext.sinkId")}} later in the code will return a `AudioSinkInfo` object containing `type: 'none'`. This is currently the only value available. ```js audioCtx = new window.AudioContext({ sinkId: { type: "none" }, }); // ... audioCtx.sinkId; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [SetSinkId test example](https://set-sink-id.glitch.me/) - {{domxref("AudioContext.setSinkId()")}} - {{domxref("AudioContext.sinkId")}} - {{domxref("AudioContext/sinkchange_event", "sinkchange")}}
0
data/mdn-content/files/en-us/web/api/audiosinkinfo
data/mdn-content/files/en-us/web/api/audiosinkinfo/type/index.md
--- title: "AudioSinkInfo: type property" short-title: type slug: Web/API/AudioSinkInfo/type page-type: web-api-instance-property status: - experimental browser-compat: api.AudioSinkInfo.type --- {{APIRef("Web Audio API")}}{{SeeCompatTable}} The **`type`** read-only property of the {{domxref("AudioSinkInfo")}} interface returns the type of the audio output device. ## Value A string. Currently the only value is `none`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [SetSinkId test example](https://set-sink-id.glitch.me/) - {{domxref("AudioContext.setSinkId()")}} - {{domxref("AudioContext.sinkId")}} - {{domxref("AudioContext/sinkchange_event", "sinkchange")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/domstringmap/index.md
--- title: DOMStringMap slug: Web/API/DOMStringMap page-type: web-api-interface browser-compat: api.DOMStringMap --- {{ APIRef("HTML DOM") }} The **`DOMStringMap`** interface is used for the {{domxref("HTMLElement.dataset")}} attribute, to represent data for custom attributes added to elements. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLElement.dataset")}} - [Global attributes - `data-*`](/en-US/docs/Web/HTML/Global_attributes/data-*)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/cssmathvalue/index.md
--- title: CSSMathValue slug: Web/API/CSSMathValue page-type: web-api-interface browser-compat: api.CSSMathValue --- {{APIRef("CSS Typed Object Model API")}} The **`CSSMathValue`** interface of the {{domxref('CSS_Object_Model#css_typed_object_model','','',' ')}} a base class for classes representing complex numeric values. {{InheritanceDiagram}} ## Interfaces based on CSSMathValue Below is a list of interfaces based on the CSSMathValue interface. - {{domxref('CSSMathInvert')}} - {{domxref('CSSMathMax')}} - {{domxref('CSSMathMin')}} - {{domxref('CSSMathNegate')}} - {{domxref('CSSMathProduct')}} - {{domxref('CSSMathSum')}} ## Instance properties - {{domxref('CSSMathValue.operator')}} - : Indicates the operator that the current subtype represents. ## Static methods _The interface may also inherit methods from its parent interface, {{domxref("CSSNumericValue")}}._ ## Instance methods _The interface may also inherit methods from its parent interface, {{domxref("CSSNumericValue")}}._ ## Examples We create an element with a [`width`](/en-US/docs/Web/CSS/width) determined using a [`calc()`](/en-US/docs/Web/CSS/calc) function, then {{domxref("console/log_static", "console.log()")}} the `operator`. ```html <div>has width</div> ``` We assign a `width` with a calculation ```css div { width: calc(30% - 20px); } ``` We add the JavaScript ```js const styleMap = document.querySelector("div").computedStyleMap(); console.log(styleMap.get("width")); // CSSMathSum {values: CSSNumericArray, operator: "sum"} console.log(styleMap.get("width").operator); // 'sum' console.log(styleMap.get("width").values[1].value); // -20 ``` {{EmbedLiveSample("Examples", 120, 300)}} The `CSSMathValue.operator` returns '`sum`' because `styleMap.get('width').values[1].value );` is `-20`: adding a negative number. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssmathvalue
data/mdn-content/files/en-us/web/api/cssmathvalue/operator/index.md
--- title: "CSSMathValue: operator property" short-title: operator slug: Web/API/CSSMathValue/operator page-type: web-api-instance-property browser-compat: api.CSSMathValue.operator --- {{APIRef("CSS Typed Object Model API")}} The **`CSSMathValue.operator`** read-only property of the {{domxref("CSSMathValue")}} interface indicates the operator that the current subtype represents. For example, if the current `CSSMathValue` subtype is `CSSMathSum`, this property will return the string `"sum"`. ## Value A {{jsxref('String')}}. | Interface | Value | | ----------------------------- | ----------- | | {{domxref('CSSMathSum')}} | `"sum"` | | {{domxref('CSSMathProduct')}} | `"product"` | | {{domxref('CSSMathMin')}} | `"min"` | | {{domxref('CSSMathMax')}} | `"max"` | | {{domxref('CSSMathClamp')}} | `"clamp"` | | {{domxref('CSSMathNegate')}} | `"negate"` | | {{domxref('CSSMathInvert')}} | `"invert"` | ## Examples We create an element with a [`width`](/en-US/docs/Web/CSS/width) determined using a [`calc()`](/en-US/docs/Web/CSS/calc) function, then {{domxref("console/log_static", "console.log()")}} the `operator`. ```html <div>My width has a <code>calc()</code> function</div> ``` We assign a `width` with a calculation ```css div { width: calc(50% - 0.5vw); } ``` We add the JavaScript ```js const styleMap = document.querySelector("div").computedStyleMap(); console.log(styleMap.get("width")); // CSSMathSum {values: CSSNumericArray, operator: "sum"} console.log(styleMap.get("width").values); // CSSNumericArray {0: CSSUnitValue, 1: CSSMathNegate, length: 2} console.log(styleMap.get("width").operator); // 'sum' console.log(styleMap.get("width").values[1].operator); // 'negate' ``` {{EmbedLiveSample("Examples", 120, 300)}} The `CSSMathValue.operator` returns `sum` for the equation and `negate` for the operator on the second value. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/mediasourcehandle/index.md
--- title: MediaSourceHandle slug: Web/API/MediaSourceHandle page-type: web-api-interface status: - experimental browser-compat: api.MediaSourceHandle --- {{APIRef("Media Source Extensions")}}{{SeeCompatTable}} The **`MediaSourceHandle`** interface of the {{domxref("Media Source Extensions API", "Media Source Extensions API", "", "nocode")}} is a proxy for a {{domxref("MediaSource")}} that can be transferred from a dedicated worker back to the main thread and attached to a media element via its {{domxref("HTMLMediaElement.srcObject")}} property. `MediaSource` objects are not transferable because they are event targets, hence the need for `MediaSourceHandle`s. It can be accessed via the {{domxref("MediaSource.handle")}} property. Each `MediaSource` object created inside a dedicated worker has its own distinct `MediaSourceHandle`. The `MediaSource.handle` getter will always return the `MediaSourceHandle` instance specific to the associated dedicated worker `MediaSource` instance. If the handle has already been transferred to the main thread using {{domxref("DedicatedWorkerGlobalScope.postMessage()", "postMessage()")}}, the handle instance in the worker is technically detached and can't be transferred again. {{AvailableInWorkers}} ## Instance properties None. ## Instance methods None. ## Examples The {{domxref("MediaSource.handle", "handle")}} property can be accessed inside a dedicated worker and the resulting `MediaSourceHandle` object is then transferred over to the thread that created the worker (in this case the main thread) via a {{domxref("DedicatedWorkerGlobalScope.postMessage()", "postMessage()")}} call: ```js // Inside dedicated worker let mediaSource = new MediaSource(); let handle = mediaSource.handle; // Transfer the handle to the context that created the worker postMessage({ arg: handle }, [handle]); mediaSource.addEventListener("sourceopen", () => { // Await sourceopen on MediaSource before creating SourceBuffers // and populating them with fetched media — MediaSource won't // accept creation of SourceBuffers until it is attached to the // HTMLMediaElement and its readyState is "open" }); ``` Over in the main thread, we receive the handle via a {{domxref("Worker.message_event", "message")}} event handler, attach it to a {{htmlelement("video")}} via its {{domxref("HTMLMediaElement.srcObject")}} property, and {{domxref("HTMLMediaElement.play()", "play")}} the video: ```js worker.addEventListener("message", (msg) => { let mediaSourceHandle = msg.data.arg; video.srcObject = mediaSourceHandle; video.play(); }); ``` > **Note:** {{domxref("MediaSourceHandle")}}s cannot be successfully transferred into or via a shared worker or service worker. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [MSE-in-Workers Demo by Matt Wolenetz](https://wolenetz.github.io/mse-in-workers-demo/mse-in-workers-demo.html) - {{domxref("Media Source Extensions API", "Media Source Extensions API", "", "nocode")}} - {{domxref("MediaSource")}} - {{domxref("SourceBuffer")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/fontfaceset/index.md
--- title: FontFaceSet slug: Web/API/FontFaceSet page-type: web-api-interface browser-compat: api.FontFaceSet --- {{APIRef("CSS Font Loading API")}} The **`FontFaceSet`** interface of the [CSS Font Loading API](/en-US/docs/Web/API/CSS_Font_Loading_API) manages the loading of font-faces and querying of their download status. A `FontFaceSet` instance is a [`Set`-like object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_browser_apis) that can hold an ordered set of {{domxref("FontFace")}} objects. This property is available as {{domxref("Document.fonts")}}, or `self.fonts` in [web workers](/en-US/docs/Web/API/Web_Workers_API). {{InheritanceDiagram}} ## Instance properties - {{domxref("FontFaceSet.status")}} {{ReadOnlyInline}} - : Indicates the font-face's loading status. It will be one of `'loading'` or `'loaded'`. - {{domxref("FontFaceSet.ready")}} {{ReadOnlyInline}} - : {{jsxref("Promise")}} which resolves once font loading and layout operations have completed. - {{domxref("FontFaceSet.size")}} {{ReadOnlyInline}} - : Returns the number of values in the `FontFaceSet`. ### Events - {{domxref("FontFaceSet.loading_event", "loading")}} - : Fires when a font-face set has started loading. - {{domxref("FontFaceSet.loadingdone_event", "loadingdone")}} - : Fires when a font face set has finished loading. - {{domxref("FontFaceSet.loadingerror_event", "loadingerror")}} - : Fires when an error occurred whilst loading a font-face set. ## Instance methods - {{domxref("FontFaceSet.add","FontFaceSet.add()")}} - : Adds a font to the font set. - {{domxref("FontFaceSet.check","FontFaceSet.check()")}} - : A boolean value that indicates whether a font is loaded, but doesn't initiate a load when it isn't. - {{domxref("FontFaceSet.clear", "FontFaceSet.clear()")}} - : Removes all manually-added fonts from the font set. [CSS-connected](https://www.w3.org/TR/css-font-loading-3/#css-connected) fonts are unaffected. - {{domxref("FontFaceSet.delete","FontFaceSet.delete()")}} - : Removes a manually-added font from the font set. [CSS-connected](https://www.w3.org/TR/css-font-loading-3/#css-connected) fonts are unaffected. - {{domxref("FontFaceSet.entries","FontFaceSet.entries()")}} - : Returns a new iterator with the values for each element in the `FontFaceSet` in insertion order. - {{domxref("FontFaceSet.forEach","FontFaceSet.forEach()")}} - : Executes a provided function for each value in the `FontFaceSet` object. - {{domxref("FontFaceSet.has","FontFaceSet.has()")}} - : Returns a {{jsxref("Boolean")}} asserting whether an element is present with the given value. - {{domxref("FontFaceSet.keys","FontFaceSet.keys()")}} - : An alias for {{domxref("FontFaceSet.values()")}}. - {{domxref("FontFaceSet.load","FontFaceSet.load()")}} - : Returns a {{jsxref("Promise")}} which resolves to a list of font-faces for a requested font. - {{domxref("FontFaceSet.values","FontFaceSet.values()")}} - : Returns a new iterator object that yields the values for each element in the `FontFaceSet` object in insertion order. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/fontfaceset
data/mdn-content/files/en-us/web/api/fontfaceset/add/index.md
--- title: "FontFaceSet: add() method" short-title: add() slug: Web/API/FontFaceSet/add page-type: web-api-instance-method browser-compat: api.FontFaceSet.add --- {{APIRef("CSS Font Loading API")}} The **`add()`** method of the {{domxref("FontFaceSet")}} interface adds a new font to the set. ## Syntax ```js-nolint add(font) ``` ### Parameters - `font` - : A {{domxref("FontFace")}} to be added to the set. ### Return value A new {{domxref("FontFaceSet")}}. ### Exceptions - `InvalidModificationError` {{domxref("DOMException")}} - : Thrown if this font is already included via the CSS {{cssxref("@font-face")}} rule. ## Examples In the following example a new {{domxref("FontFace")}} object is created and then added to the {{domxref("FontFaceSet")}}. ```js const font = new FontFace("MyFont", "url(myFont.woff2)"); document.fonts.add(font); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/fontfaceset
data/mdn-content/files/en-us/web/api/fontfaceset/has/index.md
--- title: "FontFaceSet: has() method" short-title: has() slug: Web/API/FontFaceSet/has page-type: web-api-instance-method browser-compat: api.FontFaceSet.has --- {{APIRef("CSS Font Loading API")}} The **`has()`** method of the {{domxref("FontFaceSet")}} interface returns a {{jsxref("Boolean")}} asserting whether an element is present with the given value. ## Syntax ```js-nolint has(value) ``` ### Parameters - `value` - : The value to test for in the `FontFaceSet` object. ### Return value A {{jsxref("Boolean")}}, `true` if `value` exists in the `FontFaceSet`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0