repo_id
stringlengths 22
103
| file_path
stringlengths 41
147
| content
stringlengths 181
193k
| __index_level_0__
int64 0
0
|
---|---|---|---|
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/window_management_api/index.md | ---
title: Window Management API
slug: Web/API/Window_Management_API
page-type: web-api-overview
status:
- experimental
browser-compat: api.Window.getScreenDetails
spec-urls: https://w3c.github.io/window-management/
---
{{SeeCompatTable}}{{DefaultAPISidebar("Window Management API")}}
The **Window Management API** allows you to get detailed information on the displays connected to your device and more easily place windows on specific screens, paving the way towards more effective multi-screen applications.
## Concepts and usage
Historically, we have used {{domxref("Window.open()")}} to manage browser windows related to the current application β opening new windows, resizing and closing existing windows, etc. For example, to open a 400Γ300 window 50 pixels from the left and top of your screen:
```js
const myWindow = window.open(
"https://example.com/",
"myWindow",
"left=50,top=50,width=400,height=300",
);
```
You can retrieve information about your screen from the {{domxref("Window.screen")}} property, such as how much screen space you have available to place windows in.
However, the above features are limited. `Window.screen` only returns data about the primary screen, and not secondary displays available to a device. To move a window to a secondary display, you could use {{domxref("Window.moveTo()")}}, but you'd have to guess what coordinates to use based on where it is placed in your setup relative to the primary display.
The Window Management API provides more robust, flexible window management. It allows you to query whether your display is extended with multiple screens and get information on each screen separately: windows can then be placed on each screen as desired. It also provides event handlers to allow you to respond to changes in the available screens, new fullscreen functionality to choose which screen to put into fullscreen mode (if any), and permissions functionality to control access to the API.
For details on how to use it, see [Using the Window Management API](/en-US/docs/Web/API/Window_Management_API/Using).
> **Note:** In modern browsers, a separate user gesture event is required for each `Window.open()` call, for security purposes. This prevents sites from spamming users with lots of windows. However, this poses an issue for multi-window applications. To work around this limitation, you can design your applications to open no more than one new window at once, reuse existing windows to display different pages, or advise users on how to update their browser settings to allow multiple windows.
### Use cases
The Window Management API is useful in cases such as:
- Multi-window graphics editors and audio processors that may wish to arrange editing tools and panels across different screens.
- Virtual trading desks that want to show market trends in multiple windows and put specific windows of interest in fullscreen mode.
- Slideshow apps that want to show speaker notes on the internal primary screen and the presentation on an external projector.
## Permissions policy integration
The {{httpheader("Permissions-Policy/window-management", "window-management")}} [Permissions-Policy](/en-US/docs/Web/HTTP/Permissions_Policy) can be used to control permission to use the Window Management API. Specifically:
- Usage of the {{domxref("Window.getScreenDetails()")}} method. If blocked, its {{jsxref("Promise")}} will reject with a `NotAllowedError` exception.
- Querying the {{domxref("Screen.isExtended", "Window.screen.isExtended")}} property. If blocked, it will always return `false`.
Developers can explicitly grant permission for an {{htmlelement("iframe")}} to use Window Management via the `allow` attribute:
```html
<iframe src="3rd-party.example" allow="window-management"></iframe>
```
## Interfaces
- {{domxref("ScreenDetails")}} {{securecontext_inline}}
- : Represents the details of all the screens available to the user's device.
- {{domxref("ScreenDetailed")}} {{securecontext_inline}}
- : Represents detailed information about one specific screen available to the user's device.
### Extensions to other interfaces
- The `Screen` {{domxref("Screen.change_event", "change")}} event {{securecontext_inline}}
- : Fired on a specific screen when it changes in some way β for example available width or height, or orientation.
- {{domxref("Screen.isExtended")}} {{securecontext_inline}}
- : A boolean property that returns `true` if the user's device has multiple screens, and `false` if not.
- {{domxref("Element.requestFullscreen()")}}, the `screen` option
- : Specifies on which screen you want to put the element in fullscreen mode.
- {{domxref("Window.getScreenDetails()")}} {{securecontext_inline}}
- : Returns a {{jsxref("Promise")}} that fulfills with a {{domxref("ScreenDetails")}} object instance.
## Examples
You can find full examples here:
- [Basic multi-window learning environment](https://mdn.github.io/dom-examples/window-management-api/) (see the [source code](https://github.com/mdn/dom-examples/tree/main/window-management-api)).
- [Multi-window Platformer Game](https://googlechromelabs.github.io/multi-window-platformer-game/) (see the [source code](https://github.com/googlechromelabs/multi-window-platformer-game)).
- [Elmer-inspired trading desk demo](https://window-placement.glitch.me/) (see the [source code](https://glitch.com/edit/#!/window-placement)).
- [Window placement demo](https://michaelwasserman.github.io/window-placement-demo/) (see the [source code](https://github.com/michaelwasserman/window-placement-demo)).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/window_management_api | data/mdn-content/files/en-us/web/api/window_management_api/multi-screen_origin/index.md | ---
title: Multi-screen origin
slug: Web/API/Window_Management_API/Multi-screen_origin
page-type: guide
---
{{DefaultAPISidebar("Window Management API")}}
The [Window Management API](/en-US/docs/Web/API/Window_Management_API) introduces the concept of the **multi-screen origin** β this is the (0,0) coordinate of the host operating system (OS)'s virtual screen arrangement, around which all available screens and windows are positioned. The multi-screen origin is the top-left corner of the OS primary screen by convention, although the spec stipulates that it could be any arbitrary point within the virtual screen arrangement.
The primary screen can usually be specified by the user via OS settings, and generally contains OS UI features such as the taskbar/icon dock.
> **Note:** Positive coordinate values are to the right and downwards on the screen arrangement, while negative ones are to the left and upwards.
## Effects on existing web platform features
The multi-screen origin is relevant to the following APIs:
- The values of {{domxref("ScreenDetailed.left")}}, {{domxref("ScreenDetailed.top")}}, {{domxref("ScreenDetailed.availLeft")}}, and {{domxref("ScreenDetailed.availTop")}} for each available screen are reported relative to the multi-screen origin.
- The values of {{domxref("Window.screenLeft")}}, {{domxref("Window.screenTop")}}, {{domxref("Window.screenX")}}, {{domxref("Window.screenY")}} for each window are reported relative to the multi-screen origin.
- When using {{domxref("Window.moveTo()")}} and {{domxref("Window.open()")}}, windows are positioned relative to the multi-screen origin.
> **Note:** Not all browsers officially support multi-screen origin, but some have their own non-standard implementations. You are advised to check the browser compatibility information of the above features for the behavior in each browser.
## Visual examples
Say we have an external monitor of resolution 1920 x 1080 set as the primary monitor, and an internal laptop display of resolution 1440 x 900 set as a secondary monitor. Let's also say that the OS UI takes up 25px at the top of the screen, and is only drawn on the primary screen.
If the secondary screen was positioned directly to the right of the primary screen, top screen edges in line:
- The primary screen `left`/`top` values would be (0,0) while its `availLeft`/`availTop` values would be (0,25) β the OS UI thickness is added on.
- The secondary screen `left`/`top` values would be (1920,0) while its `availLeft`/`availTop` values would also be (1920,0) β the OS UI is not drawn on the secondary screen.
![Two rectangles representing the primary screen with the secondary screen positioned to the right, as described above](primary-screen-left.png)
However, if the secondary screen was positioned directly to the left of the primary screen, top screen edges in line:
- The primary screen `left`/`top` values would still be (0,0) while its `availLeft`/`availTop` values would be (0,25).
- The secondary screen `left`/`top` values would be (-1440,0) while its `availLeft`/`availTop` values would also be (-1440,0).
![Two rectangles representing the primary screen with the secondary screen positioned to the left, as described above](primary-screen-right.png)
| 0 |
data/mdn-content/files/en-us/web/api/window_management_api | data/mdn-content/files/en-us/web/api/window_management_api/multi-screen_origin/primary-screen-right-source.drawio | <mxfile host="app.diagrams.net" modified="2023-09-05T07:49:21.881Z" agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/118.0" etag="lmQSLavgyDMHSMtqWfgH" version="21.1.4" type="device">
<diagram name="Page-1" id="Gzl_CqcP1fjfskOx1EJc">
<mxGraphModel dx="1202" dy="614" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="3300" pageHeight="4681" math="0" shadow="0">
<root>
<mxCell id="0" />
<mxCell id="1" parent="0" />
<mxCell id="SDmlWv0pgotIPSEPmgka-19" value="" style="rounded=0;whiteSpace=wrap;html=1;" parent="1" vertex="1">
<mxGeometry x="360" width="640" height="300" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-1" value="" style="rounded=0;whiteSpace=wrap;html=1;" parent="1" vertex="1">
<mxGeometry x="640" y="80" width="320" height="180" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-2" value="" style="rounded=0;whiteSpace=wrap;html=1;" parent="1" vertex="1">
<mxGeometry x="400" y="80" width="240" height="140" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-6" value="" style="group" parent="1" vertex="1" connectable="0">
<mxGeometry x="380" y="60" width="40" height="40" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-7" value="" style="endArrow=none;html=1;rounded=0;strokeColor=#3333FF;strokeWidth=2;" parent="SDmlWv0pgotIPSEPmgka-6" edge="1">
<mxGeometry width="50" height="50" relative="1" as="geometry">
<mxPoint y="20" as="sourcePoint" />
<mxPoint x="40" y="20" as="targetPoint" />
</mxGeometry>
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-8" value="" style="endArrow=none;html=1;rounded=0;strokeColor=#3333FF;strokeWidth=2;" parent="SDmlWv0pgotIPSEPmgka-6" edge="1">
<mxGeometry width="50" height="50" relative="1" as="geometry">
<mxPoint x="20" as="sourcePoint" />
<mxPoint x="20" y="40" as="targetPoint" />
</mxGeometry>
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-9" value="" style="group" parent="1" vertex="1" connectable="0">
<mxGeometry x="620" y="60" width="40" height="40" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-3" value="" style="endArrow=none;html=1;rounded=0;strokeColor=#3333FF;strokeWidth=2;" parent="SDmlWv0pgotIPSEPmgka-9" edge="1">
<mxGeometry width="50" height="50" relative="1" as="geometry">
<mxPoint y="20" as="sourcePoint" />
<mxPoint x="40" y="20" as="targetPoint" />
</mxGeometry>
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-4" value="" style="endArrow=none;html=1;rounded=0;strokeColor=#3333FF;strokeWidth=2;" parent="SDmlWv0pgotIPSEPmgka-9" edge="1">
<mxGeometry width="50" height="50" relative="1" as="geometry">
<mxPoint x="20" as="sourcePoint" />
<mxPoint x="20" y="40" as="targetPoint" />
</mxGeometry>
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-10" value="<div align="left">Multi-screen origin and primary screen left/top: (0,0)<br></div>" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1">
<mxGeometry x="650" y="25" width="160" height="60" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-11" value="<div align="left">Secondary screen left/top and availLeft/availTop: (-1440,0)<br></div>" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1">
<mxGeometry x="410" y="25" width="170" height="60" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-12" value="" style="endArrow=none;html=1;rounded=0;" parent="1" edge="1">
<mxGeometry width="50" height="50" relative="1" as="geometry">
<mxPoint x="640" y="90" as="sourcePoint" />
<mxPoint x="960" y="90" as="targetPoint" />
</mxGeometry>
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-13" value="" style="group" parent="1" vertex="1" connectable="0">
<mxGeometry x="620" y="70" width="40" height="40" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-14" value="" style="endArrow=none;html=1;rounded=0;strokeColor=#3333FF;strokeWidth=2;" parent="SDmlWv0pgotIPSEPmgka-13" edge="1">
<mxGeometry width="50" height="50" relative="1" as="geometry">
<mxPoint y="20" as="sourcePoint" />
<mxPoint x="40" y="20" as="targetPoint" />
</mxGeometry>
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-15" value="" style="endArrow=none;html=1;rounded=0;strokeColor=#3333FF;strokeWidth=2;" parent="SDmlWv0pgotIPSEPmgka-13" edge="1">
<mxGeometry width="50" height="50" relative="1" as="geometry">
<mxPoint x="20" as="sourcePoint" />
<mxPoint x="20" y="40" as="targetPoint" />
</mxGeometry>
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-16" value="<div align="left">Primary screen availLeft/availTop: (0,25)<br></div>" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1">
<mxGeometry x="650" y="85" width="160" height="60" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-17" value="<font style="font-size: 20px;">1920 x 1080</font>" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1">
<mxGeometry x="735" y="155" width="130" height="30" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-18" value="1440 x 900" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;fontSize=20;" parent="1" vertex="1">
<mxGeometry x="455" y="135" width="130" height="30" as="geometry" />
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>
| 0 |
data/mdn-content/files/en-us/web/api/window_management_api | data/mdn-content/files/en-us/web/api/window_management_api/multi-screen_origin/primary-screen-left-source.drawio | <mxfile host="app.diagrams.net" modified="2023-09-05T07:39:16.948Z" agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/118.0" etag="zdt1ocIMYwY0P0IQihPp" version="21.1.4" type="device">
<diagram name="Page-1" id="Gzl_CqcP1fjfskOx1EJc">
<mxGraphModel dx="1202" dy="614" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0">
<root>
<mxCell id="0" />
<mxCell id="1" parent="0" />
<mxCell id="SDmlWv0pgotIPSEPmgka-19" value="" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="40" width="640" height="300" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-1" value="" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="80" y="80" width="320" height="180" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-2" value="" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="400" y="80" width="240" height="140" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-6" value="" style="group" vertex="1" connectable="0" parent="1">
<mxGeometry x="380" y="60" width="40" height="40" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-7" value="" style="endArrow=none;html=1;rounded=0;strokeColor=#3333FF;strokeWidth=2;" edge="1" parent="SDmlWv0pgotIPSEPmgka-6">
<mxGeometry width="50" height="50" relative="1" as="geometry">
<mxPoint y="20" as="sourcePoint" />
<mxPoint x="40" y="20" as="targetPoint" />
</mxGeometry>
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-8" value="" style="endArrow=none;html=1;rounded=0;strokeColor=#3333FF;strokeWidth=2;" edge="1" parent="SDmlWv0pgotIPSEPmgka-6">
<mxGeometry width="50" height="50" relative="1" as="geometry">
<mxPoint x="20" as="sourcePoint" />
<mxPoint x="20" y="40" as="targetPoint" />
</mxGeometry>
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-9" value="" style="group" vertex="1" connectable="0" parent="1">
<mxGeometry x="60" y="60" width="40" height="40" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-3" value="" style="endArrow=none;html=1;rounded=0;strokeColor=#3333FF;strokeWidth=2;" edge="1" parent="SDmlWv0pgotIPSEPmgka-9">
<mxGeometry width="50" height="50" relative="1" as="geometry">
<mxPoint y="20" as="sourcePoint" />
<mxPoint x="40" y="20" as="targetPoint" />
</mxGeometry>
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-4" value="" style="endArrow=none;html=1;rounded=0;strokeColor=#3333FF;strokeWidth=2;" edge="1" parent="SDmlWv0pgotIPSEPmgka-9">
<mxGeometry width="50" height="50" relative="1" as="geometry">
<mxPoint x="20" as="sourcePoint" />
<mxPoint x="20" y="40" as="targetPoint" />
</mxGeometry>
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-10" value="<div align="left">Multi-screen origin and primary screen left/top: (0,0)<br></div>" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">
<mxGeometry x="90" y="25" width="160" height="60" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-11" value="<div align="left">Secondary screen left/top and availLeft/availTop: (1920,0)<br></div>" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">
<mxGeometry x="410" y="25" width="170" height="60" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-12" value="" style="endArrow=none;html=1;rounded=0;" edge="1" parent="1">
<mxGeometry width="50" height="50" relative="1" as="geometry">
<mxPoint x="80" y="90" as="sourcePoint" />
<mxPoint x="400" y="90" as="targetPoint" />
</mxGeometry>
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-13" value="" style="group" vertex="1" connectable="0" parent="1">
<mxGeometry x="60" y="70" width="40" height="40" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-14" value="" style="endArrow=none;html=1;rounded=0;strokeColor=#3333FF;strokeWidth=2;" edge="1" parent="SDmlWv0pgotIPSEPmgka-13">
<mxGeometry width="50" height="50" relative="1" as="geometry">
<mxPoint y="20" as="sourcePoint" />
<mxPoint x="40" y="20" as="targetPoint" />
</mxGeometry>
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-15" value="" style="endArrow=none;html=1;rounded=0;strokeColor=#3333FF;strokeWidth=2;" edge="1" parent="SDmlWv0pgotIPSEPmgka-13">
<mxGeometry width="50" height="50" relative="1" as="geometry">
<mxPoint x="20" as="sourcePoint" />
<mxPoint x="20" y="40" as="targetPoint" />
</mxGeometry>
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-16" value="<div align="left">Primary screen availLeft/availTop: (0,25)<br></div>" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">
<mxGeometry x="90" y="85" width="160" height="60" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-17" value="<font style="font-size: 20px;">1920 x 1080</font>" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">
<mxGeometry x="175" y="155" width="130" height="30" as="geometry" />
</mxCell>
<mxCell id="SDmlWv0pgotIPSEPmgka-18" value="1440 x 900" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;fontSize=20;" vertex="1" parent="1">
<mxGeometry x="455" y="135" width="130" height="30" as="geometry" />
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>
| 0 |
data/mdn-content/files/en-us/web/api/window_management_api | data/mdn-content/files/en-us/web/api/window_management_api/using/index.md | ---
title: Using the Window Management API
slug: Web/API/Window_Management_API/Using
page-type: guide
---
{{DefaultAPISidebar("Window Management API")}}
This guide explains how to use the [Window Management API](/en-US/docs/Web/API/Window_Management_API). The example code seen below is taken from our [Multi-window learning environment](https://mdn.github.io/dom-examples/window-management-api/) example (see the [source code](https://github.com/mdn/dom-examples/tree/main/window-management-api)).
## Feature detection
You can feature detect the Window Management API by checking for the existence of `getScreenDetails` in the current `window` instance. For example, you might want to provide a button to open a multi-window display if the API is supported, or a different experience such as creating links to the different pages if it isn't:
```js
if ("getScreenDetails" in window) {
// The Window Management API is supported
createButton();
} else {
// The Window Management API is not supported
createLinks(sites);
}
```
## Basic usage
The core of the Windows Management API is the {{domxref("Window.getScreenDetails()")}} method, which returns an object containing details of all the screens available to the user's system:
```js
const screenDetails = await window.getScreenDetails();
// Return the number of screens
const noOfScreens = screenDetails.screens.length;
```
When `getScreenDetails()` is invoked, the user will be asked for permission to manage windows on all their displays (the status of this permission can be checked using {{domxref("Permissions.query()")}} to query `window-management`). If the user grants permission, a {{domxref("ScreenDetails")}} object is returned. This object contains the following properties:
- `screens`: An array of {{domxref("ScreenDetailed")}} objects, each one containing detailed information about a separate screen available to the system (see below). This array is also useful for determining the number of available screens, via `screens.length`.
- `currentScreen`: A single {{domxref("ScreenDetailed")}} object containing detailed information about the screen that the current browser window is displayed in.
{{domxref("ScreenDetailed")}} objects inherit the properties of the {{domxref("Screen")}} interface, and contain useful information for placing windows on specific screens.
> **Note:** You can gate functionality based on whether the user has more than one screen available using the {{domxref("Screen.isExtended", "Window.screen.isExtended")}} property. This returns `true` if the device has multiple screens, and `false` if not.
### Opening windows
You'll still need to use {{domxref("Window.open()")}} to open and manage windows, but the above provides you with better information for doing so in a multi-screen environment. For example, a utility function might look like so:
```js
// Array to hold references to the currently open windows
let windowRefs = [];
// ...
function openWindow(left, top, width, height, url) {
const windowFeatures = `left=${left},top=${top},width=${width},height=${height}`;
const windowRef = window.open(
url,
"_blank", // needed for it to open in a new window
windowFeatures,
);
if (windowRef === null) {
// If the browser is blocking new windows, close any windows that were
// able to open and display instructions to help the user fix this problem
closeAllWindows();
popoverElem.showPopover();
} else {
// Store a reference to the window in the windowRefs array
windowRefs.push(windowRef);
}
}
```
You would then invoke this function and open windows on specific screens like this:
```js
const screen1 = screenDetails.screens[0];
const screen2 = screenDetails.screens[1];
// Windows will be a third the width and the full height of the screen
// The available width of screen1, minus 3 times the horizontal browser chrome
// width, divided by 3
const windowWidth = Math.floor((screen1.availWidth - 3 * WINDOW_CHROME_X) / 3);
// The available height of screen1, minus the vertical browser chrome width
const windowHeight = Math.floor(screen1.availHeight - WINDOW_CHROME_Y);
// Open a window a third of the width and the entire height of the primary screen
openWindow(
screen1.availLeft,
screen1.availTop,
windowWidth,
windowHeight,
sites[1].url,
);
// ...
```
### Closing all windows
After opening each window, we add a reference to the `windowRefs` array. This allows you to, for example, close them all when one window is closed:
```js
function closeAllWindows() {
// Loop through all window refs and close each one
windowRefs.forEach((windowRef) => {
windowRef.close();
});
windowRefs = [];
}
// Check whether one of our popup windows has been closed
// If so, close them all
closeMonitor = setInterval(checkWindowClose, 250);
function checkWindowClose() {
if (windowRefs.some((windowRef) => windowRef.closed)) {
closeAllWindows();
clearInterval(closeMonitor);
}
}
```
> **Note:** In our experiments, the {{domxref("setInterval()")}} polling method shown above seemed to work best for detecting window closure in the case of multiple windows. Using events such as {{domxref("Window.beforeunload_event", "beforeunload")}}, {{domxref("Window.pagehide_event", "pagehide")}}, or {{domxref("Document.visibilitychange_event", "visibilitychange")}} proved unreliable because, when opening multiple windows at the same time, the rapid shift in focus/visibility seemed to fire the handler function prematurely.
> **Note:** One concern with the above example is that it uses constant values to represent the size of the Chrome window UI portions in the calculations β `WINDOW_CHROME_X` and `WINDOW_CHROME_Y` β to get the window size calculations correct. To create precisely-sized windows on other future implementations of the API, you'd need to keep a small library of browser chrome sizes, and employ browser detection to discover which browser is rendering your app and choose the correct size for calculations. Or you can rely on less precise window sizes.
### Handling browser popup blockers
In modern browsers, a separate user gesture event is required for each `Window.open()` call, for security purposes. This prevents sites from spamming users with lots of windows. However, this poses an issue for multi-window applications. To work around this limitation, you can design your applications to:
- Open no more than one new window at once.
- Reuse existing windows to display different pages.
- Advise users on how to update their browser settings to allow multiple windows.
In our demo application, we have gone for the third option. Our `openWindow()` function contains the following section:
```js
// ...
if (windowRef === null) {
// If the browser is blocking new windows, close any windows that were
// able to open and display instructions to help the user fix this problem
closeAllWindows();
popoverElem.showPopover();
} else {
// Store a reference to the window in the windowRefs array
windowRefs.push(windowRef);
}
// ...
```
If the browser blocks a new window, the resulting `windowRef` will be `null`. In this case we run our `closeAllWindows()` function to close any windows that _did_ manage to open before the blocking started, and show a [popover element](/en-US/docs/Web/API/Popover_API) that explains how to disable the popup blocker.
## Simple single-window per display case
If you want to open a single window on each available display that is the full width and height of the display, you could use a pattern like this:
```js
// Open a window on each screen of the device
for (const screen of screenDetails.screens) {
openWindow(
screen.availLeft,
screen.availTop,
screen.availWidth,
screen.availHeight,
url,
);
}
```
## Window management events
The Window Management API provides some events for responding to changes in the available screens:
- The `ScreenDetails` {{domxref("ScreenDetails.screenschange_event", "screenschange")}} event
- : Fired when screens are connected to or disconnected from the system.
- The `ScreenDetails` {{domxref("ScreenDetails.currentscreenchange_event", "currentscreenchange")}} event
- : Fired when the window's current screen changes in some way.
- The `Screen` {{domxref("Screen.change_event", "change")}} event
- : Fired on a specific screen when it changes in some way.
So for example, you could use the `screenschange` event to detect when the available screens have changed (perhaps when a screen is plugged in or unplugged), report the change, close all windows, and update window arrangements to suit the new configuration:
```js
screenDetails.addEventListener("screenschange", () => {
// If the new number of screens is different to the old number of screens,
// report the difference
if (screenDetails.screens.length !== noOfScreens) {
console.log(
`The screen count changed from ${noOfScreens} to ${screenDetails.screens.length}`,
);
}
// If the windows are open, close them and then open them again
// So that they fit with the new screen configuration
if (windowRefs.length > 0) {
closeAllWindows();
openWindows();
}
});
```
## requestFullscreen() screen option
The Window Management API adds a new `screen` option to the {{domxref("Element.requestFullscreen", "requestFullscreen()")}} method that allows you to specify on which screen you want to put the element in fullscreen mode. For example, if you want to make it fullscreen on the primary OS screen:
```js
try {
const primaryScreen = (await getScreenDetails()).screens.find(
(screen) => screen.isPrimary,
);
await document.body.requestFullscreen({ screen: primaryScreen });
} catch (err) {
console.error(err.name, err.message);
}
```
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/idbopendbrequest/index.md | ---
title: IDBOpenDBRequest
slug: Web/API/IDBOpenDBRequest
page-type: web-api-interface
browser-compat: api.IDBOpenDBRequest
---
{{APIRef("IndexedDB")}}
The **`IDBOpenDBRequest`** interface of the IndexedDB API provides access to the results of requests to open or delete databases (performed using {{domxref("IDBFactory.open")}} and {{domxref("IDBFactory.deleteDatabase")}}), using specific event handler attributes.
{{AvailableInWorkers}}
{{InheritanceDiagram}}
## Instance properties
_Also inherits properties from its parents {{domxref("IDBRequest")}} and {{domxref("EventTarget")}}_.
## Instance methods
_No methods, but inherits methods from its parents {{domxref("IDBRequest")}} and {{domxref("EventTarget")}}._
## Events
_Events defined on parent interfaces, {{DOMxRef("IDBRequest")}} and {{DOMxRef("EventTarget")}}, can also be dispatched on `IDBOpenDBRequest` objects._
Listen to these generic and specific events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.
Events specific to this interface are:
- [`blocked`](/en-US/docs/Web/API/IDBOpenDBRequest/blocked_event)
- : Fired when an open connection to a database is blocking a `versionchange` transaction on the same database. Also available via the [`onblocked`](/en-US/docs/Web/API/IDBOpenDBRequest/blocked_event) property.
- [`upgradeneeded`](/en-US/docs/Web/API/IDBOpenDBRequest/upgradeneeded_event)
- : Fired when an attempt was made to open a database with a version number higher than its current version. Also available via the [`onupgradeneeded`](/en-US/docs/Web/API/IDBOpenDBRequest/upgradeneeded_event) property.
## Example
In the following example you can see the onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded. For a full working example, see our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app ([view example live](https://mdn.github.io/dom-examples/to-do-notifications/).)
```js
let db;
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
// these event handlers act on the database being opened.
DBOpenRequest.onerror = (event) => {
note.innerHTML += "<li>Error loading database.</li>";
};
DBOpenRequest.onsuccess = (event) => {
note.innerHTML += "<li>Database initialized.</li>";
// store the result of opening the database in the db
// variable. This is used a lot below
db = DBOpenRequest.result;
// Run the displayData() function to populate the task
// list with all the to-do list data already in the IDB
displayData();
};
// This event handles the event whereby a new version of
// the database needs to be created Either one has not
// been created before, or a new version number has been
// submitted via the window.indexedDB.open line above
// it is only implemented in recent browsers
DBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
db.onerror = (event) => {
note.innerHTML += "<li>Error loading database.</li>";
};
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
objectStore.createIndex("notified", "notified", { unique: false });
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
- Starting transactions: {{domxref("IDBDatabase")}}
- Using transactions: {{domxref("IDBTransaction")}}
- Setting a range of keys: {{domxref("IDBKeyRange")}}
- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
- Using cursors: {{domxref("IDBCursor")}}
- Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
| 0 |
data/mdn-content/files/en-us/web/api/idbopendbrequest | data/mdn-content/files/en-us/web/api/idbopendbrequest/blocked_event/index.md | ---
title: "IDBOpenDBRequest: blocked event"
short-title: blocked
slug: Web/API/IDBOpenDBRequest/blocked_event
page-type: web-api-event
browser-compat: api.IDBOpenDBRequest.blocked_event
---
{{APIRef("IndexedDB")}}
The `blocked` handler is executed when an open connection to a database is blocking a `versionchange` transaction on the same database.
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("blocked", (event) => {});
onblocked = (event) => {};
```
## Event type
An {{domxref("IDBVersionChangeEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("IDBVersionChangeEvent")}}
## Event properties
_Also inherits properties from its parent, {{domxref("Event")}} interface._
- {{ domxref("IDBVersionChangeEvent.oldVersion") }} {{ReadOnlyInline}}
- : Returns the old version of the database.
- {{ domxref("IDBVersionChangeEvent.newVersion") }} {{ReadOnlyInline}}
- : Returns the new version of the database.
## Examples
Using `addEventListener()`:
```js
// Open the database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
db.onerror = () => {
console.log("Error creating database");
};
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
};
DBOpenRequest.onsuccess = (event) => {
// Let's try to open the same database with a higher revision version
const req2 = indexedDB.open("toDoList", 5);
// In this case the onblocked handler will be executed
req2.addEventListener("blocked", () => {
console.log("Request was blocked");
});
};
```
Using the `onblocked` property:
```js
// Open the database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
db.onerror = () => {
console.log("Error creating database");
};
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
};
DBOpenRequest.onsuccess = (event) => {
// Let's try to open the same database with a higher revision version
const req2 = indexedDB.open("toDoList", 5);
// In this case the onblocked handler will be executed
req2.onblocked = () => {
console.log("Request was blocked");
};
};
```
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
| 0 |
data/mdn-content/files/en-us/web/api/idbopendbrequest | data/mdn-content/files/en-us/web/api/idbopendbrequest/upgradeneeded_event/index.md | ---
title: "IDBOpenDBRequest: upgradeneeded event"
short-title: upgradeneeded
slug: Web/API/IDBOpenDBRequest/upgradeneeded_event
page-type: web-api-event
browser-compat: api.IDBOpenDBRequest.upgradeneeded_event
---
{{APIRef("IndexedDB")}}
The `upgradeneeded` event is fired when an attempt was made to open a database with a version number higher than its current version.
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("upgradeneeded", (event) => {});
onupgradeneeded = (event) => {};
```
## Event type
An {{domxref("IDBVersionChangeEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("IDBVersionChangeEvent")}}
## Event properties
_Also inherits properties from its parent, {{domxref("Event")}} interface._
- {{ domxref("IDBVersionChangeEvent.oldVersion") }} {{ReadOnlyInline}}
- : Returns the old version of the database.
- {{ domxref("IDBVersionChangeEvent.newVersion") }} {{ReadOnlyInline}}
- : Returns the new version of the database.
## Examples
This example opens a database and handles the `upgradeneeded` event by making any necessary updates to the object store.
```js
// Open the database
const dBOpenRequest = window.indexedDB.open("toDoList", 4);
dBOpenRequest.addEventListener("upgradeneeded", (event) => {
const db = event.target.result;
console.log(`Upgrading to version ${db.version}`);
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
});
```
This is the same example, but uses the onupgradeneeded event handler property.
```js
// Open the database
const dBOpenRequest = window.indexedDB.open("toDoList", 4);
dBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
console.log(`Upgrading to version ${db.version}`);
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
};
```
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/rtcidentityassertion/index.md | ---
title: RTCIdentityAssertion
slug: Web/API/RTCIdentityAssertion
page-type: web-api-interface
status:
- experimental
browser-compat: api.RTCIdentityAssertion
---
{{APIRef("WebRTC")}}{{SeeCompatTable}}
The **`RTCIdentityAssertion`** interface of the [WebRTC API](/en-US/docs/Web/API/WebRTC_API) represents the identity of a remote peer of the current connection. If no peer has yet been set and verified, then this interface returns `null`. Once set it can't be changed.
## Instance properties
- {{domxref("RTCIdentityAssertion.idp")}} {{Experimental_Inline}}
- : Indicates the provider of the identity assertion.
- {{domxref("RTCIdentityAssertion.name")}} {{Experimental_Inline}}
- : Indicates the name of the identity assertion provider.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/rtcsessiondescription/index.md | ---
title: RTCSessionDescription
slug: Web/API/RTCSessionDescription
page-type: web-api-interface
browser-compat: api.RTCSessionDescription
---
{{APIRef("WebRTC")}}
The **`RTCSessionDescription`** interface describes one end of a connectionβor potential connectionβand how it's configured. Each `RTCSessionDescription` consists of a description {{domxref("RTCSessionDescription.type", "type")}} indicating which part of the offer/answer negotiation process it describes and of the {{Glossary("SDP")}} descriptor of the session.
The process of negotiating a connection between two peers involves exchanging `RTCSessionDescription` objects back and forth, with each description suggesting one combination of connection configuration options that the sender of the description supports. Once the two peers agree upon a configuration for the connection, negotiation is complete.
## Instance properties
_The `RTCSessionDescription` interface doesn't inherit any properties._
- {{domxref("RTCSessionDescription.type")}} {{ReadOnlyInline}}
- : An enum describing the session description's type.
- {{domxref("RTCSessionDescription.sdp")}} {{ReadOnlyInline}}
- : A string containing the {{Glossary("SDP")}} describing the session.
## Instance methods
_The `RTCSessionDescription` doesn't inherit any methods._
- {{domxref("RTCSessionDescription.RTCSessionDescription", "RTCSessionDescription()")}} {{deprecated_inline}}
- : This constructor returns a new `RTCSessionDescription`. The parameter is a `RTCSessionDescriptionInit` dictionary containing the values to assign the two properties.
- {{domxref("RTCSessionDescription.toJSON()")}}
- : Returns a {{Glossary("JSON")}} description of the object. The values of both properties, {{domxref("RTCSessionDescription.type", "type")}} and {{domxref("RTCSessionDescription.sdp", "sdp")}}, are contained in the generated JSON.
## Example
```js
signalingChannel.onmessage = (evt) => {
if (!pc) start(false);
const message = JSON.parse(evt.data);
if (message.sdp) {
pc.setRemoteDescription(
new RTCSessionDescription(message),
() => {
// if we received an offer, we need to answer
if (pc.remoteDescription.type === "offer") {
pc.createAnswer(localDescCreated, logError);
}
},
logError,
);
} else {
pc.addIceCandidate(
new RTCIceCandidate(message.candidate),
() => {},
logError,
);
}
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
- {{domxref("RTCPeerConnection.setLocalDescription()")}} and {{domxref("RTCPeerConnection.setRemoteDescription()")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcsessiondescription | data/mdn-content/files/en-us/web/api/rtcsessiondescription/sdp/index.md | ---
title: "RTCSessionDescription: sdp property"
short-title: sdp
slug: Web/API/RTCSessionDescription/sdp
page-type: web-api-instance-property
browser-compat: api.RTCSessionDescription.sdp
---
{{APIRef("WebRTC")}}
The property **`RTCSessionDescription.sdp`** is a read-only
string containing the {{Glossary("SDP")}} which describes the session.
## Syntax
```js-nolint
const value = sessionDescription.sdp
sessionDescription.sdp = value
```
### Value
The value is a string containing an SDP message like this one:
```plain
v=0
o=alice 2890844526 2890844526 IN IP4 host.anywhere.com
s=
c=IN IP4 host.anywhere.com
t=0 0
m=audio 49170 RTP/AVP 0
a=rtpmap:0 PCMU/8000
m=video 51372 RTP/AVP 31
a=rtpmap:31 H261/90000
m=video 53000 RTP/AVP 32
a=rtpmap:32 MPV/90000
```
## Example
```js
// The remote description has been set previously on pc, an RTCPeerConnection
alert(pc.remoteDescription.sdp);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
- The standard for using SDP in an offer/answer protocol {{rfc("3264")}}.
| 0 |
data/mdn-content/files/en-us/web/api/rtcsessiondescription | data/mdn-content/files/en-us/web/api/rtcsessiondescription/rtcsessiondescription/index.md | ---
title: "RTCSessionDescription: RTCSessionDescription() constructor"
short-title: RTCSessionDescription()
slug: Web/API/RTCSessionDescription/RTCSessionDescription
page-type: web-api-constructor
status:
- deprecated
browser-compat: api.RTCSessionDescription.RTCSessionDescription
---
{{APIRef("WebRTC")}}{{deprecated_header}}
The **`RTCSessionDescription()`** constructor creates a new
{{domxref("RTCSessionDescription")}} with its properties initialized as described in the
specified object.
> **Note:** This constructor has been deprecated because
> {{domxref("RTCPeerConnection.setLocalDescription()")}} and other methods which take
> SDP as input now directly accept an object conforming to the
> `RTCSessionDescriptionInit` dictionary, so you don't have to instantiate an
> `RTCSessionDescription` yourself.
## Syntax
```js-nolint
new RTCSessionDescription(options)
```
### Values
- `options` {{optional_inline}}
- : An object providing the default values for the session description; the object
conforms to the `RTCSessionDescriptionInit` dictionary. That dictionary has
the following properties:
- `type`
- : **Required.** A string which is used to set the `type` property of the new `RTCSessionDescription` object.
- `sdp`
- : A string containing a {{Glossary("SDP")}} message describing the session. This value is an empty string (`""`) by default and may not be `null`.
## Example
This example uses the constructor to convert an SDP offer into an
`RTCSessionDescription` object.
> **Note:** This is no longer necessary, however;
> {{domxref("RTCPeerConnection.setLocalDescription()")}} and other methods which take
> SDP as input now directly accept an object conforming to the
> `RTCSessionDescriptionInit` dictionary, so you don't have to instantiate an
> `RTCSessionDescription` yourself.
```js
navigator.getUserMedia({ video: true }, (stream) => {
pc.onaddstream({ stream });
// Adding a local stream won't trigger the onaddstream callback
pc.addStream(stream);
pc.createOffer((offer) => {
pc.setLocalDescription(
new RTCSessionDescription(offer),
() => {
// send the offer to a server to be forwarded to the friend you're calling.
},
error,
);
}, error);
});
```
## Specifications
This feature is not part of any current specification. It is no longer on track to become a standard.
## Browser compatibility
{{Compat}}
## See also
- [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
- {{domxref("RTCSessionDescription")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcsessiondescription | data/mdn-content/files/en-us/web/api/rtcsessiondescription/type/index.md | ---
title: "RTCSessionDescription: type property"
short-title: type
slug: Web/API/RTCSessionDescription/type
page-type: web-api-instance-property
browser-compat: api.RTCSessionDescription.type
---
{{APIRef("WebRTC")}}
The property **`RTCSessionDescription.type`** is a read-only
string value which describes the description's type.
## Syntax
```js-nolint
const value = sessionDescription.type
sessionDescription.type = value
```
### Value
The possible values are:
- `"answer"`
- : The SDP contained in the {{domxref("RTCSessionDescription.sdp", "sdp")}} property is the definitive choice in the exchange. In other words, this session description describes the agreed-upon configuration, and is being sent to finalize negotiation.
- `"offer"`
- : The session description object describes the initial proposal in an offer/answer exchange. The session negotiation process begins with an offer being sent from the caller to the callee.
- `"pranswer"`
- : The session description object describes a provisional answer; that is, a response to a previous offer that is not the final answer. It is usually employed by legacy hardware.
- `"rollback"`
- : This special type with an empty session description is used to roll back to the previous stable state.
## Example
```js
// The remote description has been set previously on pc, a RTCPeerConnection
alert(pc.remoteDescription.type);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
| 0 |
data/mdn-content/files/en-us/web/api/rtcsessiondescription | data/mdn-content/files/en-us/web/api/rtcsessiondescription/tojson/index.md | ---
title: "RTCSessionDescription: toJSON() method"
short-title: toJSON()
slug: Web/API/RTCSessionDescription/toJSON
page-type: web-api-instance-method
browser-compat: api.RTCSessionDescription.toJSON
---
{{APIRef("WebRTC")}}
The **`RTCSessionDescription.toJSON()`** method generates a
{{Glossary("JSON")}} description of the object. Both properties,
{{domxref("RTCSessionDescription.type", "type")}} and
{{domxref("RTCSessionDescription.sdp", "sdp")}}, are contained in the generated JSON.
## Syntax
```js-nolint
toJSON()
```
### Parameters
None.
### Return value
A {{jsxref("JSON")}} object containing the following properties:
- `type`
- : One of the following: `"offer"`, `"answer"`, `"pranswer"` or `null`.
- `sdp`
- : Either `null` or the {{Glossary("SDP")}} message string corresponding to {{domxref("RTCSessionDescription.sdp")}} property.
## Example
```js
// sd is a RTCSessionDescriptor
alert(JSON.stringify(sd)); // This call the toJSON() method behind the scene.
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/ext_blend_minmax/index.md | ---
title: EXT_blend_minmax extension
short-title: EXT_blend_minmax
slug: Web/API/EXT_blend_minmax
page-type: webgl-extension
browser-compat: api.EXT_blend_minmax
---
{{APIRef("WebGL")}}
The **`EXT_blend_minmax`** extension is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and extends blending capabilities by adding two new blend equations: the minimum or maximum color components of the source and destination colors.
WebGL extensions are available using the {{domxref("WebGLRenderingContext.getExtension()")}} method. For more information, see also [Using Extensions](/en-US/docs/Web/API/WebGL_API/Using_Extensions) in the [WebGL tutorial](/en-US/docs/Web/API/WebGL_API/Tutorial).
> **Note:** This extension is only available to {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}} contexts. In {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}}, the functionality of this extension is available on the WebGL2 context by default. The constants in WebGL2 are `gl.MIN` and `gl.MAX`.
## Constants
This extension adds two new constants, which can be used in {{domxref("WebGLRenderingContext.blendEquation()")}} and {{domxref("WebGLRenderingContext.blendEquationSeparate()")}}:
- `ext.MIN_EXT`
- : Produces the minimum color components of the source and destination colors.
- `ext.MAX_EXT`
- : Produces the maximum color components of the source and destination colors.
## Examples
```js
const ext = gl.getExtension("EXT_blend_minmax");
gl.blendEquation(ext.MIN_EXT);
gl.blendEquation(ext.MAX_EXT);
gl.blendEquationSeparate(ext.MIN_EXT, ext.MAX_EXT);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("WebGLRenderingContext.getExtension()")}}
- {{domxref("WebGLRenderingContext.blendEquation()")}}
- {{domxref("WebGLRenderingContext.blendEquationSeparate()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/webtransportdatagramduplexstream/index.md | ---
title: WebTransportDatagramDuplexStream
slug: Web/API/WebTransportDatagramDuplexStream
page-type: web-api-interface
browser-compat: api.WebTransportDatagramDuplexStream
---
{{APIRef("WebTransport API")}}{{SecureContext_Header}}
The **`WebTransportDatagramDuplexStream`** interface of the {{domxref("WebTransport API", "WebTransport API", "", "nocode")}} represents a duplex stream that can be used for unreliable transport of datagrams between client and server. Provides access to a {{domxref("ReadableStream")}} for reading incoming datagrams, a {{domxref("WritableStream")}} for writing outgoing datagrams, and various settings and statistics related to the stream.
This is accessed via the {{domxref("WebTransport.datagrams")}} property.
"Unreliable" means that transmission of data is not guaranteed, nor is arrival in a specific order. This is fine in some situations and provides very fast delivery. For example, you might want to transmit regular game state updates where each message supersedes the last one that arrives, and order is not important.
{{InheritanceDiagram}}
{{AvailableInWorkers}}
## Instance properties
- {{domxref("WebTransportDatagramDuplexStream.incomingHighWaterMark", "incomingHighWaterMark")}}
- : Gets or sets the high water mark for incoming chunks of data β this is the maximum size, in chunks, that the incoming {{domxref("ReadableStream")}}'s internal queue can reach before it is considered full. See [Internal queues and queuing strategies](/en-US/docs/Web/API/Streams_API/Concepts#internal_queues_and_queuing_strategies) for more information.
- {{domxref("WebTransportDatagramDuplexStream.incomingMaxAge", "incomingMaxAge")}}
- : Gets or sets the maximum age for incoming datagrams, in milliseconds. Returns `null` if no maximum age has been set.
- {{domxref("WebTransportDatagramDuplexStream.maxDatagramSize", "maxDatagramSize")}} {{ReadOnlyInline}}
- : Returns the maximum allowable size of outgoing datagrams, in bytes, that can be written to {{domxref("WebTransportDatagramDuplexStream.writable", "writable")}}.
- {{domxref("WebTransportDatagramDuplexStream.outgoingHighWaterMark", "outgoingHighWaterMark")}}
- : Gets or sets the high water mark for outgoing chunks of data β this is the maximum size, in chunks, that the outgoing {{domxref("WritableStream")}}'s internal queue can reach before it is considered full. See [Internal queues and queuing strategies](/en-US/docs/Web/API/Streams_API/Concepts#internal_queues_and_queuing_strategies) for more information.
- {{domxref("WebTransportDatagramDuplexStream.outgoingMaxAge", "outgoingMaxAge")}}
- : Gets or sets the maximum age for outgoing datagrams, in milliseconds. Returns `null` if no maximum age has been set.
- {{domxref("WebTransportDatagramDuplexStream.readable", "readable")}} {{ReadOnlyInline}}
- : Returns a {{domxref("ReadableStream")}} instance that can be used to read incoming datagrams from the stream.
- {{domxref("WebTransportDatagramDuplexStream.writable", "writable")}} {{ReadOnlyInline}}
- : Returns a {{domxref("WritableStream")}} instance that can be used to write outgoing datagrams to the stream.
## Examples
### Writing outgoing datagrams
The {{domxref("WebTransportDatagramDuplexStream.writable", "writable")}} property returns a {{domxref("WritableStream")}} object that you can write data to using a writer, for transmission to the server:
```js
const writer = transport.datagrams.writable.getWriter();
const data1 = new Uint8Array([65, 66, 67]);
const data2 = new Uint8Array([68, 69, 70]);
writer.write(data1);
writer.write(data2);
```
### Reading incoming datagrams
The {{domxref("WebTransportDatagramDuplexStream.readable", "readable")}} property returns a {{domxref("ReadableStream")}} object that you can use to receive data from the server:
```js
async function readData() {
const reader = transport.datagrams.readable.getReader();
while (true) {
const { value, done } = await reader.read();
if (done) {
break;
}
// value is a Uint8Array.
console.log(value);
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api/webtransportdatagramduplexstream | data/mdn-content/files/en-us/web/api/webtransportdatagramduplexstream/readable/index.md | ---
title: "WebTransportDatagramDuplexStream: readable property"
short-title: readable
slug: Web/API/WebTransportDatagramDuplexStream/readable
page-type: web-api-instance-property
browser-compat: api.WebTransportDatagramDuplexStream.readable
---
{{APIRef("WebTransport API")}}{{SecureContext_Header}}
The **`readable`** read-only property of the {{domxref("WebTransportDatagramDuplexStream")}} interface returns a {{domxref("ReadableStream")}} instance that can be used to unreliably read incoming datagrams from the stream.
"Unreliably" means that transmission of data is not guaranteed, nor is arrival in a specific order. This is fine in some situations and provides very fast delivery. For example, you might want to transmit regular game state updates where each message supersedes the last one that arrives, and order is not important.
{{AvailableInWorkers}}
## Value
A {{domxref("ReadableStream")}}.
## Examples
See the main {{domxref("WebTransportDatagramDuplexStream")}} interface page.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api/webtransportdatagramduplexstream | data/mdn-content/files/en-us/web/api/webtransportdatagramduplexstream/incomingmaxage/index.md | ---
title: "WebTransportDatagramDuplexStream: incomingMaxAge property"
short-title: incomingMaxAge
slug: Web/API/WebTransportDatagramDuplexStream/incomingMaxAge
page-type: web-api-instance-property
browser-compat: api.WebTransportDatagramDuplexStream.incomingMaxAge
---
{{APIRef("WebTransport API")}}{{SecureContext_Header}}
The **`incomingMaxAge`** property of the {{domxref("WebTransportDatagramDuplexStream")}} interface gets or sets the maximum age for incoming datagrams, in milliseconds.
{{AvailableInWorkers}}
## Value
A number, or `null` if no maximum age has been set.
## Examples
```js
const url = "https://example.com:4999/wt";
async function initTransport(url) {
// Initialize transport connection
const transport = new WebTransport(url);
// The connection can be used once ready fulfills
await transport.ready;
const datagrams = transport.datagrams;
// set incomingMaxAge
datagrams.incomingMaxAge = 2000;
// get incomingMaxAge
console.log(datagrams.incomingMaxAge);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api/webtransportdatagramduplexstream | data/mdn-content/files/en-us/web/api/webtransportdatagramduplexstream/writable/index.md | ---
title: "WebTransportDatagramDuplexStream: writable property"
short-title: writable
slug: Web/API/WebTransportDatagramDuplexStream/writable
page-type: web-api-instance-property
browser-compat: api.WebTransportDatagramDuplexStream.writable
---
{{APIRef("WebTransport API")}}{{SecureContext_Header}}
The **`writable`** read-only property of the {{domxref("WebTransportDatagramDuplexStream")}} interface returns a {{domxref("WritableStream")}} instance that can be used to unreliably write outgoing datagrams to the stream.
"Unreliably" means that transmission of data is not guaranteed, nor is arrival in a specific order. This is fine in some situations and provides very fast delivery. For example, you might want to transmit regular game state updates where each message supersedes the last one that arrives, and order is not important.
{{AvailableInWorkers}}
## Value
A {{domxref("WritableStream")}}.
## Examples
See the main {{domxref("WebTransportDatagramDuplexStream")}} interface page.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api/webtransportdatagramduplexstream | data/mdn-content/files/en-us/web/api/webtransportdatagramduplexstream/maxdatagramsize/index.md | ---
title: "WebTransportDatagramDuplexStream: maxDatagramSize property"
short-title: maxDatagramSize
slug: Web/API/WebTransportDatagramDuplexStream/maxDatagramSize
page-type: web-api-instance-property
browser-compat: api.WebTransportDatagramDuplexStream.maxDatagramSize
---
{{APIRef("WebTransport API")}}{{SecureContext_Header}}
The **`maxDatagramSize`** read-only property of the {{domxref("WebTransportDatagramDuplexStream")}} interface returns the maximum allowable size of outgoing datagrams, in bytes, that can be written to {{domxref("WebTransportDatagramDuplexStream.writable", "writable")}}.
{{AvailableInWorkers}}
## Value
A number.
## Examples
```js
const url = "https://example.com:4999/wt";
async function initTransport(url) {
// Initialize transport connection
const transport = new WebTransport(url);
// The connection can be used once ready fulfills
await transport.ready;
const datagrams = transport.datagrams;
// get maxDatagramSize
console.log(datagrams.maxDatagramSize);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api/webtransportdatagramduplexstream | data/mdn-content/files/en-us/web/api/webtransportdatagramduplexstream/outgoingmaxage/index.md | ---
title: "WebTransportDatagramDuplexStream: outgoingMaxAge property"
short-title: outgoingMaxAge
slug: Web/API/WebTransportDatagramDuplexStream/outgoingMaxAge
page-type: web-api-instance-property
browser-compat: api.WebTransportDatagramDuplexStream.outgoingMaxAge
---
{{APIRef("WebTransport API")}}{{SecureContext_Header}}
The **`outgoingMaxAge`** property of the {{domxref("WebTransportDatagramDuplexStream")}} interface gets or sets the maximum age for outgoing datagrams, in milliseconds.
{{AvailableInWorkers}}
## Value
A number, or `null` if no maximum age has been set.
## Examples
```js
const url = "https://example.com:4999/wt";
async function initTransport(url) {
// Initialize transport connection
const transport = new WebTransport(url);
// The connection can be used once ready fulfills
await transport.ready;
const datagrams = transport.datagrams;
// set outgoingMaxAge
datagrams.outgoingMaxAge = 2000;
// get outgoingMaxAge
console.log(datagrams.outgoingMaxAge);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api/webtransportdatagramduplexstream | data/mdn-content/files/en-us/web/api/webtransportdatagramduplexstream/outgoinghighwatermark/index.md | ---
title: "WebTransportDatagramDuplexStream: outgoingHighWaterMark property"
short-title: outgoingHighWaterMark
slug: Web/API/WebTransportDatagramDuplexStream/outgoingHighWaterMark
page-type: web-api-instance-property
browser-compat: api.WebTransportDatagramDuplexStream.outgoingHighWaterMark
---
{{APIRef("WebTransport API")}}{{SecureContext_Header}}
The **`outgoingHighWaterMark`** property of the {{domxref("WebTransportDatagramDuplexStream")}} interface gets or sets the high water mark for outgoing chunks of data β this is the maximum size, in chunks, that the outgoing {{domxref("WritableStream")}}'s internal queue can reach before it is considered full. See [Internal queues and queuing strategies](/en-US/docs/Web/API/Streams_API/Concepts#internal_queues_and_queuing_strategies) for more information.
{{AvailableInWorkers}}
## Value
A number.
## Examples
```js
const url = "https://example.com:4999/wt";
async function initTransport(url) {
// Initialize transport connection
const transport = new WebTransport(url);
// The connection can be used once ready fulfills
await transport.ready;
const datagrams = transport.datagrams;
// set outgoingHighWaterMark
datagrams.outgoingHighWaterMark = 20000;
// get outgoingHighWaterMark
console.log(datagrams.outgoingHighWaterMark);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api/webtransportdatagramduplexstream | data/mdn-content/files/en-us/web/api/webtransportdatagramduplexstream/incominghighwatermark/index.md | ---
title: "WebTransportDatagramDuplexStream: incomingHighWaterMark property"
short-title: incomingHighWaterMark
slug: Web/API/WebTransportDatagramDuplexStream/incomingHighWaterMark
page-type: web-api-instance-property
browser-compat: api.WebTransportDatagramDuplexStream.incomingHighWaterMark
---
{{APIRef("WebTransport API")}}{{SecureContext_Header}}
The **`incomingHighWaterMark`** property of the {{domxref("WebTransportDatagramDuplexStream")}} interface gets or sets the high water mark for incoming chunks of data β this is the maximum size, in chunks, that the incoming {{domxref("ReadableStream")}}'s internal queue can reach before it is considered full. See [Internal queues and queuing strategies](/en-US/docs/Web/API/Streams_API/Concepts#internal_queues_and_queuing_strategies) for more information.
{{AvailableInWorkers}}
## Value
A number.
## Examples
```js
const url = "https://example.com:4999/wt";
async function initTransport(url) {
// Initialize transport connection
const transport = new WebTransport(url);
// The connection can be used once ready fulfills
await transport.ready;
const datagrams = transport.datagrams;
// set incomingHighWaterMark
datagrams.incomingHighWaterMark = 20000;
// get incomingHighWaterMark
console.log(datagrams.incomingHighWaterMark);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport)
- {{domxref("WebSockets API", "WebSockets API", "", "nocode")}}
- {{domxref("Streams API", "Streams API", "", "nocode")}}
- [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/gpucommandencoder/index.md | ---
title: GPUCommandEncoder
slug: Web/API/GPUCommandEncoder
page-type: web-api-interface
status:
- experimental
browser-compat: api.GPUCommandEncoder
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`GPUCommandEncoder`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} represents a command encoder, used to encode commands to be issued to the GPU.
A `GPUCommandEncoder` object instance is created via the {{domxref("GPUDevice.createCommandEncoder()")}} property.
{{InheritanceDiagram}}
## Instance properties
- {{domxref("GPUCommandEncoder.label", "label")}} {{Experimental_Inline}}
- : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings.
## Instance methods
- {{domxref("GPUCommandEncoder.beginComputePass", "beginComputePass()")}} {{Experimental_Inline}}
- : Starts encoding a compute pass, returning a {{domxref("GPUComputePassEncoder")}} that can be used to control computation.
- {{domxref("GPUCommandEncoder.beginRenderPass", "beginRenderPass()")}} {{Experimental_Inline}}
- : Starts encoding a render pass, returning a {{domxref("GPURenderPassEncoder")}} that can be used to control rendering.
- {{domxref("GPUCommandEncoder.clearBuffer", "clearBuffer()")}} {{Experimental_Inline}}
- : Encodes a command that fills a region of a {{domxref("GPUBuffer")}} with zeroes.
- {{domxref("GPUCommandEncoder.copyBufferToBuffer", "copyBufferToBuffer()")}} {{Experimental_Inline}}
- : Encodes a command that copies data from one {{domxref("GPUBuffer")}} to another.
- {{domxref("GPUCommandEncoder.copyBufferToTexture", "copyBufferToTexture()")}} {{Experimental_Inline}}
- : Encodes a command that copies data from a {{domxref("GPUBuffer")}} to a {{domxref("GPUTexture")}}.
- {{domxref("GPUCommandEncoder.copyTextureToBuffer", "copyTextureToBuffer()")}} {{Experimental_Inline}}
- : Encodes a command that copies data from a {{domxref("GPUTexture")}} to a {{domxref("GPUBuffer")}}.
- {{domxref("GPUCommandEncoder.copyTextureToTexture", "copyTextureToTexture()")}} {{Experimental_Inline}}
- : Encodes a command that copies data from one {{domxref("GPUTexture")}} to another.
- {{domxref("GPUCommandEncoder.finish", "finish()")}} {{Experimental_Inline}}
- : Completes recording of the command sequence encoded on this `GPUCommandEncoder`, returning a corresponding {{domxref("GPUCommandBuffer")}}.
- {{domxref("GPUCommandEncoder.insertDebugMarker", "insertDebugMarker()")}} {{Experimental_Inline}}
- : Marks a specific point in a series of encoded commands with a label.
- {{domxref("GPUCommandEncoder.popDebugGroup", "popDebugGroup()")}} {{Experimental_Inline}}
- : Ends a debug group, which is begun with a {{domxref("GPUCommandEncoder.pushDebugGroup", "pushDebugGroup()")}} call.
- {{domxref("GPUCommandEncoder.pushDebugGroup", "pushDebugGroup()")}} {{Experimental_Inline}}
- : Begins a debug group, which is marked with a specified label, and will contain all subsequent encoded commands up until a {{domxref("GPUCommandEncoder.popDebugGroup", "popDebugGroup()")}} method is invoked.
- {{domxref("GPUCommandEncoder.resolveQuerySet", "resolveQuerySet()")}} {{Experimental_Inline}}
- : Encodes a command that resolves a {{domxref("GPUQuerySet")}}, copying the results into a specified {{domxref("GPUBuffer")}}.
- {{domxref("GPUCommandEncoder.writeTimestamp", "writeTimestamp()")}} {{Experimental_Inline}}
- : Encodes a command that writes a timestamp into a {{domxref("GPUQuerySet")}} once the previous commands recorded into the same queued {{domxref("GPUCommandBuffer")}} have been executed by the GPU.
## Examples
In our [basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/), several commands are recorded via a {{domxref("GPUCommandEncoder")}}:
```js
// ...
// Create GPUCommandEncoder
const commandEncoder = device.createCommandEncoder();
// Create GPURenderPassDescriptor to tell WebGPU which texture to draw into, then initiate render pass
const renderPassDescriptor = {
colorAttachments: [
{
clearValue: clearColor,
loadOp: "clear",
storeOp: "store",
view: context.getCurrentTexture().createView(),
},
],
};
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
// Draw a triangle
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);
// End the render pass
passEncoder.end();
// ...
```
The commands encoded by the {{domxref("GPUCommandEncoder")}} are recoded into a {{domxref("GPUCommandBuffer")}} using the {{domxref("GPUCommandEncoder.finish()")}} method. The command buffer is then passed into the queue via a {{domxref("GPUQueue.submit", "submit()")}} call, ready to be processed by the GPU.
```js
device.queue.submit([commandEncoder.finish()]);
```
> **Note:** Study the [WebGPU samples](https://webgpu.github.io/webgpu-samples/) to find more command encoding examples.
## 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/gpucommandencoder | data/mdn-content/files/en-us/web/api/gpucommandencoder/pushdebuggroup/index.md | ---
title: "GPUCommandEncoder: pushDebugGroup() method"
short-title: pushDebugGroup()
slug: Web/API/GPUCommandEncoder/pushDebugGroup
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPUCommandEncoder.pushDebugGroup
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`pushDebugGroup()`** method of the
{{domxref("GPUCommandEncoder")}} interface begins a debug group, which is marked with a specified label, and will contain all subsequent encoded commands up until a {{domxref("GPUCommandEncoder.popDebugGroup", "popDebugGroup()")}} method is invoked.
This could be used for telemetry, or may be utilized in {{domxref("GPUError")}} messages, browser dev tools, or other services in the future to help with debugging.
## Syntax
```js-nolint
pushDebugGroup(groupLabel)
```
### Parameters
- `groupLabel`
- : A string representing the label for the debug group.
### Return value
None ({{jsxref("Undefined")}}).
## Examples
```js
// ...
commandEncoder.pushDebugGroup("mygroupmarker"); // Start labeled debug group
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);
passEncoder.end();
commandEncoder.popDebugGroup(); // End labeled debug group
// ...
```
## 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/gpucommandencoder | data/mdn-content/files/en-us/web/api/gpucommandencoder/writetimestamp/index.md | ---
title: "GPUCommandEncoder: writeTimestamp() method"
short-title: writeTimestamp()
slug: Web/API/GPUCommandEncoder/writeTimestamp
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPUCommandEncoder.writeTimestamp
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}
The **`writeTimestamp()`** method of the
{{domxref("GPUCommandEncoder")}} interface encodes a command that writes a timestamp into a {{domxref("GPUQuerySet")}} once the previous commands recorded into the same queued {{domxref("GPUCommandBuffer")}} have been executed by the GPU.
> **Note:** To use timestamp queries, the `timestamp-query` {{domxref("GPUSupportedFeatures", "feature", "", "nocode")}} must be enabled in the {{domxref("GPUDevice")}}.
## Syntax
```js-nolint
writeTimestamp(querySet, queryIndex)
```
### Parameters
- `querySet`
- : A {{domxref("GPUQuerySet")}} object representing the query set that will store the timestamp values.
- `queryIndex`
- : A number representing the index of the query in the query set.
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`writeTimestamp()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPUCommandEncoder")}} becomes invalid:
- The `timestamp-query` {{domxref("GPUSupportedFeatures", "feature", "", "nocode")}} is enabled in the {{domxref("GPUDevice")}}.
- The `querySet` {{domxref("GPUQuerySet.type")}} is `"timestamp"`
- The `queryIndex` value is less than the {{domxref("GPUQuerySet.count")}}.
## Examples
```js
// ...
const querySet = device.createQuerySet({
type: "timestamp",
count: 32,
});
// ...
commandEncoder.writeTimestamp(querySet, 0);
// ...
```
## 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/gpucommandencoder | data/mdn-content/files/en-us/web/api/gpucommandencoder/insertdebugmarker/index.md | ---
title: "GPUCommandEncoder: insertDebugMarker() method"
short-title: insertDebugMarker()
slug: Web/API/GPUCommandEncoder/insertDebugMarker
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPUCommandEncoder.insertDebugMarker
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`insertDebugMarker()`** method of the
{{domxref("GPUCommandEncoder")}} interface marks a specific point in a series of encoded commands with a label.
This could be used for telemetry, or may be utilized in {{domxref("GPUError")}} messages, browser dev tools, or other services in the future to help with debugging.
## Syntax
```js-nolint
insertDebugMarker(markerLabel)
```
### Parameters
- `markerLabel`
- : A string representing the label to insert.
### Return value
None ({{jsxref("Undefined")}}).
## Examples
```js
// ...
commandEncoder.insertDebugMarker("mymarker");
// ...
```
## 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/gpucommandencoder | data/mdn-content/files/en-us/web/api/gpucommandencoder/begincomputepass/index.md | ---
title: "GPUCommandEncoder: beginComputePass() method"
short-title: beginComputePass()
slug: Web/API/GPUCommandEncoder/beginComputePass
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPUCommandEncoder.beginComputePass
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`beginComputePass()`** method of the
{{domxref("GPUCommandEncoder")}} interface starts encoding a compute pass, returning a {{domxref("GPUComputePassEncoder")}} that can be used to control computation.
## Syntax
```js-nolint
beginComputePass()
beginComputePass(descriptor)
```
### Parameters
- `descriptor` {{optional_inline}}
- : An object containing the following properties:
- `label` {{optional_inline}}
- : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings.
- `timestampWrites` {{optional_inline}}
- : An array of objects defining where and when timestamp query values will be written for this pass. These objects have the following properties:
- `location`: An enumerated value specifying when the timestamp will be executed. Available values are:
- `"beginning"`: The timestamp is executed along with the other encoded commands in the compute pass once the corresponding {{domxref("GPUCommandBuffer")}} is submitted.
- `"end"`: The timestamp is executed as part of a separate list of timestamp attachments once the pass ends.
- `queryIndex`: A number specifying the index position in the `querySet` that the timestamp will be written to.
- `querySet`: The {{domxref("GPUQuerySet")}} that the timestamp will be written to.
> **Note:** To use timestamp queries, the `timestamp-query` {{domxref("GPUSupportedFeatures", "feature", "", "nocode")}} must be enabled in the {{domxref("GPUDevice")}}.
### Return value
A {{domxref("GPUComputePassEncoder")}} object instance.
### Validation
The following criteria must be met when calling **`beginComputePass()`**, otherwise a {{domxref("GPUValidationError")}} is generated and an invalid {{domxref("GPUComputePassEncoder")}} is returned:
- The `timestamp-query` {{domxref("GPUSupportedFeatures", "feature", "", "nocode")}} is enabled in the {{domxref("GPUDevice")}}.
- No two `timestampWrites` objects have the same `location`. In effect, this means that you can only run two timestamp queries per render pass.
- For each timestamp query, the `querySet` {{domxref("GPUQuerySet.type")}} is `"timestamp"`, and the `queryIndex` value is less than the {{domxref("GPUQuerySet.count")}}.
## Examples
In our [basic compute demo](https://mdn.github.io/dom-examples/webgpu-compute-demo/), several commands are recorded via a {{domxref("GPUCommandEncoder")}}. Most of these commands originate from the {{domxref("GPUComputePassEncoder")}} created via `beginComputePass()`.
```js
// ...
// Create GPUCommandEncoder to encode commands to issue to the GPU
const commandEncoder = device.createCommandEncoder();
// Initiate render pass
const passEncoder = commandEncoder.beginComputePass();
// Issue commands
passEncoder.setPipeline(computePipeline);
passEncoder.setBindGroup(0, bindGroup);
passEncoder.dispatchWorkgroups(Math.ceil(BUFFER_SIZE / 64));
// End the render pass
passEncoder.end();
// Copy output buffer to staging buffer
commandEncoder.copyBufferToBuffer(
output,
0, // Source offset
stagingBuffer,
0, // Destination offset
BUFFER_SIZE,
);
// End frame by passing array of command buffers to command queue for execution
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/gpucommandencoder | data/mdn-content/files/en-us/web/api/gpucommandencoder/copybuffertotexture/index.md | ---
title: "GPUCommandEncoder: copyBufferToTexture() method"
short-title: copyBufferToTexture()
slug: Web/API/GPUCommandEncoder/copyBufferToTexture
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPUCommandEncoder.copyBufferToTexture
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`copyBufferToTexture()`** method of the
{{domxref("GPUCommandEncoder")}} interface encodes a command that copies data from a {{domxref("GPUBuffer")}} to a {{domxref("GPUTexture")}}.
## Syntax
```js-nolint
copyBufferToTexture(source, destination, copySize)
```
### Parameters
- `source`
- : An object that defines the buffer to copy from, plus the layout of the data in the buffer to be copied to the texture. Combined with `copySize`, it defines the region of the source buffer. `source` can take the following properties:
- `buffer`
- : The {{domxref("GPUBuffer")}} to copy from.
- `offset` {{optional_inline}}
- : The offset, in bytes, from the beginning of `data` to the start of the image data to be copied. If omitted, `offset` defaults to 0.
- `bytesPerRow` {{optional_inline}}
- : A number representing the stride, in bytes, between the start of each block row (i.e. a row of complete texel blocks) and the subsequent block row. This is required if there are multiple block rows (i.e. the copy height or depth is more than one block).
- `rowsPerImage` {{optional_inline}}
- : The number of block rows per single image inside the data. `bytesPerRow` × `rowsPerImage` will give you the stride, in bytes, between the start of each complete image. This is required if there are multiple images to copy.
- `destination`
- : An object defining the texture to write the data to. Combined with `copySize`, defines the region of the destination texture subresource. `destination` can take the following properties:
- `aspect` {{optional_inline}}
- : An enumerated value defining which aspects of the texture to write the data to. Possible values are:
- `"all"`
- : All available aspects of the texture format will be written to, which can mean all or any of color, depth, and stencil, depending on what kind of format you are dealing with.
- `"depth-only"`
- : Only the depth aspect of a [depth-or-stencil format](https://gpuweb.github.io/gpuweb/#combined-depth-stencil-format) will be written to.
- `"stencil-only"`
- : Only the stencil aspect of a depth-or-stencil format will be written to.
If omitted, `aspect` takes a value of `"all"`.
- `mipLevel` {{optional_inline}}
- : A number representing the mip-map level of the texture to write the data to. If omitted, `mipLevel` defaults to 0.
- `origin` {{optional_inline}}
- : An object or array specifying the origin of the copy β the minimum corner of the texture region to write the data to. Together with `size`, this defines the full extent of the region to copy to. The `x`, `y`, and `z` values default to 0 if any of all of `origin` is omitted.
What follows is a sample array:
```js
[0, 0, 0];
```
The object equivalent would look like this:
```js
{
x: 0,
y: 0,
z: 0
}
```
- `texture`
- : A {{domxref("GPUTexture")}} object representing the texture to write the data to.
- `copySize`
- : An object or array specifying the width, height, and depth/array layer count of the copied data. The width value must always be specified, while the height and depth/array layer count values are optional and will default to 1 if omitted.
What follows is a sample `copySize` array:
```js
[16, 16, 2];
```
The object equivalent would look like this:
```js
{
width: 16,
height: 16,
depthOrArrayLayers: 2
}
```
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`copyBufferToTexture()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPUCommandEncoder")}} becomes invalid.
For the `source`:
- `source.bytesPerRow` is a multiple of 256.
- The `source.buffer`'s {{domxref("GPUBuffer.usage")}} includes the `GPUBufferUsage.COPY_SRC` flag.
For the `destination`:
- `mipLevel` is less than the {{domxref("GPUTexture.mipLevelCount")}}.
- `origin.x` is a multiple of the texel block width of the {{domxref("GPUTexture.format")}}.
- `origin.y` is a multiple of the texel block height of the {{domxref("GPUTexture.format")}}.
- If the {{domxref("GPUTexture.format")}} is a [depth-or-stencil format](https://gpuweb.github.io/gpuweb/#combined-depth-stencil-format) or {{domxref("GPUTexture.sampleCount")}} is more than 1, the subresource size is equal to `size`.
- The `destination`'s {{domxref("GPUTexture.usage")}} includes the `GPUTextureUsage.COPY_DST` flag.
- The `destination`'s {{domxref("GPUTexture.sampleCount")}} is 1.
- `destination.aspect` refers to a single aspect of the {{domxref("GPUTexture.format")}}.
- That aspect is a valid image copy destination according to [depth-or-stencil formats](https://gpuweb.github.io/gpuweb/#combined-depth-stencil-format).
- The `destination` is compatible with the `copySize`.
## Examples
```js
commandEncoder.copyBufferToTexture(
{
buffer: sourceBuffer,
},
{
texture: destinationTexture,
},
{
width: 16,
height: 16,
depthOrArrayLayers: 2,
},
);
```
## 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/gpucommandencoder | data/mdn-content/files/en-us/web/api/gpucommandencoder/popdebuggroup/index.md | ---
title: "GPUCommandEncoder: popDebugGroup() method"
short-title: popDebugGroup()
slug: Web/API/GPUCommandEncoder/popDebugGroup
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPUCommandEncoder.popDebugGroup
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`popDebugGroup()`** method of the
{{domxref("GPUCommandEncoder")}} interface ends a debug group, which is begun with a {{domxref("GPUCommandEncoder.pushDebugGroup", "pushDebugGroup()")}} call.
This could be used for telemetry, or may be utilized in {{domxref("GPUError")}} messages, browser dev tools, or other services in the future to help with debugging.
## Syntax
```js-nolint
popDebugGroup()
```
### Parameters
None.
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`popDebugGroup()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPUCommandEncoder")}} becomes invalid:
- The command encoder's debug stack is not empty (i.e. at least one debug group was previously started with {{domxref("GPUCommandEncoder.pushDebugGroup", "pushDebugGroup()")}}).
## Examples
```js
// ...
commandEncoder.pushDebugGroup("mygroupmarker"); // Start labeled debug group
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);
passEncoder.end();
commandEncoder.popDebugGroup(); // End labeled debug group
// ...
```
## 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/gpucommandencoder | data/mdn-content/files/en-us/web/api/gpucommandencoder/copytexturetotexture/index.md | ---
title: "GPUCommandEncoder: copyTextureToTexture() method"
short-title: copyTextureToTexture()
slug: Web/API/GPUCommandEncoder/copyTextureToTexture
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPUCommandEncoder.copyTextureToTexture
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`copyTextureToTexture()`** method of the
{{domxref("GPUCommandEncoder")}} interface encodes a command that copies data from one {{domxref("GPUTexture")}} to another.
## Syntax
```js-nolint
copyTextureToTexture(source, destination, copySize)
```
### Parameters
- `source`
- : An object (see [Copy texture object structure](#copy_texture_object_structure)) defining the texture to copy the data from. Combined with `copySize`, this defines the region of the source texture subresource.
- `destination`
- : An object (see [Copy texture object structure](#copy_texture_object_structure)) defining the texture to write the data to. Combined with `copySize`, this defines the region of the destination texture subresource.
- `copySize`
- : An object or array specifying the width, height, and depth/array layer count of the copied data. The width value must always be specified, while the height and depth/array layer count values are optional and will default to 1 if omitted.
What follows is a sample `copySize` array:
```js
[16, 16, 2];
```
The object equivalent would look like this:
```js
{
width: 16,
height: 16,
depthOrArrayLayers: 2
}
```
### Copy texture object structure
A copy texture object has the following structure:
- `aspect` {{optional_inline}}
- : An enumerated value defining which aspects of the texture to copy the data from/to. Possible values are:
- `"all"`
- : All available aspects of the texture format will be copied from/to, which can mean all or any of color, depth, and stencil, depending on what kind of format you are dealing with.
- `"depth-only"`
- : Only the depth aspect of a [depth-or-stencil format](https://gpuweb.github.io/gpuweb/#combined-depth-stencil-format) will be copied from/to.
- `"stencil-only"`
- : Only the stencil aspect of a depth-or-stencil format will be copied from/to.
If omitted, `aspect` takes a value of `"all"`.
- `mipLevel` {{optional_inline}}
- : A number representing the mip-map level of the texture to copy the data from/to. If omitted, `mipLevel` defaults to 0.
- `origin` {{optional_inline}}
- : An object or array specifying the origin of the copy/destination β the minimum corner of the texture region to copy the data from/to. Together with `size`, this defines the full extent of the region to copy from/to. The `x`, `y`, and `z` values default to 0 if any of all of `origin` is omitted.
What follows is a sample array:
```js
[0, 0, 0];
```
The object equivalent would look like this:
```js
{
x: 0,
y: 0,
z: 0
}
```
- `texture`
- : A {{domxref("GPUTexture")}} object representing the texture to copy the data from/to.
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`copyTextureToTexture()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPUCommandEncoder")}} becomes invalid.
For the `source`:
- The `source`'s {{domxref("GPUTexture.usage")}} includes the `GPUTextureUsage.COPY_SRC` flag.
For the `destination`:
- The `source`'s {{domxref("GPUTexture.usage")}} includes the `GPUTextureUsage.COPY_DST` flag.
For `source` and `destination`:
- `mipLevel` is less than the {{domxref("GPUTexture.mipLevelCount")}}.
- `origin.x` is a multiple of the texel block width of the {{domxref("GPUTexture.format")}}.
- `origin.y` is a multiple of the texel block height of the {{domxref("GPUTexture.format")}}.
- The source and destination `texture` {{domxref("GPUTexture.format")}}s are copy-compatible.
- The source and destination `texture` {{domxref("GPUTexture.sampleCount")}}s are equal.
- If the {{domxref("GPUTexture.format")}} is a [depth-or-stencil format](https://gpuweb.github.io/gpuweb/#combined-depth-stencil-format) or {{domxref("GPUTexture.sampleCount")}} is more than 1, the subresource size is equal to `size`.
- The `texture`'s {{domxref("GPUTexture.sampleCount")}} is 1.
- `aspect` refers to a single aspect of the {{domxref("GPUTexture.format")}}.
- That aspect is a valid image copy source/destination according to [depth-or-stencil formats](https://gpuweb.github.io/gpuweb/#combined-depth-stencil-format).
- The `texture` is compatible with the `copySize`.
## Examples
```js
commandEncoder.copyTextureToTexture(
{
texture: sourceTexture,
},
{
texture: destinationTexture,
},
{
width: 16,
height: 16,
depthOrArrayLayers: 2,
},
);
```
## 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/gpucommandencoder | data/mdn-content/files/en-us/web/api/gpucommandencoder/resolvequeryset/index.md | ---
title: "GPUCommandEncoder: resolveQuerySet() method"
short-title: resolveQuerySet()
slug: Web/API/GPUCommandEncoder/resolveQuerySet
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPUCommandEncoder.resolveQuerySet
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`resolveQuerySet()`** method of the
{{domxref("GPUCommandEncoder")}} interface encodes a command that resolves a {{domxref("GPUQuerySet")}}, copying the results into a specified {{domxref("GPUBuffer")}}.
## Syntax
```js-nolint
resolveQuerySet(querySet, firstQuery, queryCount, destination, destinationOffset)
```
### Parameters
- `querySet`
- : A {{domxref("GPUQuerySet")}} object representing the query set to be resolved.
- `firstQuery`
- : The index number of the first query value to be copied over to the buffer.
- `queryCount`
- : The number of queries to be copied over to the buffer, starting from `firstQuery`.
- `destination`
- : A {{domxref("GPUBuffer")}} representing the buffer to copy the query values to.
- `destinationOffset`
- : A number representing the offset, in bytes, from the start of the buffer to start writing the query values at.
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`resolveQuerySet()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPUCommandEncoder")}} becomes invalid:
- The `destination.buffer`'s {{domxref("GPUBuffer.usage")}} includes the `GPUBufferUsage.QUERY_RESOLVE` flag.
- `firstQuery` is smaller than the number of queries in `querySet`.
- `firstQuery` + `queryCount` is smaller than or equal to the number of queries in `querySet`.
- `destinationOffset` is a multiple of 256.
- `destinationOffset` + 8 Γ `queryCount` is less than or equal to `destination.size`.
## Examples
```js
// ...
const queryBuffer = device.createBuffer({
size: 1024,
usage: GPUBufferUsage.QUERY_RESOLVE,
});
const querySet = device.createQuerySet({
type: "timestamp",
count: 32,
});
// ...
const commandEncoder = device.createCommandEncoder();
// Write timestamps to querySet
commandEncoder.writeTimestamp(querySet, 0);
// ...
commandEncoder.writeTimestamp(querySet, 1);
// etc.
// ...
commandEncoder.resolveQuerySet(
querySet,
0, // First query to write
16, // Number of queries to count
queryBuffer,
0, // Buffer offset
);
// ...
```
## 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/gpucommandencoder | data/mdn-content/files/en-us/web/api/gpucommandencoder/clearbuffer/index.md | ---
title: "GPUCommandEncoder: clearBuffer() method"
short-title: clearBuffer()
slug: Web/API/GPUCommandEncoder/clearBuffer
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPUCommandEncoder.clearBuffer
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`clearBuffer()`** method of the
{{domxref("GPUCommandEncoder")}} interface encodes a command that fills a region of a {{domxref("GPUBuffer")}} with zeroes.
## Syntax
```js-nolint
clearBuffer(buffer)
clearBuffer(buffer, offset)
clearBuffer(buffer, offset, size)
```
### Parameters
- `buffer`
- : A {{domxref("GPUBuffer")}} object representing the buffer to clear.
- `offset` {{optional_inline}}
- : A number representing the offset, in bytes, from the start of the `buffer` to the sub-region to clear. If omitted, `offset` defaults to 0.
- `size` {{optional_inline}}
- : A number representing the size, in bytes, of the sub-region to clear. If omitted, `size` defaults to the `buffer` size - `offset`.
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`clearBuffer()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPUCommandEncoder")}} becomes invalid:
- The `buffer`'s {{domxref("GPUBuffer.usage")}} includes the `GPUBufferUsage.COPY_DST` flag.
- `offset` and `size` are both multiples of 4.
- The `buffer`'s {{domxref("GPUBuffer.size")}} is greater than or equal to `offset` + `size`.
## Examples
```js
// ...
const buffer = device.createBuffer({
size: 1000,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
});
// Later on
const commandBuffer = device.createCommandEncoder();
commandEncoder.clearBuffer(buffer);
// ...
```
## 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/gpucommandencoder | data/mdn-content/files/en-us/web/api/gpucommandencoder/copytexturetobuffer/index.md | ---
title: "GPUCommandEncoder: copyTextureToBuffer() method"
short-title: copyTextureToBuffer()
slug: Web/API/GPUCommandEncoder/copyTextureToBuffer
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPUCommandEncoder.copyTextureToBuffer
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`copyTextureToBuffer()`** method of the
{{domxref("GPUCommandEncoder")}} interface encodes a command that copies data from a {{domxref("GPUTexture")}} to a {{domxref("GPUBuffer")}}.
## Syntax
```js-nolint
copyTextureToBuffer(source, destination, copySize)
```
### Parameters
- `source`
- : An object defining the texture to copy the data from. Combined with `copySize`, defines the region of the source texture subresource. `source` can take the following properties:
- `aspect` {{optional_inline}}
- : An enumerated value defining which aspects of the texture to copy the data from. Possible values are:
- `"all"`
- : All available aspects of the texture format will be copied from, which can mean all or any of color, depth, and stencil, depending on what kind of format you are dealing with.
- `"depth-only"`
- : Only the depth aspect of a [depth-or-stencil format](https://gpuweb.github.io/gpuweb/#combined-depth-stencil-format) will be copied from.
- `"stencil-only"`
- : Only the stencil aspect of a depth-or-stencil format will be copied from.
If omitted, `aspect` takes a value of `"all"`.
- `mipLevel` {{optional_inline}}
- : A number representing the mip-map level of the texture to copy the data from. If omitted, `mipLevel` defaults to 0.
- `origin` {{optional_inline}}
- : An object or array specifying the origin of the copy β the minimum corner of the texture region to copy the data from. Together with `size`, this defines the full extent of the region to copy from. The `x`, `y`, and `z` values default to 0 if any of all of `origin` is omitted.
What follows is a sample array:
```js
[0, 0, 0];
```
The object equivalent would look like this:
```js
{
x: 0,
y: 0,
z: 0
}
```
- `texture`
- : A {{domxref("GPUTexture")}} object representing the texture to copy the data from.
- `destination`
- : An object that defines the buffer to write to, plus the layout of the data to write to the buffer. Combined with `copySize`, it defines the region of the destination buffer. `source` can take the following properties:
- `buffer`
- : The {{domxref("GPUBuffer")}} to write to.
- `offset` {{optional_inline}}
- : The offset, in bytes, from the beginning of `data` to the start position to write the copied data to. If omitted, `offset` defaults to 0.
- `bytesPerRow` {{optional_inline}}
- : A number representing the stride, in bytes, between the start of each block row (i.e. a row of complete texel blocks) and the subsequent block row. This is required if there are multiple block rows (i.e. the copy height or depth is more than one block).
- `rowsPerImage` {{optional_inline}}
- : The number of block rows per single image inside the data. `bytesPerRow` × `rowsPerImage` will give you the stride, in bytes, between the start of each complete image. This is required if there are multiple images to copy.
- `copySize`
- : An object or array specifying the width, height, and depth/array layer count of the copied data. The width value must always be specified, while the height and depth/array layer count values are optional and will default to 1 if omitted.
What follows is a sample `copySize` array:
```js
[16, 16, 2];
```
The object equivalent would look like this:
```js
{
width: 16,
height: 16,
depthOrArrayLayers: 2
}
```
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`copyTextureToBuffer()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPUCommandEncoder")}} becomes invalid.
For the `source`:
- `mipLevel` is less than the {{domxref("GPUTexture.mipLevelCount")}}.
- `origin.x` is a multiple of the texel block width of the {{domxref("GPUTexture.format")}}.
- `origin.y` is a multiple of the texel block height of the {{domxref("GPUTexture.format")}}.
- If the {{domxref("GPUTexture.format")}} is a [depth-or-stencil format](https://gpuweb.github.io/gpuweb/#combined-depth-stencil-format) or {{domxref("GPUTexture.sampleCount")}} is more than 1, the subresource size is equal to `size`.
- The `source`'s {{domxref("GPUTexture.usage")}} includes the `GPUTextureUsage.COPY_SRC` flag.
- The `source`'s {{domxref("GPUTexture.sampleCount")}} is 1.
- `source.aspect` refers to a single aspect of the {{domxref("GPUTexture.format")}}.
- That aspect is a valid image copy source according to [depth-or-stencil formats](https://gpuweb.github.io/gpuweb/#combined-depth-stencil-format).
- The `source` is compatible with the `copySize`.
For the `destination`:
- `destination.bytesPerRow` is a multiple of 256.
- The `destination.buffer`'s {{domxref("GPUBuffer.usage")}} includes the `GPUBufferUsage.COPY_DST` flag.
## Examples
```js
commandEncoder.copyTextureToBuffer(
{
texture: sourceTexture,
},
{
buffer: destinationBuffer,
},
{
width: 16,
height: 16,
depthOrArrayLayers: 2,
},
);
```
## 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/gpucommandencoder | data/mdn-content/files/en-us/web/api/gpucommandencoder/copybuffertobuffer/index.md | ---
title: "GPUCommandEncoder: copyBufferToBuffer() method"
short-title: copyBufferToBuffer()
slug: Web/API/GPUCommandEncoder/copyBufferToBuffer
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPUCommandEncoder.copyBufferToBuffer
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`copyBufferToBuffer()`** method of the
{{domxref("GPUCommandEncoder")}} interface encodes a command that copies data from one {{domxref("GPUBuffer")}} to another.
## Syntax
```js-nolint
copyBufferToBuffer(source, sourceOffset, destination, destinationOffset, size)
```
### Parameters
- `source`
- : The {{domxref("GPUBuffer")}} to copy from.
- `sourceOffset`
- : The offset, in bytes, into the `source` to begin copying from.
- `destination`
- : The {{domxref("GPUBuffer")}} to copy to.
- `destinationOffset`
- : The offset, in bytes, into the `destination` to begin copying to.
- `size`
- : The number of bytes to copy.
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`copyBufferToBuffer()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPUCommandEncoder")}} becomes invalid:
- The `source`'s {{domxref("GPUBuffer.usage")}} includes the `GPUBufferUsage.COPY_SRC` flag.
- The `destination`'s {{domxref("GPUBuffer.usage")}} includes the `GPUBufferUsage.COPY_DST` flag.
- `size`, `sourceOffset`, and `destinationOffset` are all multiples of 4.
- The `source`'s {{domxref("GPUBuffer.size")}} is greater than or equal to `sourceOffset` + `size`.
- The `destination`'s {{domxref("GPUBuffer.size")}} is greater than or equal to `destinationOffset` + `size`.
- `source` and `destination` are different {{domxref("GPUBuffer")}}s (you can't copy from and to the same buffer).
## Examples
In our [basic compute demo](https://mdn.github.io/dom-examples/webgpu-compute-demo/), we use `copyBufferToBuffer()` to copy the contents of our `output` buffer to the `stagingBuffer`.
```js
// ...
// Create an output buffer to read GPU calculations to, and a staging buffer to be mapped for JavaScript access
const output = device.createBuffer({
size: BUFFER_SIZE,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
});
const stagingBuffer = device.createBuffer({
size: BUFFER_SIZE,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
});
// ...
// Create GPUCommandEncoder to encode commands to issue to the GPU
const commandEncoder = device.createCommandEncoder();
// ...
// Copy output buffer to staging buffer
commandEncoder.copyBufferToBuffer(
output,
0, // Source offset
stagingBuffer,
0, // Destination offset
BUFFER_SIZE,
);
// ...
```
## 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/gpucommandencoder | data/mdn-content/files/en-us/web/api/gpucommandencoder/finish/index.md | ---
title: "GPUCommandEncoder: finish() method"
short-title: finish()
slug: Web/API/GPUCommandEncoder/finish
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPUCommandEncoder.finish
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`finish()`** method of the
{{domxref("GPUCommandEncoder")}} interface completes recording of the command sequence encoded on this `GPUCommandEncoder`, returning a corresponding {{domxref("GPUCommandBuffer")}}.
## Syntax
```js-nolint
finish()
finish(descriptor)
```
### Parameters
- `descriptor` {{optional_inline}}
- : An object that can contain the following properties:
- `label` {{optional_inline}}
- : A string providing a label for the returned {{domxref("GPUCommandBuffer")}} that can be used to identify it, for example in {{domxref("GPUError")}} messages or console warnings.
### Return value
A {{domxref("GPUCommandBuffer")}} object instance.
### Validation
The following criteria must be met when calling **`finish()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPUCommandEncoder")}} becomes invalid:
- There are no active debug groups (i.e. started via {{domxref("GPUCommandEncoder.pushDebugGroup", "pushDebugGroup()")}}).
- The {{domxref("GPUCommandEncoder")}} is in an open state β this means that:
- There are no child {{domxref("GPUComputePassEncoder")}} or {{domxref("GPURenderPassEncoder")}}s active that have not been `end()`ed.
- The {{domxref("GPUCommandEncoder")}} has not already had `finish()` called on it (in which case it cannot be used to encode any more commands).
## Examples
```js
// ...
const commandBuffer = commandEncoder.finish();
device.queue.submit([commandBuffer]);
// ...
```
## 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/gpucommandencoder | data/mdn-content/files/en-us/web/api/gpucommandencoder/label/index.md | ---
title: "GPUCommandEncoder: label property"
short-title: label
slug: Web/API/GPUCommandEncoder/label
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GPUCommandEncoder.label
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`label`** read-only property of the
{{domxref("GPUCommandEncoder")}} 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("GPUDevice.createCommandEncoder()")}} call, or you can get and set it directly on the `GPUCommandEncoder` 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 `GPUCommandEncoder.label`:
```js
const commandEncoder = device.createCommandEncoder();
commandEncoder.label = "mycommandencoder";
console.log(commandEncoder.label); // "mycommandencoder";
```
Setting a label via the originating {{domxref("GPUDevice.createCommandEncoder()")}} call, and then getting it via `GPUCommandEncoder.label`:
```js
const commandEncoder = device.createCommandEncoder({
label: "mycommandencoder",
});
console.log(commandEncoder.label); // "mycommandencoder";
```
## 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/gpucommandencoder | data/mdn-content/files/en-us/web/api/gpucommandencoder/beginrenderpass/index.md | ---
title: "GPUCommandEncoder: beginRenderPass() method"
short-title: beginRenderPass()
slug: Web/API/GPUCommandEncoder/beginRenderPass
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPUCommandEncoder.beginRenderPass
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`beginRenderPass()`** method of the
{{domxref("GPUCommandEncoder")}} interface starts encoding a render pass, returning a {{domxref("GPURenderPassEncoder")}} that can be used to control rendering.
## Syntax
```js-nolint
beginRenderPass(descriptor)
```
### Parameters
- `descriptor`
- : An object containing the following properties:
- `colorAttachments`
- : An array of objects (see [Color attachment object structure](#color_attachment_object_structure)) defining the color attachments that will be output to when executing this render pass.
- `depthStencilAttachment` {{optional_inline}}
- : An object (see [Depth/stencil attachment object structure](#depthstencil_attachment_object_structure)) defining the depth/stencil attachment that will be output to and tested against when executing this render pass.
- `label` {{optional_inline}}
- : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings.
- `maxDrawCount` {{optional_inline}}
- : A number indicating the maximum number of draw calls that will be done in the render pass. This is used by some implementations to size work injected before the render pass. You should keep the default value β 50000000 β unless you know that more draw calls will be done.
- `occlusionQuerySet` {{optional_inline}}
- : The {{domxref("GPUQuerySet")}} that will store the occlusion query results for this pass.
- `timestampWrites` {{optional_inline}}
- : An array of objects defining where and when timestamp query values will be written for this pass. These objects have the following properties:
- `location`: An enumerated value specifying when the timestamp will be executed. Available values are:
- `"beginning"`: The timestamp is executed along with the other encoded commands in the compute pass once the corresponding {{domxref("GPUCommandBuffer")}} is submitted.
- `"end"`: The timestamp is executed as part of a separate list of timestamp attachments once the pass ends.
- `queryIndex`: A number specifying the index position in the `querySet` that the timestamp will be written to.
- `querySet`: The {{domxref("GPUQuerySet")}} that the timestamp will be written to.
> **Note:** To use timestamp queries, the `timestamp-query` {{domxref("GPUSupportedFeatures", "feature", "", "nocode")}} must be enabled in the {{domxref("GPUDevice")}}.
### Color attachment object structure
Color attachment objects can have the following properties:
- `clearValue` {{optional_inline}}
- : A color value to clear the `view` texture to, prior to executing the render pass. This value is ignored if `loadOp` is not set to `"clear"`. `clearValue` takes an array or object representing the four color components `r`, `g`, `b`, and `a` as decimals.
What follows is a sample array:
```js
clearValue: [0.0, 0.5, 1.0, 1.0];
```
The object equivalent would look like this:
```js
clearValue: {
r: 0.0,
g: 0.5,
b: 1.0,
a: 1.0
}
```
If `clearValue` is omitted, it defaults to `{r: 0, g: 0, b: 0, a: 0}`.
- `loadOp`
- : An enumerated value indicating the load operation to perform on `view` prior to executing the render pass. Possible values are:
- `"clear"`: Loads the `clearValue` for this attachment into the render pass.
- `"load"`: Loads the existing value for this attachment into the render pass.
> **Note:** It is recommended to always use `"clear"` in cases where the initial value doesn't matter, as it will give better performance on some devices such as mobiles.
- `storeOp`
- : An enumerated value indicating the store operation to perform on `view` after executing the render pass. Possible values are:
- `"discard"`: Discards the resulting value of the render pass for this attachment.
- `"store"`: Stores the resulting value of the render pass for this attachment.
- `resolveTarget` {{optional_inline}}
- : A {{domxref("GPUTextureView")}} object representing the texture subresource that will receive the resolved output for this color attachment if `view` is multisampled.
- `view`
- : A {{domxref("GPUTextureView")}} object representing the texture subresource that will be output to for this color attachment.
> **Note:** Each color or depth/stencil attachment must be a unique texture subresource, and texture subresources used as attachments cannot be used inside the render pass.
### Depth/stencil attachment object structure
The `depthStencilAttachment` object can have the following properties:
- `depthClearValue` {{optional_inline}}
- : A number indicating the value to clear `view`'s depth component prior to executing the render pass. This is ignored if `depthLoadOp` is not set to `"clear"`.
The value must be between 0.0 and 1.0, inclusive.
- `depthLoadOp` {{optional_inline}}
- : An enumerated value indicating the load operation to perform on `view`'s depth component prior to executing the render pass. Possible values are:
- `"clear"`: Loads the `clearValue` for this attachment into the render pass.
- `"load"`: Loads the existing value for this attachment into the render pass.
> **Note:** It is recommended to always use `"clear"` in cases where the initial value doesn't matter, as it will give better performance on some devices such as mobiles.
- `depthReadOnly` {{optional_inline}}
- : A boolean. Setting the value to `true` causes the depth component of `view` to be read-only. If `depthReadOnly` is omitted, it defaults to `false`.
- `depthStoreOp` {{optional_inline}}
- : An enumerated value indicating the store operation to perform on `view`'s depth component after executing the render pass. Possible values are:
- `"discard"`: Discards the resulting value of the render pass for this attachment.
- `"store"`: Stores the resulting value of the render pass for this attachment.
- `stencilClearValue` {{optional_inline}}
- : A number indicating the value to clear `view`'s stencil component to prior to executing the render pass. This is ignored if `stencilLoadOp` is not set to `"clear"`.
If `stencilClearValue` is omitted, it defaults to 0.
- `stencilLoadOp` {{optional_inline}}
- : An enumerated value indicating the load operation to perform on `view`'s stencil component prior to executing the render pass. Possible values are:
- `"clear"`: Loads the `clearValue` for this attachment into the render pass.
- `"load"`: Loads the existing value for this attachment into the render pass.
> **Note:** It is recommended to always use `"clear"` in cases where the initial value doesn't matter, as it will give better performance on some devices such as mobiles.
- `stencilReadOnly` {{optional_inline}}
- : A boolean. Setting the value to `true` causes the stencil component of `view` to be read-only. If `stencilReadOnly` is omitted, it defaults to `false`.
- `stencilStoreOp` {{optional_inline}}
- : An enumerated value indicating the store operation to perform on `view`'s stencil component after executing the render pass. Possible values are:
- `"discard"`: Discards the resulting value of the render pass for this attachment.
- `"store"`: Stores the resulting value of the render pass for this attachment.
- `view`
- : A {{domxref("GPUTextureView")}} object representing the texture subresource that will be output to and read from for this depth/stencil attachment.
### Return value
A {{domxref("GPURenderPassEncoder")}} object instance.
### Validation
The following criteria must be met when calling **`beginRenderPass()`**, otherwise a {{domxref("GPUValidationError")}} is generated and an invalid {{domxref("GPURenderPassEncoder")}} is returned.
General:
- `colorAttachments.length` is less than or equal to the {{domxref("GPUDevice")}}'s `maxColorAttachments` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}.
- If `colorAttachments` contains only `null` values, `depthStencilAttachment` is provided.
- All `view`s in `colorAttachments` and `depthStencilAttachment` have equal {{domxref("GPUTexture.sampleCount")}} values and render extents ({{domxref("GPUTexture.height")}}, {{domxref("GPUTexture.width")}}, and {{domxref("GPUTexture.depthOrArrayLayers")}}).
- If `occlusionQuerySet` is set, the referenced {{domxref("GPUQuerySet")}} has a `type` of `"occlusion"`.
For color attachment objects
- The `view` is renderable, and the `view`'s format (i.e. specified in the descriptor of the originating {{domxref("GPUTexture.createView()")}} call) is a color renderable format.
- If `resolveTarget` is provided:
- The `view`'s originating {{domxref("GPUTexture")}}'s {{domxref("GPUTexture.sampleCount", "sampleCount")}} is greater than 1.
- The `resolveTarget`'s originating {{domxref("GPUTexture")}}'s {{domxref("GPUTexture.sampleCount", "sampleCount")}} is 1.
- `resolveTarget` is renderable.
- The sizes of the subresources that `view` and `resolveTarget` provide a view of match.
- `view`'s and `resolveTarget`'s formats match.
- [Color attachments bytes per sample](https://gpuweb.github.io/gpuweb/#abstract-opdef-validating-gpurenderpassdescriptors-color-attachment-bytes-per-sample) is less than or equal to the {{domxref("GPUDevice")}}'s `maxColorAttachmentBytesPerSample` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}.
For depth/stencil attachment objects:
- The `view` is renderable, and its format is a [depth-or-stencil](https://gpuweb.github.io/gpuweb/#depth-or-stencil-format) format.
- If `depthLoadOp` is set to `"clear"`, a valid `depthClearValue` is provided.
- If `view`'s format is a combined depth-or-stencil format, `depthReadOnly` matches `stencilReadOnly`.
- If `view`'s format has a depth aspect, and `depthReadOnly` is `false`, `depthLoadOp` and `depthStoreOp` are provided.
- If `view`'s format has a depth aspect, and `depthReadOnly` is `true`, `depthLoadOp` and `depthStoreOp` are not provided.
- If `view`'s format has a stencil aspect, and `stencilReadOnly` is `false`, `stencilLoadOp` and `stencilStoreOp` are provided.
- If `view`'s format has a stencil aspect, and `stencilReadOnly` is `true`, `stencilLoadOp` and `stencilStoreOp` are not provided.
For timestamp queries:
- The `timestamp-query` {{domxref("GPUSupportedFeatures", "feature", "", "nocode")}} is enabled in the {{domxref("GPUDevice")}}.
- No two `timestampWrites` objects have the same `location`. In effect, this means that you can only run two timestamp queries per render pass.
- For each timestamp query, the `querySet` {{domxref("GPUQuerySet.type")}} is `"timestamp"`, and the `queryIndex` value is less than the {{domxref("GPUQuerySet.count")}}.
- No two `timestampWrites` objects have the same `queryIndex` and `querySet` pair.
## Examples
In our [basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/), a number of commands are recorded via a {{domxref("GPUCommandEncoder")}}. These commands originate from the {{domxref("GPURenderPassEncoder")}} created via `beginRenderPass()` :
```js
// ...
// Create GPUCommandEncoder
const commandEncoder = device.createCommandEncoder();
// Create GPURenderPassDescriptor to tell WebGPU which texture to draw into, then initiate render pass
const renderPassDescriptor = {
colorAttachments: [
{
clearValue: clearColor,
loadOp: "clear",
storeOp: "store",
view: context.getCurrentTexture().createView(),
},
],
};
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
// Draw a triangle
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);
// End the render pass
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 | data/mdn-content/files/en-us/web/api/css_object_model/index.md | ---
title: CSS Object Model (CSSOM)
slug: Web/API/CSS_Object_Model
page-type: web-api-overview
spec-urls:
- https://drafts.csswg.org/cssom/
- https://drafts.csswg.org/cssom-view/
- https://drafts.css-houdini.org/css-typed-om/
---
{{DefaultAPISidebar("CSSOM")}}
The **CSS Object Model** is a set of APIs allowing the manipulation of CSS from JavaScript. It is much like the DOM, but for the CSS rather than the HTML. It allows users to read and modify CSS style dynamically.
The values of CSS are represented untyped, that is using {{JSxRef("String")}} objects.
## Reference
- {{DOMxRef("AnimationEvent")}}
- {{DOMxRef("CaretPosition")}}
- {{DOMxRef("CSS")}}
- {{DOMxRef("CSSConditionRule")}}
- {{DOMxRef("CSSCounterStyleRule")}}
- {{DOMxRef("CSSFontFaceRule")}}
- {{DOMxRef("CSSFontFeatureValuesMap")}}
- {{DOMxRef("CSSFontFeatureValuesRule")}}
- {{DOMxRef("CSSGroupingRule")}}
- {{DOMxRef("CSSImportRule")}}
- {{DOMxRef("CSSKeyframeRule")}}
- {{DOMxRef("CSSKeyframesRule")}}
- {{DOMxRef("CSSMarginRule")}}
- {{DOMxRef("CSSMediaRule")}}
- {{DOMxRef("CSSNamespaceRule")}}
- {{DOMxRef("CSSPageRule")}}
- {{DOMxRef("CSSRule")}}
- {{DOMxRef("CSSRuleList")}}
- {{DOMxRef("CSSStyleDeclaration")}}
- {{DOMxRef("CSSStyleSheet")}}
- {{DOMxRef("CSSStyleRule")}}
- {{DOMxRef("CSSSupportsRule")}}
- {{DOMxRef("FontFace")}}
- {{DOMxRef("FontFaceSet")}}
- {{DOMxRef("FontFaceSetLoadEvent")}}
- {{DOMxRef("MediaList")}}
- {{DOMxRef("MediaQueryList")}}
- {{DOMxRef("MediaQueryListEvent")}}
- {{DOMxRef("Screen")}}
- {{DOMxRef("StyleSheet")}}
- {{DOMxRef("StyleSheetList")}}
- {{DOMxRef("TransitionEvent")}}
Several other interfaces are also extended by the CSSOM-related specifications: {{DOMxRef("Document")}}, {{DOMxRef("Window")}}, {{DOMxRef("Element")}}, {{DOMxRef("HTMLElement")}}, {{DOMxRef("HTMLImageElement")}}, {{DOMxRef("Range")}}, {{DOMxRef("MouseEvent")}}, and {{DOMxRef("SVGElement")}}.
### CSS Typed Object Model {{Experimental_Inline}}
{{SeeCompatTable}}
- {{DOMxRef("CSSImageValue")}} {{Experimental_Inline}}
- {{DOMxRef("CSSKeywordValue")}} {{Experimental_Inline}}
- {{DOMxRef("CSSMathInvert")}} {{Experimental_Inline}}
- {{DOMxRef("CSSMathMax")}} {{Experimental_Inline}}
- {{DOMxRef("CSSMathMin")}} {{Experimental_Inline}}
- {{DOMxRef("CSSMathNegate")}} {{Experimental_Inline}}
- {{DOMxRef("CSSMathProduct")}} {{Experimental_Inline}}
- {{DOMxRef("CSSMathSum")}} {{Experimental_Inline}}
- {{DOMxRef("CSSMathValue")}} {{Experimental_Inline}}
- {{DOMxRef("CSSMatrixComponent")}} {{Experimental_Inline}}
- {{DOMxRef("CSSNumericArray")}} {{Experimental_Inline}}
- {{DOMxRef("CSSNumericValue")}} {{Experimental_Inline}}
- {{DOMxRef("CSSPerspective")}} {{Experimental_Inline}}
- {{DOMxRef("CSSPositionValue")}} {{Experimental_Inline}}
- {{DOMxRef("CSSRotate")}} {{Experimental_Inline}}
- {{DOMxRef("CSSScale")}} {{Experimental_Inline}}
- {{DOMxRef("CSSSkew")}} {{Experimental_Inline}}
- {{DOMxRef("CSSSkewX")}} {{Experimental_Inline}}
- {{DOMxRef("CSSSkewY")}} {{Experimental_Inline}}
- {{DOMxRef("CSSStyleValue")}} {{Experimental_Inline}}
- {{DOMxRef("CSSTransformComponent")}} {{Experimental_Inline}}
- {{DOMxRef("CSSTransformValue")}} {{Experimental_Inline}}
- {{DOMxRef("CSSTranslate")}} {{Experimental_Inline}}
- {{DOMxRef("CSSUnitValue")}} {{Experimental_Inline}}
- {{DOMxRef("CSSUnparsedValue")}} {{Experimental_Inline}}
- {{DOMxRef("CSSVariableReferenceValue")}} {{Experimental_Inline}}
- {{DOMxRef("StylePropertyMap")}} {{Experimental_Inline}}
- {{DOMxRef("StylePropertyMapReadOnly")}} {{Experimental_Inline}}
### Obsolete CSSOM interfaces {{deprecated_inline}}
{{deprecated_header}}
- {{DOMxRef("CSSPrimitiveValue")}} {{deprecated_inline}}
- {{DOMxRef("CSSValue")}} {{deprecated_inline}}
- {{DOMxRef("CSSValueList")}} {{deprecated_inline}}
## Tutorials
- [Determining the dimensions of elements](/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements)
- [Managing screen orientation](/en-US/docs/Web/API/CSS_Object_Model/Managing_screen_orientation)
## Specifications
{{Specifications}}
## Browser compatibility
All these features have been added little by little over the years to the different browsers: it was a quite complex process that can't be summarized in a simple table. Please refer to the specific interfaces for its availability.
## See also
- [Document Object Model (DOM)](/en-US/docs/Web/API/Document_Object_Model)
- [Houdini APIs](/en-US/docs/Web/API/Houdini_APIs)
| 0 |
data/mdn-content/files/en-us/web/api/css_object_model | data/mdn-content/files/en-us/web/api/css_object_model/css_declaration_block/index.md | ---
title: CSS Declaration Block
slug: Web/API/CSS_Object_Model/CSS_Declaration_Block
page-type: guide
spec-urls: https://drafts.csswg.org/cssom/#css-declaration-blocks
---
{{ APIRef("CSSOM") }}
A **CSS declaration block** is an ordered collection of CSS properties and values. It is represented in the DOM as a {{domxref("CSSStyleDeclaration")}}.
Each property and value pairing is known as a [CSS declaration](/en-US/docs/Web/API/CSS_Object_Model/CSS_Declaration). The CSS declaration block has the following associated properties:
- computed flag
- : Set if the {{domxref("CSSStyleDeclaration")}} object is a computed rather than specified style. Unset by default.
- declarations
- : The [CSS declarations](/en-US/docs/Web/API/CSS_Object_Model/CSS_Declaration) associated with this object.
- parent CSS rule
- : The {{domxref("CSSRule")}} that the CSS declaration block is associated with, otherwise null.
- owner node
- : The {{domxref("element")}} that the CSS declaration block is associated with, otherwise null.
- updating flag
- : Set when the CSS declaration block is updating the owner node's [`style`](/en-US/docs/Web/HTML/Global_attributes#style) attribute.
When a {{domxref("CSSStyleDeclaration")}} is returned by a [CSS Object Model (CSSOM)](/en-US/docs/Web/API/CSS_Object_Model) interface these properties are set to appropriate values as defined by the specification.
## Basic example
The following example shows a CSS rule with a declaration block for the {{htmlelement("Heading_Elements","h1")}} element. The CSS declaration block is the lines between the curly braces.
```css
h1 {
margin: 0 auto;
font-family: "Helvetica Neue", "Arial", sans-serif;
font-style: italic;
color: rebeccapurple;
}
```
We can return a {{domxref("CSSStyleDeclaration")}} representing this CSS declaration block using {{domxref("CSSStyleRule.style")}}.
```js
let myRules = document.styleSheets[0].cssRules;
let rule = myRules[0]; // a CSSStyleRule
console.log(rule.style); // a CSSStyleDeclaration object
```
## Specifications
{{Specifications}}
| 0 |
data/mdn-content/files/en-us/web/api/css_object_model | data/mdn-content/files/en-us/web/api/css_object_model/css_declaration/index.md | ---
title: CSS Declaration
slug: Web/API/CSS_Object_Model/CSS_Declaration
page-type: guide
spec-urls: https://drafts.csswg.org/cssom/#css-declarations
---
{{ APIRef("CSSOM") }}
A **CSS declaration** is an abstract concept not exposed as an object in the DOM. It represents a CSS property and value pairing.
A CSS declaration has the following associated properties:
- property name
- : The property name of the declaration, for example {{cssxref("background-color")}}.
- value
- : The value of the declaration as a list of component values.
- important flag
- : Either set or unset.
- case-sensitive flag
- : Set if the property name is defined to be case-sensitive according to the specification, otherwise unset.
## Basic example
The following example shows a CSS rule with a [CSS declaration block](/en-US/docs/Web/API/CSS_Object_Model/CSS_Declaration_Block) for the {{htmlelement("Heading_Elements","<h1>")}} element. The CSS declaration block is the lines between the curly braces, it contains two CSS declarations. One for {{cssxref("font-style")}} and another for {{cssxref("color")}}.
```css
h1 {
font-style: italic;
color: rebeccapurple;
}
```
## Specifications
{{Specifications}}
| 0 |
data/mdn-content/files/en-us/web/api/css_object_model | data/mdn-content/files/en-us/web/api/css_object_model/determining_the_dimensions_of_elements/index.md | ---
title: Determining the dimensions of elements
slug: Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements
page-type: guide
---
{{DefaultAPISidebar("CSSOM View")}}
There are several properties you can look at in order to determine the width and height of elements, and it can be tricky to determine which is the right one for your needs. This article is designed to help you make that decision. Note that all these properties are read-only. If you want to set the width and height of an element, use {{CSSxRef("width")}} and {{CSSxRef("height")}} or the overriding {{CSSxRef("min-width")}} and {{CSSxRef("max-width")}}, and {{CSSxRef("min-height")}} and {{CSSxRef("max-height")}} properties.
## How much room does it use up?
If you need to know the total amount of space an element occupies, including the width of the visible content, scrollbars (if any), padding, and border, you want to use the {{DOMxRef("HTMLElement.offsetWidth")}} and {{DOMxRef("HTMLElement.offsetHeight")}} properties. Most of the time these are the same as width and height of {{DOMxRef("Element.getBoundingClientRect()")}}, when there aren't any transforms applied to the element. In case of transforms, the `offsetWidth` and `offsetHeight` returns the element's layout width and height, while `getBoundingClientRect()` returns the rendering width and height. As an example, if the element has `width: 100px;` and `transform: scale(0.5);` the `getBoundingClientRect()` will return 50 as the width, while `offsetWidth` will return 100.
![How the offsetWidth and offsetHeight properties are determined, considering padding, borders, and margin sizes](dimensions-offset.png)
## What's the size of the displayed content?
If you need to know how much space the actual displayed content takes up, including padding but not including the border, margins, or scrollbars, you want to use the {{DOMxRef("Element.clientWidth")}} and {{DOMxRef("Element.clientHeight")}} properties:
![How the clientWidth and clientHeight properties are determined, considering padding, borders, and margin sizes](dimensions-client.png)
## How big is the content?
If you need to know the actual size of the content, regardless of how much of it is currently visible, you need to use the {{DOMxRef("Element.scrollWidth")}} and {{DOMxRef("Element.scrollHeight")}} properties. These return the width and height of the entire content of an element, even if only part of it is presently visible due to the use of scroll bars.
For example, if a 600x400 pixel element is being displayed inside a 300x300 pixel scrollbox, `scrollWidth` will return 600 while `scrollHeight` will return 400.
## See also
- <https://www.w3.org/TR/cssom-view-1/>
- [MSDN: Measuring Element Dimension and Location](<https://docs.microsoft.com/previous-versions/hh781509(v=vs.85)>)
| 0 |
data/mdn-content/files/en-us/web/api/css_object_model | data/mdn-content/files/en-us/web/api/css_object_model/managing_screen_orientation/index.md | ---
title: Managing screen orientation
slug: Web/API/CSS_Object_Model/Managing_screen_orientation
page-type: guide
---
{{DefaultAPISidebar("Screen Orientation API")}}
The term _screen orientation_ refers to whether a browser [viewport](/en-US/docs/Glossary/Viewport) is in landscape mode (that is, the width of the viewport is greater than its height), or else in portrait mode (the height of the viewport is greater than its width)
CSS provides the [`orientation`](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries#orientation) media feature to allow adjusting layout based on screen orientation.
The [Screen Orientation API](/en-US/docs/Web/API/Screen_Orientation_API) provides a programmatic JavaScript API for working with screen orientation β including the ability to lock the viewport to a specific orientation.
## Adjusting layout based on the orientation
One of the most common cases for orientation changes is when you want to revise the layout of your content based on the orientation of the device. For example, perhaps you want a button bar to stretch along the longest dimension of the device's display. By using a media query, you can do this easily and automatically.
Let's have an example with the following HTML code
```html
<ul id="toolbar">
<li>A</li>
<li>B</li>
<li>C</li>
</ul>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis lacinia nisi nec
sem viverra vitae fringilla nulla ultricies. In ac est dolor, quis tincidunt
leo. Cras commodo quam non tortor consectetur eget rutrum dolor ultricies. Ut
interdum tristique dapibus. Nullam quis malesuada est.
</p>
```
CSS relies on the orientation media query to handle specific styles based on the screen orientation
```css
/* First let's define some common styles */
html,
body {
width: 100%;
height: 100%;
}
body {
border: 1px solid black;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
p {
font: 1em sans-serif;
margin: 0;
padding: 0.5em;
}
ul {
list-style: none;
font: 1em monospace;
margin: 0;
padding: 0.5em;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: black;
}
li {
display: inline-block;
margin: 0;
padding: 0.5em;
background: white;
}
```
Once we have some common styles we can start defining a special case for the orientation
```css
/* For portrait, we want the toolbar on top */
@media screen and (orientation: portrait) {
#toolbar {
width: 100%;
}
}
/* For landscape, we want the toolbar stick on the left */
@media screen and (orientation: landscape) {
#toolbar {
position: fixed;
width: 2.65em;
height: 100%;
}
p {
margin-left: 2em;
}
li + li {
margin-top: 0.5em;
}
}
```
And here's the result
<table class="no-markdown">
<thead>
<tr>
<th scope="col">Portrait</th>
<th scope="col">Landscape</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div>
{{ EmbedLiveSample('Adjusting_layout_based_on_the_orientation', 180, 350) }}
</div>
</td>
<td>
<div>
{{ EmbedLiveSample('Adjusting_layout_based_on_the_orientation', 350, 180) }}
</div>
</td>
</tr>
</tbody>
</table>
> **Note:** The orientation media query actually applies based on the orientation of the browser window (or iframe) not the orientation of the device.
## Locking the screen orientation
Some devices (mainly mobile devices) can dynamically change the orientation of the screen based on their own orientation, ensuring that the user will always be able to read what's on the screen. While this behavior is perfectly suited for text content, there is some content that can be negatively affected by such a change. For example, games based on the orientation of the device could be messed up by such a change of the orientation.
The Screen Orientation API is made to prevent or handle such a change.
### Listening to orientation changes
The {{domxref("Window.orientationchange_event", "orientationchange")}} event is triggered each time the device change the orientation of the screen and the orientation itself can be read with the {{domxref("Screen.orientation")}} property.
```js
screen.addEventListener("orientationchange", () => {
console.log(`The orientation of the screen is: ${screen.orientation}`);
});
```
### Preventing orientation change
Any web application can lock the screen to suits its own needs. The screen is locked using the {{domxref("ScreenOrientation.lock()", "screen.orientation.lock()")}} method and unlocked using the {{domxref("ScreenOrientation.unlock()", "screen.orientation.unlock()")}} method.
The {{domxref("ScreenOrientation.lock()", "screen.orientation.lock()")}} method accepts one of the following values to define the kind of lock to apply: `any`, `natural`. `portrait-primary`, `portrait-secondary`, `landscape-primary`, `landscape-secondary`, `portrait`, and `landscape`:
```js
screen.orientation.lock();
```
It returns a [promise](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves after the lock succeeds.
> **Note:** A screen lock is web application dependent. If application A is locked to `landscape` and application B is locked to `portrait`, switching from application A to B or B to A will not fire an {{domxref("Window.orientationchange_event", "orientationchange")}} event because both applications will keep the orientation they had.
>
> However, locking the orientation can fire an {{domxref("Window.orientationchange_event", "orientationchange")}} event if the orientation had to be changed to satisfy the lock requirements.
## See also
- {{domxref("Screen.orientation", "screen.orientation")}}
- {{domxref("ScreenOrientation")}}
- {{DOMxRef("Screen.orientationchange_event", "orientationchange")}} event
- [The orientation media query](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries#orientation)
| 0 |
data/mdn-content/files/en-us/web/api/css_object_model | data/mdn-content/files/en-us/web/api/css_object_model/using_dynamic_styling_information/index.md | ---
title: Using dynamic styling information
slug: Web/API/CSS_Object_Model/Using_dynamic_styling_information
page-type: guide
---
{{DefaultAPISidebar("CSSOM")}}
The CSS Object Model (CSSOM), part of the DOM, exposes specific interfaces allowing manipulation of a wide amount of information regarding CSS. Initially defined in the _DOM Level 2 Style_ recommendation, these interfaces forms now a specification, _CSS Object Model (CSSOM)_ which aims at superseding it.
In many cases, and where possible, it is best practice to dynamically manipulate classes via the {{ domxref("element.className", "className") }} property since the ultimate appearance of all of the styling hooks can be controlled in a single stylesheet. One's JavaScript code also becomes cleaner since instead of being dedicated to styling details, it can focus on the overall semantics of each section it is creating or manipulating, leaving the precise style details to the stylesheet. However, there are cases where actually obtaining or manipulating the rules can be useful (whether for whole stylesheets or individual elements), and that is described in further detail below. Note also that, as with individual element's DOM styles, when speaking of manipulating the stylesheets, this is not actually manipulating the physical document(s), but merely the internal representation of the document.
The basic `style` object exposes the {{domxref("Stylesheet")}} and the {{domxref("CSSStylesheet")}} interfaces. Those interfaces contain members like `insertRule`, `selectorText`, and `parentStyleSheet` for accessing and manipulating the individual style rules that make up a CSS stylesheet.
To get to the `style` objects from the `document`, you can use the {{domxref("Document.styleSheets")}} property and access the individual objects by index (e.g., `document.styleSheets[0]` is the first stylesheet defined for the document, etc.).
## Modify a stylesheet rule with CSSOM
In this example the background of the page is set to red using CSS. The JavaScript then accesses the property using the CSSOM and changes the background to blue.
```html
<html lang="en">
<head>
<title>Modifying a stylesheet rule with CSSOM</title>
<style>
body {
background-color: red;
}
</style>
<script>
const stylesheet = document.styleSheets[0];
stylesheet.cssRules[0].style.backgroundColor = "aqua";
</script>
</head>
<body>
The stylesheet declaration for the body's background color is modified via
JavaScript.
</body>
</html>
```
### Result
{{EmbedGHLiveSample("css-examples/cssom/modify-rule.html", '100%', 120)}}
The list of properties available in the DOM from the `style` property is given on the [DOM CSS Properties List](/en-US/docs/Web/CSS/Reference) page.
To modify styles to a document using CSS syntax, one can insert rules or insert {{HTMLElement("style")}} tags whose `innerHTML` property is set to the desired CSS.
## Modify an element's style
The element {{domxref("HTMLElement.style", "style")}} property (see also the section "DOM Style Object" below) can also be used to get and set the styles on an element. However, this property only returns style attributes that have been set _in-line_ (e.g., `<td style="background-color: lightblue">` returns the string "`background-color:lightblue`", or directly for that element using `element.style.propertyName`, even though there may be other styles on the element from a stylesheet).
Also, when you set this property on an element, you override any styles that have been set elsewhere for that element's particular property you are setting. Setting the `border` property, for example, will override settings made elsewhere for that element's `border` property in the head section, or external style sheets. However, this will not affect any other property declarations for that element's styles, such as padding or margin or font, for example.
To change a particular element's style, you can adapt the following example for the element(s) you want to style.
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>simple style example</title>
<script>
function alterStyle(elem) {
elem.style.background = "green";
}
function resetStyle(elemId) {
const elem = document.getElementById(elemId);
elem.style.background = "white";
}
</script>
<style>
#p1 {
border: solid blue 2px;
}
</style>
</head>
<body>
<!-- passes a reference to the element's object as parameter 'this'. -->
<p id="p1" onclick="alterStyle(this);">
Click here to change background color.
</p>
<!-- passes the 'p1' id of another element's style to modify. -->
<button onclick="resetStyle('p1');">Reset background color</button>
</body>
</html>
```
{{ EmbedLiveSample('Modify_an_elements_style') }}
The {{domxref("window.getComputedStyle", "getComputedStyle()")}} method on the `document.defaultView` object returns all styles that have actually been computed for an element.
## DOM Style Object
The `style` object represents an individual style statement. The style object is accessed from the `document` or from the elements to which that style is applied. It represents the _in-line_ styles on a particular element.
### Setting style properties
More important than the two properties noted here is the use of the `style` object to set individual style properties on an element:
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Style Property Example</title>
<link rel="StyleSheet" href="example.css" />
<script>
function setStyle() {
document.getElementById("d").style.color = "orange";
}
function resetStyle() {
document.getElementById("d").style.color = "black";
}
</script>
</head>
<body>
<div id="d" class="thunder">Thunder</div>
<button onclick="setStyle()">Click here to change text color</button>
<button onclick="resetStyle()">Reset text color</button>
</body>
</html>
```
{{ EmbedLiveSample('Setting_style_properties') }}
The **media** and **type** of the style may or may not be given.
### Using the setAttribute method
Note that you can also change style of an element by getting a reference to it and then use its [`setAttribute`](/en-US/docs/Web/API/Element/setAttribute) method to specify the CSS property and its value.
```js
const el = document.getElementById("some-element");
el.setAttribute("style", "background-color:darkblue;");
```
Be aware, however, that `setAttribute` removes all other `style` properties that may already have been defined in the element's `style` object. If the `some-element` element above had an inβline `style` attribute of say `style="font-size: 18px"`, that value would be removed by the use of `setAttribute`.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/cssstyledeclaration/index.md | ---
title: CSSStyleDeclaration
slug: Web/API/CSSStyleDeclaration
page-type: web-api-interface
browser-compat: api.CSSStyleDeclaration
---
{{APIRef("CSSOM")}}
The **`CSSStyleDeclaration`** interface represents an object that is a CSS declaration block, and exposes style information and various style-related methods and properties.
A `CSSStyleDeclaration` object can be exposed using three different APIs:
- Via {{DOMxRef("HTMLElement.style")}}, which deals with the inline styles of a single element (e.g., `<div style="β¦">`).
- Via the {{DOMxRef("CSSStyleSheet")}} API. For example, `document.styleSheets[0].cssRules[0].style` returns a `CSSStyleDeclaration` object on the first CSS rule in the document's first stylesheet.
- Via {{DOMxRef("Window.getComputedStyle()")}}, which exposes the `CSSStyleDeclaration` object as a **read-only** interface.
## Attributes
- {{DOMxRef("CSSStyleDeclaration.cssText")}}
- : Textual representation of the declaration block, if and only if it is exposed via {{DOMxRef("HTMLElement.style")}}. Setting this attribute changes the inline style. If you want a text representation of a computed declaration block, you can get it with `JSON.stringify()`.
- {{DOMxRef("CSSStyleDeclaration.length")}} {{ReadOnlyInline}}
- : The number of properties. See the {{DOMxRef("CSSStyleDeclaration.item()", 'item()')}} method below.
- {{DOMxRef("CSSStyleDeclaration.parentRule")}} {{ReadOnlyInline}}
- : The containing {{DOMxRef("CSSRule")}}.
### CSS Properties
- {{DOMxRef("CSSStyleDeclaration.cssFloat", "CSSStyleDeclaration.cssFloat")}}
- : Special alias for the {{CSSxRef("float")}} CSS property.
- {{DOMxRef("CSSStyleDeclaration.named_properties", '<code>CSSStyleDeclaration</code> named properties', "", 1)}}
- : Dashed and camel-cased attributes for all supported CSS properties.
## Instance methods
- {{DOMxRef("CSSStyleDeclaration.getPropertyPriority()")}}
- : Returns the optional priority, "important".
- {{DOMxRef("CSSStyleDeclaration.getPropertyValue()")}}
- : Returns the property value given a property name.
- {{DOMxRef("CSSStyleDeclaration.item()")}}
- : Returns a CSS property name by its index, or the empty string if the index is out-of-bounds.
- {{DOMxRef("CSSStyleDeclaration.removeProperty()")}}
- : Removes a property from the CSS declaration block.
- {{DOMxRef("CSSStyleDeclaration.setProperty()")}}
- : Modifies an existing CSS property or creates a new CSS property in the declaration block.
- {{DOMxRef("CSSStyleDeclaration.getPropertyCSSValue()")}} {{deprecated_inline}}
- : **Only supported via getComputedStyle in Firefox.** Returns the property value as a {{DOMxRef("CSSPrimitiveValue")}} or `null` for [shorthand properties](/en-US/docs/Web/CSS/Shorthand_properties).
## Example
```js
const styleObj = document.styleSheets[0].cssRules[0].style;
console.log(styleObj.cssText);
for (let i = styleObj.length; i--; ) {
const nameString = styleObj[i];
styleObj.removeProperty(nameString);
}
console.log(styleObj.cssText);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssstyledeclaration | data/mdn-content/files/en-us/web/api/cssstyledeclaration/parentrule/index.md | ---
title: "CSSStyleDeclaration: parentRule property"
short-title: parentRule
slug: Web/API/CSSStyleDeclaration/parentRule
page-type: web-api-instance-property
browser-compat: api.CSSStyleDeclaration.parentRule
---
{{ APIRef("CSSOM") }}
The **CSSStyleDeclaration.parentRule** read-only
property returns a {{domxref('CSSRule')}} that is the parent of this style
block, e.g. a {{domxref('CSSStyleRule')}} representing the style for a CSS
selector.
## Value
The CSS rule that contains this declaration block or `null` if this
{{domxref('CSSStyleDeclaration')}} is not attached to a {{domxref('CSSRule')}}.
## Examples
The following JavaScript code gets the parent CSS style rule from a
{{domxref('CSSStyleDeclaration')}}:
```js
const declaration = document.styleSheets[0].rules[0].style;
const rule = declaration.parentRule;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssstyledeclaration | data/mdn-content/files/en-us/web/api/cssstyledeclaration/getpropertypriority/index.md | ---
title: "CSSStyleDeclaration: getPropertyPriority() method"
short-title: getPropertyPriority()
slug: Web/API/CSSStyleDeclaration/getPropertyPriority
page-type: web-api-instance-method
browser-compat: api.CSSStyleDeclaration.getPropertyPriority
---
{{ APIRef("CSSOM") }}
The **CSSStyleDeclaration.getPropertyPriority()** method interface returns
a string that provides all explicitly set priorities on the CSS
property.
## Syntax
```js-nolint
getPropertyPriority(property)
```
### Parameters
- `property`
- : A string representing the property name to be checked.
### Return value
A string that represents the priority (e.g. `"important"`) if one exists.
If none exists, returns the empty string.
## Examples
The following JavaScript code checks whether `margin` is marked as important
in a CSS selector rule:
```js
const declaration = document.styleSheets[0].cssRules[0].style;
const isImportant = declaration.getPropertyPriority("margin") === "important";
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssstyledeclaration | data/mdn-content/files/en-us/web/api/cssstyledeclaration/csstext/index.md | ---
title: "CSSStyleDeclaration: cssText property"
short-title: cssText
slug: Web/API/CSSStyleDeclaration/cssText
page-type: web-api-instance-property
browser-compat: api.CSSStyleDeclaration.cssText
---
{{APIRef("CSSOM")}}
The **`cssText`** property of the {{domxref("CSSStyleDeclaration")}} interface returns or sets the text of the element's **inline** style declaration only.
To be able to set a **stylesheet** rule dynamically, see [Using dynamic styling information](/en-US/docs/Web/API/CSS_Object_Model/Using_dynamic_styling_information).
Not to be confused with stylesheet style-rule {{domxref("CSSRule.cssText")}}.
## Value
A string containing the text of the element's inline style declaration.
## Example
```html
<span id="s1" style="color: red;"> Some text </span>
<script>
const elem = document.getElementById("s1");
alert(elem.style.cssText); // "color: red;"
</script>
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssstyledeclaration | data/mdn-content/files/en-us/web/api/cssstyledeclaration/length/index.md | ---
title: "CSSStyleDeclaration: length property"
short-title: length
slug: Web/API/CSSStyleDeclaration/length
page-type: web-api-instance-property
browser-compat: api.CSSStyleDeclaration.length
---
{{ APIRef("CSSOM") }}
The read-only property returns an integer that represents the
number of style declarations in this CSS declaration block.
## Value
An integer that provides the number of styles explicitly set on the parent of
the instance.
## Examples
The following gets the number of explicitly set styles on the following HTML element:
```html
<div
id="div1"
style="margin: 0 10px; background-color: #CA1; font-family: monospace"></div>
```
JavaScript code:
```js
const myDiv = document.getElementById("div1");
const divStyle = myDiv.style;
const len = divStyle.length; // 6
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssstyledeclaration | data/mdn-content/files/en-us/web/api/cssstyledeclaration/cssfloat/index.md | ---
title: "CSSStyleDeclaration: cssFloat property"
short-title: cssFloat
slug: Web/API/CSSStyleDeclaration/cssFloat
page-type: web-api-instance-property
browser-compat: api.CSSStyleDeclaration.cssFloat
---
{{APIRef("CSSOM")}}
The **`cssFloat`** property of the {{domxref("CSSStyleDeclaration")}} interface returns the result of invoking {{DOMxRef("CSSStyleDeclaration.getPropertyValue()")}} with `float` as an argument.
When setting, it invokes {{DOMxRef("CSSStyleDeclaration.setProperty()")}} with `float` as the first argument, and the given value as the second argument. The given value must be a valid value for the {{cssxref("float")}} property.
## Value
A string.
## Example
In the below example, the stylesheet contains a single rule for `.box`, which has the {{cssxref("float")}} property with a value of `left`. This value will be returned by `cssFloat`. We then set the value to "right" using `cssFloat`, and return the new value.
```css
.box {
float: left;
inline-size: 300px;
}
```
```js
let myRules = document.styleSheets[0].cssRules;
let rule = myRules[0];
console.log(rule.style.cssFloat); // "left"
rule.style.cssFloat = "right";
console.log(rule.style.cssFloat); //right
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssstyledeclaration | data/mdn-content/files/en-us/web/api/cssstyledeclaration/removeproperty/index.md | ---
title: "CSSStyleDeclaration: removeProperty() method"
short-title: removeProperty()
slug: Web/API/CSSStyleDeclaration/removeProperty
page-type: web-api-instance-method
browser-compat: api.CSSStyleDeclaration.removeProperty
---
{{ APIRef("CSSOM") }}
The **`CSSStyleDeclaration.removeProperty()`** method interface
removes a property from a CSS style declaration object.
## Syntax
```js-nolint
removeProperty(property)
```
### Parameters
- `property`
- A string representing the property name to be removed. Multi-word property names are hyphenated ({{Glossary("kebab_case", "kebab-case")}}) and not {{Glossary("camel_case", "camel-cased")}}.
### Return value
A string equal to the value of the CSS property before it was removed.
### Exceptions
- `NoModificationAllowedError` {{domxref('DOMException')}}
- : Thrown when the property or declaration block is read-only.
## Examples
The following JavaScript code removes the `background-color` CSS property
from a selector rule:
```js
const declaration = document.styleSheets[0].rules[0].style;
const oldValue = declaration.removeProperty("background-color");
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssstyledeclaration | data/mdn-content/files/en-us/web/api/cssstyledeclaration/item/index.md | ---
title: "CSSStyleDeclaration: item() method"
short-title: item()
slug: Web/API/CSSStyleDeclaration/item
page-type: web-api-instance-method
browser-compat: api.CSSStyleDeclaration.item
---
{{ APIRef("CSSOM") }}
The `CSSStyleDeclaration.item()`
method interface returns a CSS property name from a {{domxref('CSSStyleDeclaration')}}
by index.
This method doesn't throw exceptions as long as you provide
arguments; the empty string is returned if the index is out of range and a
{{jsxref("TypeError")}} is thrown if no argument is provided.
## Syntax
```js-nolint
item(index)
```
### Parameters
- `index`
- : The index of the node to be fetched. The index is zero-based.
### Return value
A string that is the name of the CSS property at the specified index.
JavaScript has a special simpler syntax for obtaining an item from a NodeList by index:
```js
const propertyName = style[index];
```
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if no argument is provided.
## Examples
```js
const style = document.getElementById("div1").style;
const propertyName = style.item(1); // or style[1] - returns the second style listed
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssstyledeclaration | data/mdn-content/files/en-us/web/api/cssstyledeclaration/setproperty/index.md | ---
title: "CSSStyleDeclaration: setProperty() method"
short-title: setProperty()
slug: Web/API/CSSStyleDeclaration/setProperty
page-type: web-api-instance-method
browser-compat: api.CSSStyleDeclaration.setProperty
---
{{ APIRef("CSSOM") }}
The
**`CSSStyleDeclaration.setProperty()`** method interface sets
a new value for a property on a CSS style declaration object.
## Syntax
```js-nolint
setProperty(propertyName, value)
setProperty(propertyName, value, priority)
```
### Parameters
- `propertyName`
- : A string representing the CSS property name (hyphen case) to be modified.
- `value` {{optional_inline}}
- : A string containing the new property value. If not specified, treated
as the empty string.
> **Note:** `value` must not contain `"!important"`, that should be set using the `priority` parameter.
- `priority` {{optional_inline}}
- : A string allowing the "important" CSS priority to be set. If not
specified, treated as the empty string. The following values are accepted:
- String value `"important"`
- Keyword `undefined`
- String empty value `""`
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- `NoModificationAllowedError` {{domxref('DOMException')}}
- : Thrown if the property or declaration block is read only.
## Alternative usage
If `priority` can be omitted, JavaScript has a special simpler
syntax for setting a CSS property on a style declaration object:
```js
style.cssPropertyName = "value";
```
## Examples
In this example we have three buttons, which can be pressed to dynamically alter our
box paragraph's border, background color, and text color to random values (see the live
example at the end of this section).
We know that the rule we want to alter to do this is contained inside the second
stylesheet applied to the page, so we grab a reference to it using
[`document.styleSheets[1]`](/en-US/docs/Web/API/Document/styleSheets).
We then loop through the different rules contained inside the stylesheet, which are
contained in the array found at
[`stylesheet.cssRules`](/en-US/docs/Web/API/CSSStyleSheet/cssRules);
for each one, we check whether its
[`CSSStyleRule.selectorText`](/en-US/docs/Web/API/CSSStyleRule/selectorText)
property is equal to the selector `.box p`, which indicates it is the one we
want.
If so, we store a reference to this `CSSStyleRule` object in a variable. We
then use three functions to generate random values for the properties in question, and
update the rule with these values. In each case, this is done with the
`setProperty()` method, for example `boxParaRule.style.setProperty('border', newBorder);`.
### HTML
```html
<div class="controls">
<button class="border">Border</button>
<button class="bgcolor">Background</button>
<button class="color">Text</button>
</div>
<div class="box">
<p>Box</p>
</div>
```
### CSS
```css
html {
background: orange;
font-family: sans-serif;
height: 100%;
}
body {
height: inherit;
width: 80%;
min-width: 500px;
max-width: 1000px;
margin: 0 auto;
}
.controls {
display: flex;
justify-content: space-around;
align-items: center;
}
div button {
flex: 1;
margin: 20px;
height: 30px;
line-height: 30px;
}
.box {
display: flex;
justify-content: center;
align-items: center;
height: calc(100% - 70px);
}
.box p {
width: 50%;
text-align: center;
font-weight: bold;
font-size: 40px;
height: 150px;
line-height: 150px;
background: red;
border: 5px solid purple;
color: white;
transition: all 1s;
}
```
### JavaScript
```js
const borderBtn = document.querySelector(".border");
const bgColorBtn = document.querySelector(".bgcolor");
const colorBtn = document.querySelector(".color");
const box = document.querySelector(".box");
function random(min, max) {
const num = Math.floor(Math.random() * (max - min)) + min;
return num;
}
function randomColor() {
return `rgb(${random(0, 255)} ${random(0, 255)} ${random(0, 255)})`;
}
const stylesheet = document.styleSheets[1];
const boxParaRule = [...stylesheet.cssRules].find(
(r) => r.selectorText === ".box p",
);
function setRandomBorder() {
const newBorder = `${random(1, 50)}px solid ${randomColor()}`;
boxParaRule.style.setProperty("border", newBorder);
}
function setRandomBgColor() {
const newBgColor = randomColor();
boxParaRule.style.setProperty("background-color", newBgColor);
}
function setRandomColor() {
const newColor = randomColor();
boxParaRule.style.setProperty("color", newColor);
}
borderBtn.addEventListener("click", setRandomBorder);
bgColorBtn.addEventListener("click", setRandomBgColor);
colorBtn.addEventListener("click", setRandomColor);
```
### Result
{{EmbedLiveSample('Examples', '100%', 400)}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssstyledeclaration | data/mdn-content/files/en-us/web/api/cssstyledeclaration/getpropertycssvalue/index.md | ---
title: "CSSStyleDeclaration: getPropertyCSSValue() method"
short-title: getPropertyCSSValue()
slug: Web/API/CSSStyleDeclaration/getPropertyCSSValue
page-type: web-api-instance-method
status:
- deprecated
browser-compat: api.CSSStyleDeclaration.getPropertyCSSValue
---
{{ APIRef("CSSOM") }} {{deprecated_header}}
The **CSSStyleDeclaration.getPropertyCSSValue()**
method interface returns a {{domxref('CSSValue')}} containing the CSS value for a
property. Note that it returns `null` if the property name is a
shorthand 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:
>
> - {{domxref("CSSStyleDeclaration.getPropertyValue()")}} of the untyped [CSS Object Model](/en-US/docs/Web/API/CSS_Object_Model), widely supported, or
> - {{domxref("Element.computedStyleMap()")}} of the modern [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API), less supported and considered experimental.
## Syntax
```js-nolint
getPropertyCSSValue(property)
```
### Parameters
- `property`
- : A string representing the property name to be retrieved.
### Return value
A {{domxref('CSSValue')}} containing the CSS value for a property. If none exists, returns `null`.
## Examples
The following JavaScript code gets an object containing the computed RGB values of
the `color` CSS property:
```js
const style = window.getComputedStyle(elem, null);
const rgbObj = style.getPropertyCSSValue("color").getRGBColorValue();
```
## 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/cssstyledeclaration | data/mdn-content/files/en-us/web/api/cssstyledeclaration/getpropertyvalue/index.md | ---
title: "CSSStyleDeclaration: getPropertyValue() method"
short-title: getPropertyValue()
slug: Web/API/CSSStyleDeclaration/getPropertyValue
page-type: web-api-instance-method
browser-compat: api.CSSStyleDeclaration.getPropertyValue
---
{{ APIRef("CSSOM") }}
The **CSSStyleDeclaration.getPropertyValue()** method interface returns a
string containing the value of a specified CSS property.
## Syntax
```js-nolint
getPropertyValue(property)
```
### Parameters
- `property`
- : A string representing the property name (in hyphen case) to be checked.
### Return value
A string containing the value of the property. If not set, returns the empty string.
## Examples
The following JavaScript code queries the value of the `margin` property in
a CSS selector rule:
```js
const declaration = document.styleSheets[0].cssRules[0].style;
const value = declaration.getPropertyValue("margin"); // "1px 2px"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/radionodelist/index.md | ---
title: RadioNodeList
slug: Web/API/RadioNodeList
page-type: web-api-interface
browser-compat: api.RadioNodeList
---
{{APIRef("HTML DOM")}}
The **`RadioNodeList`** interface represents a collection of elements in a {{HTMLElement("form")}} or a {{HTMLElement("fieldset")}} element, returned by a call to {{domxref("HTMLFormControlsCollection.namedItem()")}}.
{{InheritanceDiagram}}
## Instance properties
_The `RadioNodeList` interface inherits the properties of_ {{domxref("NodeList")}}.
- {{domxref("RadioNodeList.value")}}
- : If the underlying element collection contains radio buttons, the `value` property represents the checked radio button. On retrieving the `value` property, the `value` of the currently `checked` radio button is returned as a string. If the collection does not contain any radio buttons or none of the radio buttons in the collection is in `checked` state, the empty string is returned. On setting the `value` property, the first radio button input element whose `value` property is equal to the new value will be set to `checked`.
## Instance methods
_The `RadioNodeList` interface inherits the methods of_ {{domxref("NodeList")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{HTMLElement("form")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("input")}} elements.
| 0 |
data/mdn-content/files/en-us/web/api/radionodelist | data/mdn-content/files/en-us/web/api/radionodelist/value/index.md | ---
title: "RadioNodeList: value property"
short-title: value
slug: Web/API/RadioNodeList/value
page-type: web-api-instance-property
browser-compat: api.RadioNodeList.value
---
{{ APIRef("HTML DOM") }}
If the underlying element collection contains radio buttons, the
**`RadioNodeList.value`** property represents the checked radio
button. On retrieving the `value` property, the `value` of the
currently `checked` radio button is returned as a string. If the collection
does not contain any radio buttons or none of the radio buttons in the collection is in
`checked` state, the empty string is returned. On setting the
`value` property, the first radio button input element whose
`value` property is equal to the new value will be set to
`checked`.
## Syntax
```js-nolint
value = radioNodeList.value
radioNodeList.value = string
```
## Example
### HTML
```html
<form>
<label><input type="radio" name="color" value="blue" />Blue</label>
<label><input type="radio" name="color" value="red" />Red</label>
</form>
```
### JavaScript
```js
// Get the form
const form = document.forms[0];
// Get the form's radio buttons
const radios = form.elements["color"];
// Choose the "red" option
radios.value = "red";
```
### Result
{{EmbedLiveSample("Example")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{HTMLElement("form")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("input")}}
elements.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/compression_streams_api/index.md | ---
title: Compression Streams API
slug: Web/API/Compression_Streams_API
page-type: web-api-overview
browser-compat: api.CompressionStream
---
{{DefaultAPISidebar("Compression Streams API")}}
The **Compression Streams API** provides a JavaScript API for compressing and decompressing streams of data using the gzip or deflate formats.
Built in compression means that JavaScript applications will not need to include a compression library, which makes the download size of the application smaller.
## Interfaces
- {{domxref("CompressionStream")}}
- : Compresses a stream of data.
- {{domxref("DecompressionStream")}}
- : Decompresses a stream of data.
## Examples
In this example a stream is compressed using gzip compression.
```js
const compressedReadableStream = inputReadableStream.pipeThrough(
new CompressionStream("gzip"),
);
```
In the following example a function decompresses a blob using gzip.
```js
async function DecompressBlob(blob) {
const ds = new DecompressionStream("gzip");
const decompressedStream = blob.stream().pipeThrough(ds);
return await new Response(decompressedStream).blob();
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/webglsampler/index.md | ---
title: WebGLSampler
slug: Web/API/WebGLSampler
page-type: web-api-interface
browser-compat: api.WebGLSampler
---
{{APIRef("WebGL")}}
The **`WebGLSampler`** interface is part of the [WebGL 2](/en-US/docs/Web/API/WebGL_API) API and stores sampling parameters for {{domxref("WebGLTexture")}} access inside of a shader.
{{InheritanceDiagram}}
When working with `WebGLSampler` objects, the following methods of the {{domxref("WebGL2RenderingContext")}} are useful:
- {{domxref("WebGL2RenderingContext.createSampler()")}}
- {{domxref("WebGL2RenderingContext.deleteSampler()")}}
- {{domxref("WebGL2RenderingContext.isSampler()")}}
- {{domxref("WebGL2RenderingContext.bindSampler()")}}
- {{domxref("WebGL2RenderingContext.getSamplerParameter()")}}
## Examples
### Creating a `WebGLSampler` object
in this example, `gl` must be a {{domxref("WebGL2RenderingContext")}}. `WebGLSampler` objects are not available in WebGL 1.
```js
const sampler = gl.createSampler();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/errorevent/index.md | ---
title: ErrorEvent
slug: Web/API/ErrorEvent
page-type: web-api-interface
browser-compat: api.ErrorEvent
---
{{APIRef("HTML DOM")}}
The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files.
{{InheritanceDiagram}}
## Instance properties
_Also inherits properties from its parent {{domxref("Event")}}_.
- {{domxref("ErrorEvent.message")}} {{ReadOnlyInline}}
- : A string containing a human-readable error message describing the problem. Lacking a [`crossorigin`](/en-US/docs/Web/HTML/Global_attributes#crossorigin) setting reduces error logging.
- {{domxref("ErrorEvent.filename")}} {{ReadOnlyInline}}
- : A string containing the name of the script file in which the error occurred.
- {{domxref("ErrorEvent.lineno")}} {{ReadOnlyInline}}
- : An `integer` containing the line number of the script file on which the error occurred.
- {{domxref("ErrorEvent.colno")}} {{ReadOnlyInline}}
- : An `integer` containing the column number of the script file on which the error occurred.
- {{domxref("ErrorEvent.error")}} {{ReadOnlyInline}}
- : A JavaScript `Object` that is concerned by the event.
## Constructor
- {{domxref("ErrorEvent.ErrorEvent", "ErrorEvent()")}}
- : Creates an `ErrorEvent` event with the given parameters.
## Instance methods
_Inherits methods from its parent {{domxref("Event")}}_.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers), most likely objects to raise such an event
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/xrmediabinding/index.md | ---
title: XRMediaBinding
slug: Web/API/XRMediaBinding
page-type: web-api-interface
status:
- experimental
browser-compat: api.XRMediaBinding
---
{{APIRef("WebXR Device API")}} {{secureContext_header}}{{SeeCompatTable}}
The **`XRMediaBinding`** interface is used to create layers that display the content of an {{domxref("HTMLVideoElement")}}.
> **Note:**
> Only the video frames will be displayed in the layer. Video controls need to be implemented separately and must be drawn in another layer.
## Constructor
- {{domxref("XRMediaBinding.XRMediaBinding", "XRMediaBinding()")}} {{Experimental_Inline}}
- : Creates a new `XRMediaBinding` object for the specified {{domxref("XRSession")}}.
## Instance methods
- {{domxref("XRMediaBinding.createCylinderLayer()")}} {{Experimental_Inline}}
- : Returns an {{domxref("XRCylinderLayer")}} object bound to an {{domxref("HTMLVideoElement")}}.
- {{domxref("XRMediaBinding.createEquirectLayer()")}} {{Experimental_Inline}}
- : Returns an {{domxref("XREquirectLayer")}} object bound to an {{domxref("HTMLVideoElement")}}.
- {{domxref("XRMediaBinding.createQuadLayer()")}} {{Experimental_Inline}}
- : Returns an {{domxref("XRQuadLayer")}} object bound to an {{domxref("HTMLVideoElement")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLVideoElement")}}
- {{domxref("XRCylinderLayer")}}, {{domxref("XREquirectLayer")}}, {{domxref("XRQuadLayer")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrmediabinding | data/mdn-content/files/en-us/web/api/xrmediabinding/createquadlayer/index.md | ---
title: "XRMediaBinding: createQuadLayer() method"
short-title: createQuadLayer()
slug: Web/API/XRMediaBinding/createQuadLayer
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRMediaBinding.createQuadLayer
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}
The **`createQuadLayer()`** method of the {{domxref("XRMediaBinding")}} interface returns an {{domxref("XRQuadLayer")}} object which is a layer that takes up a flat rectangular space in the virtual environment.
## Syntax
```js-nolint
createQuadLayer(video, options)
```
### Parameters
- `video`
- : An {{domxref("HTMLVideoElement")}} to display.
- `options`
- : An object to configure the {{domxref("XRQuadLayer")}}. The object can have the following properties and `space` is required:
- `height` {{optional_inline}}
- : A number specifying the height of the layer.
- `invertStereo` {{optional_inline}}
- : A boolean specifying if the natural location of each view in the video should be inverted. By default `false`.
- `layout` {{optional_inline}}
- : A string indicating the layout of the video. Possible values:
- `default`
- : The layer accommodates all views of the session.
- `mono`
- : A single {{domxref("XRSubImage")}} is allocated and presented to both eyes.
- `stereo`
- : The user agent decides how it allocates the {{domxref("XRSubImage")}} (one or two) and the layout (top/bottom or left/right). It is recommended to use the `texture-array` texture type for `stereo` layouts.
- `stereo-left-right`
- : A single {{domxref("XRSubImage")}} is allocated. Left eye gets the left area of the texture, right eye the right. This layout is designed to minimize draw calls for content that is already in stereo (for example stereo videos or images).
- `stereo-top-bottom`
- : A single {{domxref("XRSubImage")}} is allocated. Left eye gets the top area of the texture, right eye the bottom. This layout is designed to minimize draw calls for content that is already in stereo (for example stereo videos or images).
The default value is `mono`.
- `space` **Required**
- : An {{domxref("XRSpace")}} object defining the layer's spatial relationship with the user's physical environment.
- `transform` {{optional_inline}}
- : An {{domxref("XRRigidTransform")}} object defining the offset and orientation relative to `space`.
- `width` {{optional_inline}}
- : A number specifying the width of the layer.
### Return value
An {{domxref("XRQuadLayer")}} object.
## Examples
### Creating an `XRQuadLayer` to display a video
Create an {{domxref("XRMediaBinding")}} and use an {{domxref("HTMLVideoElement")}} that is passed into `createQuadLayer()`. Configure the quad layer using the options listed above and present the layer to the XR device by adding it to the `layers` render state in {{domxref("XRSession.updateRenderState()")}}.
```js
function onXRSessionStarted(xrSession) {
const xrMediaBinding = new XRMediaBinding(xrSession);
const video = document.createElement("video");
video.src = "just-fascination.mp4";
const videoLayer = xrMediaBinding.createQuadLayer(video, {
space: xrReferenceSpace,
});
xrSession.updateRenderState({
layers: [videoLayer],
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRQuadLayer")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrmediabinding | data/mdn-content/files/en-us/web/api/xrmediabinding/xrmediabinding/index.md | ---
title: "XRMediaBinding: XRMediaBinding() constructor"
short-title: XRMediaBinding()
slug: Web/API/XRMediaBinding/XRMediaBinding
page-type: web-api-constructor
status:
- experimental
browser-compat: api.XRMediaBinding.XRMediaBinding
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}
The **`XRMediaBinding()`** constructor creates and returns a new {{domxref("XRMediaBinding")}} object.
## Syntax
```js-nolint
new XRMediaBinding(session)
```
### Parameters
- `session`
- : An {{domxref("XRSession")}} object specifying the WebXR session for which to create the media binding.
### Return value
A newly-created {{domxref("XRMediaBinding")}}.
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the new `XRMediaBinding` could not be created due to one of a number of possible state errors:
- The {{domxref("XRSession")}} specified by `session` has already been stopped.
- The specified `session` is not immersive.
## Examples
### Creating a new `XRMediaBinding`
The following example creates a new media binding for a session to create an {{domxref("XRQuadLayer")}} to display a video layer in the scene.
```js
const xrMediaBinding = new XRMediaBinding(xrSession);
const video = document.createElement("video");
video.src = "just-fascination.mp4";
const layer = xrMediaBinding.createQuadLayer(video);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRWebGLBinding")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrmediabinding | data/mdn-content/files/en-us/web/api/xrmediabinding/createcylinderlayer/index.md | ---
title: "XRMediaBinding: createCylinderLayer() method"
short-title: createCylinderLayer()
slug: Web/API/XRMediaBinding/createCylinderLayer
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRMediaBinding.createCylinderLayer
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}
The **`createCylinderLayer()`** method of the {{domxref("XRMediaBinding")}} interface returns an {{domxref("XRCylinderLayer")}} object which is a layer that takes up a curved rectangular space in the virtual environment.
## Syntax
```js-nolint
createCylinderLayer(video, options)
```
### Parameters
- `video`
- : An {{domxref("HTMLVideoElement")}} to display.
- `options`
- : An object to configure the {{domxref("XRCylinderLayer")}}. The object can have the following properties and `space` is required:
- `aspectRatio` {{optional_inline}}
- : A number indicating the ratio of the visible cylinder section. It is the ratio of the width of the visible section of the cylinder divided by its height. The width is calculated by multiplying the `radius` with the `centralAngle`.
- `centralAngle` {{optional_inline}}
- : A number indicating the angle in radians of the visible section of the cylinder. Default value: `0.78539` (Ο / 4).
- `invertStereo` {{optional_inline}}
- : A boolean specifying if the natural location of each view in the video should be inverted. By default `false`.
- `layout` {{optional_inline}}
- : A string indicating the layout of the video. Possible values:
- `default`
- : The layer accommodates all views of the session.
- `mono`
- : A single {{domxref("XRSubImage")}} is allocated and presented to both eyes.
- `stereo`
- : The user agent decides how it allocates the {{domxref("XRSubImage")}} (one or two) and the layout (top/bottom or left/right). It is recommended to use the `texture-array` texture type for `stereo` layouts.
- `stereo-left-right`
- : A single {{domxref("XRSubImage")}} is allocated. Left eye gets the left area of the texture, right eye the right. This layout is designed to minimize draw calls for content that is already in stereo (for example stereo videos or images).
- `stereo-top-bottom`
- : A single {{domxref("XRSubImage")}} is allocated. Left eye gets the top area of the texture, right eye the bottom. This layout is designed to minimize draw calls for content that is already in stereo (for example stereo videos or images).
The default value is `mono`.
- `radius` {{optional_inline}}
- : A number indicating the radius of the cylinder. Default value `2.0`.
- `space` **Required**
- : An {{domxref("XRSpace")}} object defining the layer's spatial relationship with the user's physical environment.
- `transform` {{optional_inline}}
- : An {{domxref("XRRigidTransform")}} object defining the offset and orientation relative to `space`.
### Return value
An {{domxref("XRCylinderLayer")}} object.
## Examples
### Creating an `XRCylinderLayer` to display a video
Create an {{domxref("XRMediaBinding")}} and use an {{domxref("HTMLVideoElement")}} that is passed into `createCylinderLayer()`. Configure the quad layer using the options listed above and present the layer to the XR device by adding it to the `layers` render state in {{domxref("XRSession.updateRenderState()")}}.
```js
function onXRSessionStarted(xrSession) {
const xrMediaBinding = new XRMediaBinding(xrSession);
const video = document.createElement("video");
video.src = "just-fascination.mp4";
const videoLayer = xrMediaBinding.createCylinderLayer(video, {
space: xrReferenceSpace,
});
xrSession.updateRenderState({
layers: [videoLayer],
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRCylinderLayer")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrmediabinding | data/mdn-content/files/en-us/web/api/xrmediabinding/createequirectlayer/index.md | ---
title: "XRMediaBinding: createEquirectLayer() method"
short-title: createEquirectLayer()
slug: Web/API/XRMediaBinding/createEquirectLayer
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.XRMediaBinding.createEquirectLayer
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}
The **`createEquirectLayer()`** method of the {{domxref("XRMediaBinding")}} interface returns an {{domxref("XREquirectLayer")}} object which is a layer that maps an equirectangular coded data onto the inside of a sphere.
## Syntax
```js-nolint
createEquirectLayer(video, options)
```
### Parameters
- `video`
- : An {{domxref("HTMLVideoElement")}} to display.
- `options`
- : An object to configure the {{domxref("XREquirectLayer")}}. The object can have the following properties and `space` is required:
- `centralHorizontalAngle` {{optional_inline}}
- : A number indicating the central horizontal angle in radians for the sphere. Default value: `6.28318` (2Ο).
- `invertStereo` {{optional_inline}}
- : A boolean specifying if the natural location of each view in the video should be inverted. By default `false`.
- `layout` {{optional_inline}}
- : A string indicating the layout of the video. Possible values:
- `default`
- : The layer accommodates all views of the session.
- `mono`
- : A single {{domxref("XRSubImage")}} is allocated and presented to both eyes.
- `stereo`
- : The user agent decides how it allocates the {{domxref("XRSubImage")}} (one or two) and the layout (top/bottom or left/right). It is recommended to use the `texture-array` texture type for `stereo` layouts.
- `stereo-left-right`
- : A single {{domxref("XRSubImage")}} is allocated. Left eye gets the left area of the texture, right eye the right. This layout is designed to minimize draw calls for content that is already in stereo (for example stereo videos or images).
- `stereo-top-bottom`
- : A single {{domxref("XRSubImage")}} is allocated. Left eye gets the top area of the texture, right eye the bottom. This layout is designed to minimize draw calls for content that is already in stereo (for example stereo videos or images).
The default value is `mono`.
- `lowerVerticalAngle` {{optional_inline}}
- : A number indicating the lower vertical angle in radians for the sphere. Default value: `-1.570795` (-Ο/2).
- `radius` {{optional_inline}}
- : A number indicating the radius of the sphere. Default value `0.0`.
- `space` **Required**
- : An {{domxref("XRSpace")}} object defining the layer's spatial relationship with the user's physical environment.
- `transform` {{optional_inline}}
- : An {{domxref("XRRigidTransform")}} object defining the offset and orientation relative to `space`.
- `upperVerticalAngle` {{optional_inline}}
- : A number indicating the upper vertical angle in radians for the sphere. Default value: `1.570795` (Ο/2).
### Return value
An {{domxref("XREquirectLayer")}} object.
## Examples
### Creating an `XREquirectLayer` to display a video
Create an {{domxref("XRMediaBinding")}} and use an {{domxref("HTMLVideoElement")}} that is passed into `createEquirectLayer()`. Configure the quad layer using the options listed above and present the layer to the XR device by adding it to the `layers` render state in {{domxref("XRSession.updateRenderState()")}}.
```js
function onXRSessionStarted(xrSession) {
const xrMediaBinding = new XRMediaBinding(xrSession);
const video = document.createElement("video");
video.src = "just-fascination.mp4";
const videoLayer = xrMediaBinding.createEquirectLayer(video, {
space: xrReferenceSpace,
});
xrSession.updateRenderState({
layers: [videoLayer],
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XREquirectLayer")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmlslotelement/index.md | ---
title: HTMLSlotElement
slug: Web/API/HTMLSlotElement
page-type: web-api-interface
browser-compat: api.HTMLSlotElement
---
{{APIRef('Web Components')}}
The **`HTMLSlotElement`** interface of the [Shadow DOM API](/en-US/docs/Web/API/Web_components/Using_shadow_DOM) enables access to the name and assigned nodes of an HTML {{HTMLElement("slot")}} element.
{{InheritanceDiagram}}
## Instance properties
_Also inherits properties from its parent interface, {{domxref("HTMLElement")}}._
- {{domxref('HTMLSlotElement.name')}}
- : A string used to get and set the slot's name.
## Instance methods
_Also inherits methods from its parent interface, {{domxref("HTMLElement")}}._
- {{domxref('HTMLSlotElement.assign()')}}
- : Sets the manually assigned nodes for this slot to the given nodes.
- {{domxref('HTMLSlotElement.assignedNodes()')}}
- : Returns a sequence of the nodes assigned to this slot. If the `flatten` option is set to `true`, it returns a sequence of both the nodes assigned to this slot, and the nodes assigned to any other slots that are descendants of this slot. If no assigned nodes are found, it returns the slot's fallback content.
- {{domxref('HTMLSlotElement.assignedElements()')}}
- : Returns a sequence of the elements assigned to this slot (and no other nodes). If the `flatten` option is set to `true`, it returns a sequence of both the elements assigned to this slot, and the elements assigned to any other slots that are descendants of this slot. If no assigned elements are found, it returns the slot's fallback content.
## Events
_Also inherits events from its parent interface, {{domxref("HTMLElement")}}._
Listen to these events using {{DOMxRef("EventTarget.addEventListener", "addEventListener()")}} or by assigning an event listener to the `oneventname` property of this interface.
- {{domxref('HTMLSlotElement.slotchange_event', 'slotchange')}}
- : Fired on an `HTMLSlotElement` instance ([`<slot>`](/en-US/docs/Web/HTML/Element/slot) element) when the node(s) contained in that slot change.
## Examples
The following snippet is taken from our [slotchange example](https://github.com/mdn/web-components-examples/tree/main/slotchange) ([see it live also](https://mdn.github.io/web-components-examples/slotchange/)).
```js
let slots = this.shadowRoot.querySelectorAll("slot");
slots[1].addEventListener("slotchange", (e) => {
let nodes = slots[1].assignedNodes();
console.log(
`Element in Slot "${slots[1].name}" changed to "${nodes[0].outerHTML}".`,
);
});
```
Here we grab references to all the slots, then add a slotchange event listener to the 2nd slot in the template β which is the one that keeps having its contents changed in the example.
Every time the element inserted in the slot changes, we log a report to the console saying which slot has changed, and what the new node inside the slot is.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlslotelement | data/mdn-content/files/en-us/web/api/htmlslotelement/name/index.md | ---
title: "HTMLSlotElement: name property"
short-title: name
slug: Web/API/HTMLSlotElement/name
page-type: web-api-instance-property
browser-compat: api.HTMLSlotElement.name
---
{{APIRef("Shadow DOM API")}}
The **`name`** property of the {{domxref("HTMLSlotElement")}}
interface returns or sets the slot name. A slot is a placeholder inside a web component
that users can fill with their own markup.
## Value
A string.
## Examples
The following snippet is taken from our [slotchange example](https://github.com/mdn/web-components-examples/tree/main/slotchange) ([See it live](https://mdn.github.io/web-components-examples/slotchange/)).
```js
let slots = this.shadowRoot.querySelectorAll("slot");
slots[1].addEventListener("slotchange", (e) => {
let nodes = slots[1].assignedNodes();
console.log(
`Element in Slot "${slots[1].name}" changed to "${nodes[0].outerHTML}".`,
);
});
```
Here we grab references to all the slots, then add a slotchange event listener to the
2nd slot in the template β which is the one that keeps having its contents changed in
the example.
Every time the element inserted in the slot changes, we log a report to the console
saying which slot has changed, and what the new node inside the slot is.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlslotelement | data/mdn-content/files/en-us/web/api/htmlslotelement/assignednodes/index.md | ---
title: "HTMLSlotElement: assignedNodes() method"
short-title: assignedNodes()
slug: Web/API/HTMLSlotElement/assignedNodes
page-type: web-api-instance-method
browser-compat: api.HTMLSlotElement.assignedNodes
---
{{APIRef("Shadow DOM API")}}
The **`assignedNodes()`** method of the {{domxref("HTMLSlotElement")}} interface returns a sequence of the nodes assigned to this slot.
If the `flatten` option is set to `true`, it returns a sequence of both the nodes assigned to this slot, as well as the nodes assigned to any other slots that are descendants of this slot. If no assigned nodes are found, it returns the slot's fallback content.
## Syntax
```js-nolint
assignedNodes()
assignedNodes(options)
```
### Parameters
- `options` {{optional_inline}}
- : An object that sets options for the nodes to be returned. The available options are:
- `flatten`
- : A boolean value indicating whether to return the assigned nodes of any available child `<slot>` elements (`true`) or not (`false`). Defaults to `false`.
### Return value
An array of nodes.
## Examples
The following snippet is taken from our [slotchange example](https://github.com/mdn/web-components-examples/tree/main/slotchange) ([See it live](https://mdn.github.io/web-components-examples/slotchange/)).
```js
let slots = this.shadowRoot.querySelectorAll("slot");
slots[1].addEventListener("slotchange", (e) => {
let nodes = slots[1].assignedNodes();
console.log(
`Element in Slot "${slots[1].name}" changed to "${nodes[0].outerHTML}".`,
);
});
```
Here we grab references to all the slots, then add a slotchange event listener to the
2nd slot in the template β which is the one that keeps having its contents changed in
the example.
Every time the element inserted in the slot changes, we log a report to the console
saying which slot has changed, and what the new node inside the slot is.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlslotelement | data/mdn-content/files/en-us/web/api/htmlslotelement/slotchange_event/index.md | ---
title: "HTMLSlotElement: slotchange event"
short-title: slotchange
slug: Web/API/HTMLSlotElement/slotchange_event
page-type: web-api-event
browser-compat: api.HTMLSlotElement.slotchange_event
---
{{APIRef}}
The **`slotchange`** event is fired on an {{DOMxRef("HTMLSlotElement")}} instance ({{HTMLElement("slot")}} element) when the node(s) contained in that slot change.
> **Note:** the `slotchange` event doesn't fire if the children of a slotted node change β only if you change (e.g. add or delete) the actual nodes themselves.
In order to trigger a **slotchange** event, one has to set or remove the `slot` attribute.
This event is not cancelable.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("slotchange", (event) => {});
onslotchange = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
```js
element.setAttribute("slot", slotName);
// element.assignedSlot = $slot
element.removeAttribute("slot");
// element.assignedSlot = null
```
The following snippet is taken from our [slotchange example](https://github.com/mdn/web-components-examples/tree/main/slotchange) ([see it live also](https://mdn.github.io/web-components-examples/slotchange/)).
```js
let slots = this.shadowRoot.querySelectorAll("slot");
slots[1].addEventListener("slotchange", (e) => {
let nodes = slots[1].assignedNodes();
console.log(
`Element in Slot "${slots[1].name}" changed to "${nodes[0].outerHTML}".`,
);
});
```
Here we grab references to all the `<slot>`s, then add a `slotchange` event listener to the template's second slot β which is the one which has its contents changed in the example.
Every time the element inserted in the slot changes, we log a report to the console saying which slot has changed, and what the new node inside the slot is.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
{{domxref("HTMLSlotElement")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlslotelement | data/mdn-content/files/en-us/web/api/htmlslotelement/assignedelements/index.md | ---
title: "HTMLSlotElement: assignedElements() method"
short-title: assignedElements()
slug: Web/API/HTMLSlotElement/assignedElements
page-type: web-api-instance-method
browser-compat: api.HTMLSlotElement.assignedElements
---
{{APIRef("Shadow DOM API")}}
The **`assignedElements()`** method of the {{domxref("HTMLSlotElement")}}
interface returns a sequence of the elements assigned to this slot (and no
other nodes).
If the `flatten` option is set to `true`, it returns a sequence of both the elements assigned to this slot, as well as the elements assigned to any other slots that are descendants of this slot. If no assigned elements are found, it returns the slot's fallback content.
## Syntax
```js-nolint
assignedElements()
assignedElements(options)
```
### Parameters
- `options` {{optional_inline}}
- : An object that sets options for the nodes to be returned. The available options are:
- `flatten`
- : A boolean value indicating whether to return the
assigned elements of any available child `<slot>` elements
(`true`) or not (`false`). Defaults to `false`.
### Return value
An array of elements.
## Examples
```js
let slots = this.shadowRoot.querySelector("slot");
let elements = slots.assignedElements({ flatten: true });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmlslotelement | data/mdn-content/files/en-us/web/api/htmlslotelement/assign/index.md | ---
title: "HTMLSlotElement: assign() method"
short-title: assign()
slug: Web/API/HTMLSlotElement/assign
page-type: web-api-instance-method
browser-compat: api.HTMLSlotElement.assign
---
{{APIRef("Shadow DOM API")}}
The **`assign()`** method of the {{domxref("HTMLSlotElement")}} interface sets the slot's _manually assigned nodes_ to an ordered set of slottables. The manually assigned nodes set is initially empty until nodes are assigned using `assign()`.
> **Note:** you cannot mix manually (imperative) and named (declarative, automatic) slot assignments. Therefore, for this method to work, the shadow tree needs to have been [created](/en-US/docs/Web/API/Element/attachShadow) with the `slotAssignment: "manual"` option.
## Syntax
```js-nolint
assign(node1)
assign(node1, node2)
assign(node1, node2, /* β¦, */ nodeN)
```
### Parameters
- `node1`, β¦, `nodeN`
- : A set of {{domxref("Element")}} or {{domxref("Text")}} nodes.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- `NotAllowedError` {{domxref("DOMException")}}
-: Thrown when calling this method on an automatically assigned slot.
## Examples
In the example below, the `assign()` method is used to display the correct tab in a tabbed application. The function is called and passed the panel to show, which is then assigned to the slot.
```js
function UpdateDisplayTab(elem, tabIdx) {
const shadow = elem.shadowRoot;
const slot = shadow.querySelector("slot");
const panels = elem.querySelectorAll("tab-panel");
if (panels.length && tabIdx && tabIdx <= panels.length) {
slot.assign(panels[tabIdx - 1]);
} else {
slot.assign();
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Element.attachShadow()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/rtcrtpcodecparameters/index.md | ---
title: RTCRtpCodecParameters
slug: Web/API/RTCRtpCodecParameters
page-type: web-api-interface
---
{{APIRef("WebRTC")}}
The {{domxref("RTCRtpCodecParameters")}} dictionary, part of the WebRTC API, is used to describe the configuration parameters for a single media {{Glossary("codec")}}.
It's used in {{domxref("RTCRtpSender.getParameters()")}}, {{domxref("RTCRtpSender.setParameters()")}} and {{domxref("RTCRtpReceiver.getParameters()")}}.
Its also use used when calling {{domxref("RTCRtpTransceiver.setCodecPreferences()")}} to configure a transceiver's codecs before beginning the offer/answer process to establish a WebRTC peer connection.
Most of the fields in this property take values which are defined and maintained by the Internet Assigned Numbers Authority (IANA). References to relevant IANA documents are provided in the [see also](#see_also) section at the end of this article.
## Instance properties
- {{domxref("RTCRtpCodecParameters.payloadType", "payloadType")}} {{optional_inline}}
- : The [RTP payload type](https://www.iana.org/assignments/rtp-parameters/rtp-parameters.xhtml#rtp-parameters-1) used to identify this codec.
- {{domxref("RTCRtpCodecParameters.mimeType", "mimeType")}} {{optional_inline}}
- : The codec's MIME media type and subtype specified as a string of the form `"type/subtype"`. IANA maintains a [registry of valid MIME types](https://www.iana.org/assignments/rtp-parameters/rtp-parameters.xhtml#rtp-parameters-2).
- {{domxref("RTCRtpCodecParameters.clockRate", "clockRate")}} {{optional_inline}}
- : An unsigned long integer value specifying the codec's clock rate in hertz (Hz). The clock rate is the rate at which the codec's RTP timestamp advances. Most codecs have specific values or ranges of values they permit; see the [IANA payload format media type registry](https://www.iana.org/assignments/rtp-parameters/rtp-parameters.xhtml#rtp-parameters-2) for details.
- {{domxref("RTCRtpCodecParameters.channels", "channels")}} {{optional_inline}}
- : An unsigned short integer indicating the number of channels the codec should support. For example, for audio codecs, a value of 1 specifies monaural sound while 2 indicates stereo.
- {{domxref("RTCRtpCodecParameters.sdpFmtpLine", "sdpFmtpLine")}} {{optional_inline}}
- : A string containing the format-specific parameters field from the `"a=fmtp"` line in the codec's {{Glossary("SDP")}}, if one is present; see [section 5.8 of the IETF specification for JSEP](https://datatracker.ietf.org/doc/html/draft-ietf-rtcweb-jsep-24#section-5.8).
> **Note:** On an {{domxref("RTCRtpReceiver")}}, the format-specific parameters come from the SDP sent by the remote peer, while for {{domxref("RTCRtpSender")}}, they're provided by the local description.
## See also
- [Real-Time Transport Protocol (RTP) Parameters](https://www.iana.org/assignments/rtp-parameters/rtp-parameters.xhtml)
- : The IANA document providing registries of permitted values for the RTP parameters used by this dictionary.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/readablestreambyobrequest/index.md | ---
title: ReadableStreamBYOBRequest
slug: Web/API/ReadableStreamBYOBRequest
page-type: web-api-interface
browser-compat: api.ReadableStreamBYOBRequest
---
{{APIRef("Streams")}}
The **`ReadableStreamBYOBRequest`** interface of the [Streams API](/en-US/docs/Web/API/Streams_API) represents a "pull request" for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues).
`ReadableStreamBYOBRequest` objects are created in "BYOB mode" when a consumer makes a request for data and the stream's internal queue is _empty_.
(The stream will resolve the consumer's request directly if it already has buffered data).
An underlying byte source can access active BYOB requests through its controller's {{domxref("ReadableByteStreamController.byobRequest")}} property, which will be set to `null` if there is no outstanding request.
An underlying source that supports "BYOB mode" should check for {{domxref("ReadableByteStreamController.byobRequest")}} and must use it for transferring data, if present.
If data arrives from the underlying source when {{domxref("ReadableByteStreamController.byobRequest")}} is `null`, it can be queued using {{domxref("ReadableByteStreamController.enqueue()")}}.
This might happen when an underlying push source receives new data when the stream's internal buffers are not empty.
An underlying source uses the request by writing data to the BYOB request's [`view`](#readablestreambyobrequest.view) and then calling [`respond()`](#readablestreambyobrequest.respond), or by calling [`respondWithNewView()`](#readablestreambyobrequest.respondwithnewview) and passing a new view as an argument.
Note that the "new view" must actually be a view over the _same_ buffer as the original `view`, starting at the same offset.
This might be used to return a shorter buffer if the underlying source is unable to fill the entire original view.
Note that a {{domxref("ReadableByteStreamController")}} is only created for underlying sources when `type="bytes"` is specified for the source in the [`ReadableStream()` constructor](/en-US/docs/Web/API/ReadableStream/ReadableStream#type).
"BYOB mode" is enabled when either [`autoAllocateChunkSize`](/en-US/docs/Web/API/ReadableStream/ReadableStream#autoallocatechunksize) is specified in the [`ReadableController()` constructor](/en-US/docs/Web/API/ReadableStream/ReadableStream#autoallocatechunksize) or when using a {{domxref("ReadableStreamBYOBReader")}} (typically constructed by calling {{domxref("ReadableStream.getReader()")}} with the argument `{ mode: 'byob' }`).
## Constructor
None. `ReadableStreamBYOBRequest` instance is created automatically by `ReadableByteStreamController` as needed.
## Instance properties
- {{domxref("ReadableStreamBYOBRequest.view")}} {{ReadOnlyInline}}
- : Returns the current view.
This is a view on a buffer that will be transferred to the consumer when `ReadableStreamBYOBRequest.respond()` is called.
## Instance methods
- {{domxref("ReadableStreamBYOBRequest.respond()")}}
- : Signals the associated readable byte stream that the specified number of bytes were written into the current [`view`](#readablestreambyobrequest.view), which then causes the pending request from the consumer to be resolved.
Note that after this method is called the `view` is transferred and no longer modifiable.
- {{domxref("ReadableStreamBYOBRequest.respondWithNewView()")}}
- : Signals to the associated readable byte stream view passed as an argument should be transferred to the consumer of the readable byte stream.
This new view must use the same buffer as the original [`view`](#readablestreambyobrequest.view), start at the same offset, and be the same length or shorter.
Note that after this method is called the `view` is transferred and no longer modifiable.
## Examples
The following code is taken from the live example in [Using readable byte streams > Creating a readable socket push byte stream](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams#creating_a_readable_socket_push_byte_stream).
A push underlying byte source with data to transfer should first check that {{domxref("ReadableByteStreamController.byobRequest","controller.byobRequest")}} is non-`null`. Pul
A pull underlying byte source would only need this check if auto chunk allocation was not enabled and it was used with a default reader.
```js
if (controller.byobRequest) {
/* code to transfer data */
}
```
There are two ways to read data into a `ReadableStreamBYOBRequest` and then transfer it.
The first is to write the data into the {{domxref("ReadableStreamBYOBRequest.view")}} property and then call {{domxref("ReadableStreamBYOBRequest.respond()")}} to indicate the amount of data to be transferred.
After the operation the `byobRequest.view` is detached and the request should be discarded.
The code below shows this case using a hypothetical `readInto()` method to copy data into the view:
```js
const v = controller.byobRequest.view;
bytesRead = socket.readInto(v.buffer, v.byteOffset, v.byteLength);
controller.byobRequest.respond(bytesRead);
```
The other approach is to call {{domxref("ReadableStreamBYOBRequest.respondWithNewView()")}} passing your own view on the same underlying backing data.
Note that this just another way of specifying the range of the underlying buffer/memory backing that is actually transferred.
The `respondWithNewView` equivalent to the code above would be:
```js
const v = controller.byobRequest.view;
bytesRead = socket.readInto(v.buffer, v.byteOffset, v.byteLength);
const newView = new Uint8Array(v.buffer, v.byteOffset, bytesRead);
controller.byobRequest.respondWithNewView(newView);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using readable byte stream](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams)
| 0 |
data/mdn-content/files/en-us/web/api/readablestreambyobrequest | data/mdn-content/files/en-us/web/api/readablestreambyobrequest/respond/index.md | ---
title: "ReadableStreamBYOBRequest: respond() method"
short-title: respond()
slug: Web/API/ReadableStreamBYOBRequest/respond
page-type: web-api-instance-method
browser-compat: api.ReadableStreamBYOBRequest.respond
---
{{APIRef("Streams")}}
The **`respond()`** method of the {{domxref("ReadableStreamBYOBRequest")}} interface is used to signal to the associated [readable byte stream](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams) that the specified number of bytes were written into the {{domxref("ReadableStreamBYOBRequest.view")}}.
After this method is called, the {{domxref("ReadableStreamBYOBRequest/view","view")}} will be transferred and no longer modifiable.
## Syntax
```js-nolint
respond(bytesWritten)
```
### Parameters
- `bytesWritten`
- : The number of bytes written into {{domxref("ReadableStreamBYOBRequest.view")}}.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- {{jsxref("TypeError")}}
- : The request does not have an associated {{domxref("ReadableByteStreamController")}} or the view buffer is not detached/cannot be transferred into.
## Examples
The code below is taken from the live examples in [Using readable byte stream](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams).
The method is called by an underlying byte source as part of making a zero-copy transfer of data to fulfill a pending read request from a consumer.
The underlying source first writes data into the {{domxref("ReadableStreamBYOBRequest.view")}} and then calls this `respond()` method to indicate _how_ much data was copied into the buffer, and cause the data to be transferred to the reader.
The code below shows this case using a hypothetical `readInto()` method to copy data into the view:
```js
const v = controller.byobRequest.view;
bytesRead = socket.readInto(v.buffer, v.byteOffset, v.byteLength);
controller.byobRequest.respond(bytesRead);
```
After the operation the `byobRequest.view` is detached and the request should be discarded.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using readable byte stream](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams)
| 0 |
data/mdn-content/files/en-us/web/api/readablestreambyobrequest | data/mdn-content/files/en-us/web/api/readablestreambyobrequest/view/index.md | ---
title: "ReadableStreamBYOBRequest: view property"
short-title: view
slug: Web/API/ReadableStreamBYOBRequest/view
page-type: web-api-instance-property
browser-compat: api.ReadableStreamBYOBRequest.view
---
{{APIRef("Streams")}}
The **`view`** getter property of the {{domxref("ReadableStreamBYOBRequest")}} interface returns the current view.
## Value
A [typed array](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) representing the destination region to which the controller can write generated data.
`null` if the request has already been responded to, by calling {{domxref("ReadableStreamBYOBRequest.respond()")}} or {{domxref("ReadableStreamBYOBRequest.respondWithNewView()")}}.
## Examples
See the examples in {{domxref("ReadableStreamBYOBRequest")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using readable byte stream](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams)
| 0 |
data/mdn-content/files/en-us/web/api/readablestreambyobrequest | data/mdn-content/files/en-us/web/api/readablestreambyobrequest/respondwithnewview/index.md | ---
title: "ReadableStreamBYOBRequest: respondWithNewView() method"
short-title: respondWithNewView()
slug: Web/API/ReadableStreamBYOBRequest/respondWithNewView
page-type: web-api-instance-method
browser-compat: api.ReadableStreamBYOBRequest.respondWithNewView
---
{{APIRef("Streams")}}
The **`respondWithNewView()`** method of the {{domxref("ReadableStreamBYOBRequest")}} interface specifies a new view that the consumer of the associated readable byte stream should write to instead of {{domxref("ReadableStreamBYOBRequest.view")}}.
The new view must be a {{jsxref("TypedArray")}} or a {{jsxref("DataView")}} that provides a view onto the same backing memory region as {{domxref("ReadableStreamBYOBRequest.view")}}.
After this method is called, the view that was passed into the method will be transferred and no longer modifiable.
The method is intended for use cases where an underlying byte source needs to transfer a `byobRequest.view` internally before finishing its response.
For example, the source may transfer the BYOB view to a separate worker thread, and wait for the worker to transfer it back once it has been filled.
## Syntax
```js-nolint
respondWithNewView(view)
```
### Parameters
- `view`
- : A {{jsxref("TypedArray")}} or a {{jsxref("DataView")}} that the consumer of the associated readable byte stream should write to instead of {{domxref("ReadableStreamBYOBRequest.view")}}.
This must be a view onto the same backing memory region as {{domxref("ReadableStreamBYOBRequest.view")}} and occupy the same or less memory.
Specifically, it must be either the view's buffer or a transferred version, must have the same `byteOffset`, and a `byteLength` (number of bytes written) that is less than or equal to that of the view.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the source object is not a `ReadableStreamBYOBRequest`, or there is no associated controller, or the associated internal array buffer is non-existent or detached.
It may also be thrown if the `view` is zero-length when there is an active reader, or non-zero when called on a closed stream.
- {{jsxref("RangeError")}}
- : Thrown if the new `view` does not match the backing memory region of {{domxref("ReadableStreamBYOBRequest.view")}}.
For example, it is not the same buffer (or a transferred version), has a different `byteOffset`, or is larger than the memory available to the backing view.
## Examples
The view to be transferred must be of the same type as {{domxref("ReadableStreamBYOBRequest.view")}}, have the same underlying buffer and byte offset, and be the same or smaller byteLength.
For example, we might define the view and respond as shown below:
```js
const v = controller.byobRequest.view;
bytesRead = socket.readInto(v.buffer, v.byteOffset, v.byteLength);
byobRequest.respondWithNewView(
byobRequest.view.subarray(v.byteOffset, bytesRead),
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using readable byte stream](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/filesystemfileentry/index.md | ---
title: FileSystemFileEntry
slug: Web/API/FileSystemFileEntry
page-type: web-api-interface
browser-compat: api.FileSystemFileEntry
---
{{APIRef("File and Directory Entries API")}}
The **`FileSystemFileEntry`** interface of the [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction) represents a file in a file system. It offers properties describing the file's attributes, as well as the {{domxref("FileSystemFileEntry.file", "file()")}} method, which creates a {{domxref("File")}} object that can be used to read the file.
{{InheritanceDiagram}}
## Instance properties
_Inherits the properties of its parent interface, {{domxref("FileSystemEntry")}}, but has no properties unique to this interface._
## Instance methods
- {{domxref("FileSystemFileEntry.file", "file()")}}
- : Creates a new {{domxref("File")}} object which can be used to read the file.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
| 0 |
data/mdn-content/files/en-us/web/api/filesystemfileentry | data/mdn-content/files/en-us/web/api/filesystemfileentry/createwriter/index.md | ---
title: "FileSystemFileEntry: createWriter() method"
short-title: createWriter()
slug: Web/API/FileSystemFileEntry/createWriter
page-type: web-api-instance-method
status:
- deprecated
- non-standard
browser-compat: api.FileSystemFileEntry.createWriter
---
{{APIRef("File and Directories Entries API")}}{{deprecated_header}}{{Non-standard_header}}
The {{domxref("FileSystemFileEntry")}} interface's method
**`createWriter()`** returns a {{domxref("FileWriter")}} object
which can be used to write data into the file represented by the directory entry.
## Syntax
```js-nolint
createWriter(successCallback)
createWriter(successCallback, errorCallback)
```
### Parameters
- `successCallback`
- : A callback function which is called when the {{domxref("FileWriter")}} has been
created successfully; the `FileWriter` is passed into the callback as the
only parameter.
- `errorCallback` {{optional_inline}}
- : If provided, this must be a method which is called when an error occurs while trying
to create the {{domxref("FileWriter")}}. This callback receives as input a
{{domxref("FileError")}} object describing the error.
### Return value
None ({{jsxref("undefined")}}).
## Examples
This example establishes a method, `writeToFileEntry()`, which outputs a
text string to the file corresponding to the passed-in directory entry.
```js
function writeToFileEntry(entry, text) {
entry.createWriter(
(fileWriter) => {
let data = Blob([text], { type: "text/plain" });
fileWriter.write(data);
},
(fileError) => {
/* do whatever to handle the error */
},
);
}
```
The success callback for the `createWriter()` call takes the text which was
passed in and creates a new {{domxref("Blob")}} object of type `text/plain`
that contains the passed text. This blob is then output to the {{domxref("FileWriter")}}
object to be written to the file.
## Specifications
This feature is not part of any specification anymore. It is no longer on track to become a standard.
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
| 0 |
data/mdn-content/files/en-us/web/api/filesystemfileentry | data/mdn-content/files/en-us/web/api/filesystemfileentry/file/index.md | ---
title: "FileSystemFileEntry: file() method"
short-title: file()
slug: Web/API/FileSystemFileEntry/file
page-type: web-api-instance-method
browser-compat: api.FileSystemFileEntry.file
---
{{APIRef("File and Directory Entries API")}}
The {{domxref("FileSystemFileEntry")}} interface's method
**`file()`** returns a
{{domxref("File")}} object which can be used to read data from the file represented by
the directory entry.
## Syntax
```js-nolint
file(successCallback)
file(successCallback, errorCallback)
```
### Parameters
- `successCallback`
- : A callback function which is called when the {{domxref("File")}} has been created
successfully; the `File` is passed into the callback as the only parameter.
- `errorCallback` {{optional_inline}}
- : If provided, this must be a method which is called when an error occurs while trying
to create the {{domxref("File")}}. This callback receives as input a
{{domxref("DOMException")}} object describing the error.
### Return value
None ({{jsxref("undefined")}}).
## Examples
This example establishes a method, `readFile()`, reads a text file and calls
a specified callback function with the received text (in a string)
once the read is completed. If an error occurs, a specified (optional) error callback is
called.
```js
function readFile(entry, successCallback, errorCallback) {
entry.file((file) => {
let reader = new FileReader();
reader.onload = () => {
successCallback(reader.result);
};
reader.onerror = () => {
errorCallback(reader.error);
};
reader.readAsText(file);
}, errorCallback);
}
```
This function calls `file()`, specifying as its success callback a method
which proceeds to use a {{domxref("FileReader")}} to read the file as text. The
FileReader's {{domxref("FileReader/load_event", "load")}} event handler is set up to deliver the loaded string to
the `successCallback` specified when the `readFile()` method was
called; similarly, its {{domxref("FileReader/error_event", "error")}} handler is set up to call the
`errorCallback` specified.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API)
- [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/csskeyframerule/index.md | ---
title: CSSKeyframeRule
slug: Web/API/CSSKeyframeRule
page-type: web-api-interface
browser-compat: api.CSSKeyframeRule
---
{{APIRef("CSSOM")}}
The **`CSSKeyframeRule`** interface describes an object representing a set of styles for a given keyframe. It corresponds to the contents of a single keyframe of a {{cssxref("@keyframes")}} [at-rule](/en-US/docs/Web/CSS/At-rule).
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its ancestor {{domxref("CSSRule")}}._
- {{domxref("CSSKeyframeRule.keyText")}}
- : Represents the key of the keyframe, like `'10%'`, `'75%'`. The `from` keyword maps to `'0%'` and the `to` keyword maps to `'100%'`.
- {{domxref("CSSKeyframeRule.style")}} {{ReadOnlyInline}}
- : Returns a {{domxref("CSSStyleDeclaration")}} of the CSS style associated with the keyframe.
## Instance methods
_No specific methods; inherits methods from its ancestor {{domxref("CSSRule")}}._
## Examples
The CSS includes a keyframes at-rule. This will be the first {{domxref("CSSRule")}} returned by `document.styleSheets[0].cssRules`.
`myRules[0]` returns a {{domxref("CSSKeyframesRule")}} object, which will contain individual `CSSKeyFrameRule` objects for each keyframe.
```css
@keyframes slidein {
from {
transform: translateX(0%);
}
to {
transform: translateX(100%);
}
}
```
```js
let myRules = document.styleSheets[0].cssRules;
let keyframes = myRules[0]; // a CSSKeyframesRule
console.log(keyframes[0]); // a CSSKeyframeRule representing an individual keyframe.
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{cssxref("@keyframes")}}
- {{domxref("CSSKeyFramesRule")}}
| 0 |
data/mdn-content/files/en-us/web/api/csskeyframerule | data/mdn-content/files/en-us/web/api/csskeyframerule/keytext/index.md | ---
title: "CSSKeyframeRule: keyText property"
short-title: keyText
slug: Web/API/CSSKeyframeRule/keyText
page-type: web-api-instance-property
browser-compat: api.CSSKeyframeRule.keyText
---
{{APIRef("CSSOM") }}
The **`keyText`** property of the {{domxref("CSSKeyframeRule")}} interface represents the keyframe selector as a comma-separated list of percentage values. The from and to keywords map to 0% and 100%, respectively.
## Value
A string.
### Exceptions
- {{jsxref("SyntaxError")}}
- : Thrown if `keyText` is updated with an invalid keyframe selector, in which case `keyText` remains untouched.
## Examples
The CSS includes a keyframes at-rule. This will be the first {{domxref("CSSRule")}} returned by `document.styleSheets[0].cssRules`.
`myRules[0]` returns a {{domxref("CSSKeyframesRule")}} object, which will contain individual {{domxref("CSSKeyFrameRule")}} objects for each keyframe.
```css
@keyframes slidein {
from {
transform: translateX(0%);
}
to {
transform: translateX(100%);
}
}
```
```js
let myRules = document.styleSheets[0].cssRules;
let keyframes = myRules[0]; // a CSSKeyframesRule
console.log(keyframes[0].keyText); // a string containing 0%
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/csskeyframerule | data/mdn-content/files/en-us/web/api/csskeyframerule/style/index.md | ---
title: "CSSKeyframeRule: style property"
short-title: style
slug: Web/API/CSSkeyframeRule/style
page-type: web-api-instance-property
browser-compat: api.CSSKeyframeRule.style
---
{{ APIRef("CSSOM") }}
The read-only **`CSSKeyframeRule.style`** property is the {{ domxref("CSSStyleDeclaration") }} interface for the [declaration block](https://www.w3.org/TR/1998/REC-CSS2-19980512/syndata.html#block) of the {{ domxref("CSSKeyframeRule") }}.
## Value
A {{domxref("CSSStyleDeclaration")}} object, with the following properties:
- computed flag
- : Unset.
- declarations
- : The declared declarations in the rule, in the order they were specified, shorthand properties expanded to longhands.
- parent CSS rule
- : The context object, which is an alias for [this](https://heycam.github.io/webidl/#this).
- owner node
- : Null.
## Examples
The CSS includes a {{cssxref("@keyframes")}} at-rule. This will be the first {{domxref("CSSRule")}} returned by `document.styleSheets[0].cssRules`.
`myRules[0]` returns a {{domxref("CSSKeyframesRule")}} object, which will contain individual {{domxref("CSSKeyFrameRule")}} objects for each keyframe.
```css
@keyframes slidein {
from {
transform: translateX(0%);
}
to {
transform: translateX(100%);
}
}
```
```js
let myRules = document.styleSheets[0].cssRules;
let keyframes = myRules[0]; // a CSSKeyframesRule
console.log(keyframes[0].style); // a CSSStyleDeclaration
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/stylesheetlist/index.md | ---
title: StyleSheetList
slug: Web/API/StyleSheetList
page-type: web-api-interface
browser-compat: api.StyleSheetList
---
{{APIRef("CSSOM")}}
The `StyleSheetList` interface represents a list of {{domxref("CSSStyleSheet")}} objects. An instance of this object can be returned by {{domxref("Document.styleSheets")}}.
It is an array-like object but can't be iterated over using {{jsxref("Array")}} methods. However it can be iterated over in a standard {{jsxref("Statements/for", "for")}} loop over its indices, or converted to an {{jsxref("Array")}}.
> **Note:** This interface was an [attempt to create an unmodifiable list](https://stackoverflow.com/questions/74630989/why-use-domstringlist-rather-than-an-array/74641156#74641156) and only continues to be supported to not break code that's already using it. Modern APIs use types that wrap around ECMAScript array types instead, so you can treat them like ECMAScript arrays, and at the same time impose additional semantics on their usage (such as making their items read-only).
## Instance properties
- {{domxref("StyleSheetList.length")}} {{ReadOnlyInline}}
- : Returns the number of {{domxref("CSSStyleSheet")}} objects in the collection.
## Instance methods
- {{domxref("StyleSheetList.item()")}}
- : Returns the {{domxref("CSSStyleSheet")}} object at the index passed in, or `null` if no item exists for that index.
## Examples
### Get CSSStyleSheet objects with for loop
```js
const styleSheet = [];
const styleSheets = document.styleSheets;
for (let i = 0; i < styleSheets.length; i++) {
styleSheet.push(styleSheets[i]);
}
```
### Get all CSS rules for the document using Array methods
```js
const allCSS = [...document.styleSheets]
.map((styleSheet) => {
try {
return [...styleSheet.cssRules].map((rule) => rule.cssText).join("");
} catch (e) {
console.log(
"Access to stylesheet %s is denied. Ignoringβ¦",
styleSheet.href,
);
}
})
.filter(Boolean)
.join("\n");
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/stylesheetlist | data/mdn-content/files/en-us/web/api/stylesheetlist/length/index.md | ---
title: "StyleSheetList: length property"
short-title: length
slug: Web/API/StyleSheetList/length
page-type: web-api-instance-property
browser-compat: api.StyleSheetList.length
---
{{APIRef("CSSOM")}}
The **`length`** read-only property of the {{domxref("StyleSheetList")}} interface returns the number of {{domxref("CSSStyleSheet")}} objects in the collection.
## Value
An integer indicating the number of items in the collection.
## Examples
In the following example, `length` is printed to the console, and also used in a for loop to print each individual {{domxref("CSSStyleSheet")}} object to the console.
```js
let length = document.styleSheets.length;
console.log(length);
for (let i = 0; i < length; i++) {
console.log(document.styleSheets[i]);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/stylesheetlist | data/mdn-content/files/en-us/web/api/stylesheetlist/item/index.md | ---
title: "StyleSheetList: item() method"
short-title: item()
slug: Web/API/StyleSheetList/item
page-type: web-api-instance-method
browser-compat: api.StyleSheetList.item
---
{{APIRef("CSSOM")}}
The **`item()`** method of the {{domxref("StyleSheetList")}} interface returns a single {{domxref("CSSStyleSheet")}} object.
## Syntax
```js-nolint
item(index)
```
### Parameters
- `index`
- : An integer which is the index of the item in the collection to be returned.
### Return value
A {{domxref("CSSStyleSheet")}} object, or `null` if one does not exist for this index.
## Examples
In the following example, a for loop prints each individual {{domxref("CSSStyleSheet")}} object to the console, by calling `item` with the value of `i`.
```js
let list = document.styleSheets;
for (let i = 0; i < list.length; i++) {
console.log(list.item(i));
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/rtcdatachannelevent/index.md | ---
title: RTCDataChannelEvent
slug: Web/API/RTCDataChannelEvent
page-type: web-api-interface
browser-compat: api.RTCDataChannelEvent
---
{{APIRef("WebRTC")}}
The **`RTCDataChannelEvent`** interface
represents an event related to a specific {{DOMxRef("RTCDataChannel")}}.
{{InheritanceDiagram}}
## Constructor
- {{DOMxRef("RTCDataChannelEvent.RTCDataChannelEvent", "RTCDataChannelEvent()")}}
- : Creates a new `RTCDataChannelEvent`.
## Instance properties
_Also inherits properties from {{DOMxRef("Event")}}._
- {{DOMxRef("RTCDataChannelEvent.channel", "channel")}} {{ReadOnlyInline}}
- : Returns the {{domxref("RTCDataChannel")}} associated with the event.
## Examples
In this example, the `datachannel` event handler is set up to save the data channel reference and set up handlers for the events which need to be monitored. The {{domxref("RTCDataChannelEvent.channel", "channel")}} property provides the {{domxref("RTCDataChannel")}} representing the connection to the other peer.
```js
pc.ondatachannel = (event) => {
inboundDataChannel = event.channel;
inboundDataChannel.onmessage = handleIncomingMessage;
inboundDataChannel.onopen = handleChannelOpen;
inboundDataChannel.onclose = handleChannelClose;
};
```
See [A simple RTCDataChannel sample](/en-US/docs/Web/API/WebRTC_API/Simple_RTCDataChannel_sample) for another, more complete, example of how to use data channels.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
- {{domxref("RTCDataChannel")}}
- [A simple RTCDataChannel sample](/en-US/docs/Web/API/WebRTC_API/Simple_RTCDataChannel_sample)
- {{domxref("RTCPeerConnection")}} (the target interface for {{DOMxRef("RTCPeerConnection.datachannel_event", "datachannel")}} events)
| 0 |
data/mdn-content/files/en-us/web/api/rtcdatachannelevent | data/mdn-content/files/en-us/web/api/rtcdatachannelevent/channel/index.md | ---
title: "RTCDataChannelEvent: channel property"
short-title: channel
slug: Web/API/RTCDataChannelEvent/channel
page-type: web-api-instance-property
browser-compat: api.RTCDataChannelEvent.channel
---
{{APIRef("WebRTC")}}
The read-only property **`RTCDataChannelEvent.channel`**
returns the {{domxref("RTCDataChannel")}} associated with the event.
## Value
A {{domxref("RTCDataChannel")}} object representing the data channel linking the
receiving {{domxref("RTCPeerConnection")}} to its remote peer.
## Example
The first line of code in the {{DOMxRef("RTCPeerConnection.datachannel_event", "datachannel")}} event handler shown below takes
the channel from the event object and saves it locally for use by the code handling data
traffic.
```js
pc.ondatachannel = (event) => {
inboundDataChannel = event.channel;
inboundDataChannel.onmessage = handleIncomingMessage;
inboundDataChannel.onopen = handleChannelOpen;
inboundDataChannel.onclose = handleChannelClose;
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{DOMxRef("RTCPeerConnection.datachannel_event", "datachannel")}}
- {{domxref("RTCDataChannel")}}
- [A simple RTCDataChannel sample](/en-US/docs/Web/API/WebRTC_API/Simple_RTCDataChannel_sample)
- {{domxref("RTCPeerConnection")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcdatachannelevent | data/mdn-content/files/en-us/web/api/rtcdatachannelevent/rtcdatachannelevent/index.md | ---
title: "RTCDataChannelEvent: RTCDataChannelEvent() constructor"
short-title: RTCDataChannelEvent()
slug: Web/API/RTCDataChannelEvent/RTCDataChannelEvent
page-type: web-api-constructor
browser-compat: api.RTCDataChannelEvent.RTCDataChannelEvent
---
{{APIRef("WebRTC")}}
The **`RTCDataChannelEvent()`** constructor
creates a new {{domxref("RTCDataChannelEvent")}} object.
> **Note:** You will rarely if ever construct an `RTCDataChannelEvent` by hand; these
> events are normally created and sent by the WebRTC layer itself.
## Syntax
```js-nolint
new RTCDataChannelEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers always set it to `datachannel`.
- `options`
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties:
- `channel`
- : A {{domxref("RTCDataChannel")}}, representing the data channel being associated with the event.
### Return value
A new {{domxref("RTCDataChannelEvent")}} object configured as specified.
## Example
In this example, a new {{DOMxRef("RTCPeerConnection.datachannel_event", "datachannel")}} event is created. `dc` is a
data channel which already exists.
```js
const event = new RTCDataChannelEvent("datachannel", { channel: dc });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
- {{domxref("RTCDataChannel")}}
- {{domxref("RTCPeerConnection")}}
- [A simple RTCDataChannel sample](/en-US/docs/Web/API/WebRTC_API/Simple_RTCDataChannel_sample)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/reporting_api/index.md | ---
title: Reporting API
slug: Web/API/Reporting_API
page-type: web-api-overview
status:
- experimental
spec-urls: https://w3c.github.io/reporting/#intro
---
{{SeeCompatTable}}{{DefaultAPISidebar("Reporting API")}}
The Reporting API provides a generic reporting mechanism for web applications to use to make reports available based on various platform features (for example [Content Security Policy](/en-US/docs/Web/HTTP/CSP), [Permissions-Policy](/en-US/docs/Web/HTTP/Headers/Permissions-Policy), or feature deprecation reports) in a consistent manner.
## Concepts and usage
There are several different features and problems on the web platform that generate information useful to web developers when they are trying to fix bugs or improve their websites in other ways. Such information can include:
- [Content Security Policy](/en-US/docs/Web/HTTP/CSP) violations.
- [Permissions-Policy](/en-US/docs/Web/HTTP/Headers/Permissions-Policy) violations.
- Deprecated feature usage (when you are using something that will stop working soon in browsers).
- Occurrence of crashes.
- Occurrence of user-agent interventions (when the browser blocks something your code is trying to do because it is deemed a security risk for example, or just plain annoying, like auto-playing audio).
The Reporting API's purpose is to provide a consistent reporting mechanism that can be used to make such information available to developers in the form of reports represented by JavaScript objects. There are a few ways to use it, which are detailed in the sections below.
### Origins and endpoints
Each unique origin you want to retrieve reports for can be given a series of endpoints, which are URLs that can receive given reports from a user agent.
The {{httpheader("Report-To")}} HTTP header is used to specify details about the different endpoints that a user-agent has available to it for delivering reports to. You can then retrieve reports by making a request to those URLs.
The endpoints are arranged into groups; an endpoint group can work together to provide load balancing (each endpoint will receive a specified proportion of report traffic) and safeguarding against failure (fallback endpoints can be specified to use if the primary ones fail).
> **Note:** There is no absolute guarantee of report delivery β a report could still fail to be collected if a serious error occurs.
Reports sent to endpoints can be retrieved independently of the running of the websites they relate to, which is useful β a crash for example could bring down a website and stop anything running, but a report could still be obtained to give the developer some clues as to why it happened.
### Reporting observers
Reports can also be obtained via {{domxref("ReportingObserver")}} objects created via JavaScript inside the website you are aiming to get reports on. This method is not as failsafe as the `Report-To` method described above β any page crash could stop you retrieving the reports β but it is easier to set up, and more flexible.
A `ReportingObserver` object is created using the {{domxref("ReportingObserver.ReportingObserver", "ReportingObserver()")}} constructor, which is passed two parameters:
- A callback function that has available as parameters the reports available in the observer's report queue, and a copy of the same `ReportingObserver` object, so observation can be controlled directly from inside the callback. The callback runs when observation starts
- An options dictionary that allows you to specify the type of reports to collect, and whether the reports that were generated before the observer was able to be created should be observable (`buffered: true`).
Methods are then available on the observer to start collecting reports ({{domxref("ReportingObserver.observe()")}}), retrieve the reports currently in the report queue ({{domxref("ReportingObserver.takeRecords()")}}), and disconnect the observer so it can no longer collect records ({{domxref("ReportingObserver.disconnect()")}}).
### Generating reports via WebDriver
The Reporting API spec also defines a Generate Test Report [WebDriver](/en-US/docs/Web/WebDriver) extension, which allows you to simulate report generation during automation. Reports generated via WebDriver are observed by any registered `ReportObserver` objects present in the loaded website. This is not yet documented.
## Interfaces
- {{domxref("CSPViolationReportBody")}}
- : Contains details of a [Content Security Policy](/en-US/docs/Web/HTTP/CSP) violation.
- {{domxref("DeprecationReportBody")}}
- : Contains details of deprecated web platform features that a website is using.
- {{domxref("InterventionReportBody")}}
- : Contains details of an intervention report, which is generated when a request made by the website has been denied by the browser; e.g. for security reasons.
- {{domxref("Report")}}
- : An object representing a single report.
- {{domxref("ReportingObserver")}}
- : An object that can be used to collect and access reports as they are generated.
## Examples
In our [deprecation_report.html](https://mdn.github.io/dom-examples/reporting-api/deprecation_report.html) example, we create a simple reporting observer to observe usage of deprecated features on our web page:
```js
const options = {
types: ["deprecation"],
buffered: true,
};
const observer = new ReportingObserver((reports, observer) => {
reportBtn.onclick = () => displayReports(reports);
}, options);
```
We then tell it to start observing reports using {{domxref("ReportingObserver.observe()")}}; this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor:
```js
observer.observe();
```
Later on in the example we deliberately use the deprecated version of {{domxref("MediaDevices.getUserMedia()")}}:
```js
if (navigator.mozGetUserMedia) {
navigator.mozGetUserMedia(constraints, success, failure);
} else {
navigator.getUserMedia(constraints, success, failure);
}
```
This causes a deprecation report to be generated; because of the event handler we set up inside the `ReportingObserver()` constructor, we can now click the button to display the report details.
![image of a jolly bearded man with various stats displayed below it about a deprecated feature](reporting_api_example.png)
> **Note:** If you look at the [complete source code](https://github.com/mdn/dom-examples/blob/main/reporting-api/deprecation_report.html), you'll notice that we actually call the deprecated `getUserMedia()` method twice. After the first time we call {{domxref("ReportingObserver.takeRecords()")}}, which returns the first generated report and empties the queue. Because of this, when the button is pressed only the second report is listed.
## Specifications
{{Specifications}}
## Browser compatibility
Support is at an early stage right now. Firefox supports the JavaScript API and the `Report-To` header behind preferences:
- JavaScript API: `dom.reporting.enabled` (enabled in nightly only)
- HTTP header: `dom.reporting.header.enabled`
Chrome is also working on an implementation: [information about Chrome implementation](https://developer.chrome.com/docs/capabilities/web-apis/reporting-api).
## See also
- [Content Security Policy](/en-US/docs/Web/HTTP/CSP)
- [`Permissions-Policy`](/en-US/docs/Web/HTTP/Headers/Permissions-Policy)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/trustedscripturl/index.md | ---
title: TrustedScriptURL
slug: Web/API/TrustedScriptURL
page-type: web-api-interface
browser-compat: api.TrustedScriptURL
---
{{DefaultAPISidebar("Trusted Types API")}}
The **`TrustedScriptURL`** interface of the {{domxref('Trusted Types API')}} represents a string that a developer can insert into an [injection sink](/en-US/docs/Web/API/Trusted_Types_API#injection_sinks) that will parse it as a URL of an external script. These objects are created via {{domxref("TrustedTypePolicy.createScriptURL","TrustedTypePolicy.createScriptURL()")}} and therefore have no constructor.
The value of a **TrustedScriptURL** object is set when the object is created and cannot be changed by JavaScript as there is no setter exposed.
## Instance methods
- {{domxref("TrustedScriptURL.toJSON()")}}
- : Returns a JSON representation of the stored data.
- {{domxref("TrustedScriptURL.toString()")}}
- : A string containing the sanitized URL.
## Examples
The constant `sanitized` is an object created via a Trusted Types policy.
```js
const sanitized = scriptPolicy.createScriptURL(
"https://example.com/my-script.js",
);
console.log(sanitized); /* a TrustedScriptURL object */
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Prevent DOM-based cross-site scripting vulnerabilities with Trusted Types](https://web.dev/articles/trusted-types)
| 0 |
data/mdn-content/files/en-us/web/api/trustedscripturl | data/mdn-content/files/en-us/web/api/trustedscripturl/tostring/index.md | ---
title: "TrustedScriptURL: toString() method"
short-title: toString()
slug: Web/API/TrustedScriptURL/toString
page-type: web-api-instance-method
browser-compat: api.TrustedScriptURL.toString
---
{{DefaultAPISidebar("Trusted Types API")}}
The **`toString()`** method of the {{domxref("TrustedScriptURL")}} interface returns a string which may safely inserted into an [injection sink](/en-US/docs/Web/API/Trusted_Types_API#injection_sinks).
## Syntax
```js-nolint
toString()
```
### Parameters
None.
### Return value
A string containing the sanitized URL
## Examples
The constant `sanitized` is an object created via a Trusted Types policy. The `toString()` method returns a string to safely use to load a third party script.
```js
const sanitized = scriptPolicy.createScriptURL(
"https://example.com/my-script.js",
);
console.log(sanitized.toString());
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/trustedscripturl | data/mdn-content/files/en-us/web/api/trustedscripturl/tojson/index.md | ---
title: "TrustedScriptURL: toJSON() method"
short-title: toJSON()
slug: Web/API/TrustedScriptURL/toJSON
page-type: web-api-instance-method
browser-compat: api.TrustedScriptURL.toJSON
---
{{DefaultAPISidebar("Trusted Types API")}}
The **`toJSON()`** method of the {{domxref("TrustedScriptURL")}} interface returns a JSON representation of the stored data.
## Syntax
```js-nolint
toJSON()
```
### Parameters
None.
### Return value
A string containing a JSON representation of the stored data.
## Examples
The constant `sanitized` is an object created via a Trusted Types policy. The `toString()` method returns a string to safely use to load a third party script.
```js
const sanitized = scriptPolicy.createScriptURL(
"https://example.com/my-script.js",
);
console.log(sanitized.toJSON());
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/gamepad/index.md | ---
title: Gamepad
slug: Web/API/Gamepad
page-type: web-api-interface
browser-compat: api.Gamepad
---
{{APIRef("Gamepad API")}}{{SecureContext_Header}}
The **`Gamepad`** interface of the [Gamepad API](/en-US/docs/Web/API/Gamepad_API) defines an individual gamepad or other controller, allowing access to information such as button presses, axis positions, and id.
A Gamepad object can be returned in one of two ways: via the `gamepad` property of the {{domxref("Window.gamepadconnected_event", "gamepadconnected")}} and {{domxref("Window.gamepaddisconnected_event", "gamepaddisconnected")}} events, or by grabbing any position in the array returned by the {{domxref("Navigator.getGamepads()")}} method.
## Instance properties
- {{domxref("Gamepad.axes")}} {{ReadOnlyInline}}
- : An array representing the controls with axes present on the device (e.g. analog thumb sticks).
- {{domxref("Gamepad.buttons")}} {{ReadOnlyInline}}
- : An array of {{domxref("gamepadButton")}} objects representing the buttons present on the device.
- {{domxref("Gamepad.connected")}} {{ReadOnlyInline}}
- : A boolean indicating whether the gamepad is still connected to the system.
- {{domxref("Gamepad.displayId")}} {{ReadOnlyInline}} {{Deprecated_Inline}} {{Non-standard_Inline}}
- : Returns the {{domxref("VRDisplay.displayId")}} of an associated {{domxref("VRDisplay")}} (if relevant) β the `VRDisplay` that the gamepad is controlling the displayed scene of.
- {{domxref("Gamepad.hand")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : An enum defining what hand the controller is being held in, or is most likely to be held in.
- {{domxref("Gamepad.hapticActuators")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : An array containing {{domxref("GamepadHapticActuator")}} objects, each of which represents haptic feedback hardware available on the controller.
- {{domxref("Gamepad.vibrationActuator")}} {{ReadOnlyInline}} {{Non-standard_Inline}}
- : A {{domxref("GamepadHapticActuator")}} object, which represents haptic feedback hardware available on the controller.
- {{domxref("Gamepad.id")}} {{ReadOnlyInline}}
- : A string containing identifying information about the controller.
- {{domxref("Gamepad.index")}} {{ReadOnlyInline}}
- : An integer that is auto-incremented to be unique for each device currently connected to the system.
- {{domxref("Gamepad.mapping")}} {{ReadOnlyInline}}
- : A string indicating whether the browser has remapped the controls on the device to a known layout.
- {{domxref("Gamepad.pose")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A {{domxref("GamepadPose")}} object representing the pose information associated with a WebVR controller (e.g. its position and orientation in 3D space).
- {{domxref("Gamepad.timestamp")}} {{ReadOnlyInline}}
- : A {{domxref("DOMHighResTimeStamp")}} representing the last time the data for this gamepad was updated.
## Example
```js
window.addEventListener("gamepadconnected", (e) => {
console.log(
"Gamepad connected at index %d: %s. %d buttons, %d axes.",
e.gamepad.index,
e.gamepad.id,
e.gamepad.buttons.length,
e.gamepad.axes.length,
);
});
```
## 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/gamepad | data/mdn-content/files/en-us/web/api/gamepad/pose/index.md | ---
title: "Gamepad: pose property"
short-title: pose
slug: Web/API/Gamepad/pose
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.Gamepad.pose
---
{{APIRef("Gamepad")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`pose`** read-only property of the {{domxref("Gamepad")}} interface returns a {{domxref("GamepadPose")}} object representing the pose information associated with a WebVR controller (e.g. its position and orientation in 3D space).
## Value
A {{domxref("GamepadPose")}} object.
## Examples
TBC
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepad | data/mdn-content/files/en-us/web/api/gamepad/axes/index.md | ---
title: "Gamepad: axes property"
short-title: axes
slug: Web/API/Gamepad/axes
page-type: web-api-instance-property
browser-compat: api.Gamepad.axes
---
{{APIRef("Gamepad API")}}{{SecureContext_Header}}
The **`Gamepad.axes`** property of the {{domxref("Gamepad") }}
interface returns an array representing the controls with axes present on the device
(e.g. analog thumb sticks).
Each entry in the array is a floating point value in the range -1.0 β 1.0, representing
the axis position from the lowest value (-1.0) to the highest value (1.0).
## Value
An array of numbers.
## Examples
```js
function gameLoop() {
const [gp] = navigator.getGamepads();
let a = 0;
let b = 0;
if (gp.axes[0] !== 0) {
b -= gp.axes[0];
} else if (gp.axes[1] !== 0) {
a += gp.axes[1];
} else if (gp.axes[2] !== 0) {
b += gp.axes[2];
} else if (gp.axes[3] !== 0) {
a -= gp.axes[3];
}
ball.style.left = `${a * 2}px`;
ball.style.top = `${b * 2}px`;
const start = requestAnimationFrame(gameLoop);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
[Using the Gamepad API](/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepad | data/mdn-content/files/en-us/web/api/gamepad/hapticactuators/index.md | ---
title: "Gamepad: hapticActuators property"
short-title: hapticActuators
slug: Web/API/Gamepad/hapticActuators
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.Gamepad.hapticActuators
---
{{APIRef("Gamepad")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`hapticActuators`** read-only property of the {{domxref("Gamepad")}} interface returns an array containing {{domxref("GamepadHapticActuator")}} objects, each of which represents haptic feedback hardware available on the controller.
## Value
An array containing {{domxref("GamepadHapticActuator")}} objects.
## Examples
```js
const gamepad = navigator.getGamepads()[0];
gamepad.hapticActuators[0].pulse(1.0, 200);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepad | data/mdn-content/files/en-us/web/api/gamepad/displayid/index.md | ---
title: "Gamepad: displayId property"
short-title: displayId
slug: Web/API/Gamepad/displayId
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.Gamepad.displayId
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`displayId`** read-only property of the {{domxref("Gamepad")}} interface _returns the {{domxref("VRDisplay.displayId")}} of the associated {{domxref("VRDisplay")}} β the `VRDisplay` that the gamepad is controlling the displayed scene of._
A Gamepad is considered to be associated with a {{domxref("VRDisplay")}} if it reports a pose that is in the same space as the display's pose, see {{domxref("VRDisplay.getPose()")}}.
> **Note:** This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/#gamepad-getvrdisplays-attribute). It has been superseded by the [WebXR Gamepads Module](https://immersive-web.github.io/webxr-gamepads-module/).
>
> There is no direct replacement for this property. The {{domxref("Gamepad")}} object associated with an {{domxref("XRInputSource")}} can be obtained using the {{domxref("XRInputSource.gamepad")}} property.
## Value
A number representing the associated {{domxref("VRDisplay.displayId")}}. If the number is 0, then the gamepad is not associated with a VR display.
## Examples
```js
window.addEventListener("gamepadconnected", (e) => {
if (!e.gamepad.displayId) {
console.log("Gamepad connected");
} else {
console.log(
`Gamepad connected, associated with VR display ${e.gamepad.displayId}`,
);
}
});
```
## Specifications
This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/#gamepad-getvrdisplays-attribute) that has been superseded by the [WebXR Gamepads Module](https://immersive-web.github.io/webxr-gamepads-module/). It is no longer on track to becoming a standard.
Until all browsers have implemented the new [WebXR APIs](/en-US/docs/Web/API/WebXR_Device_API/Fundamentals), it is recommended to rely on frameworks, like [A-Frame](https://aframe.io/), [Babylon.js](https://www.babylonjs.com/), or [Three.js](https://threejs.org/), or a [polyfill](https://github.com/immersive-web/webxr-polyfill), to develop WebXR applications that will work across all browsers [\[1\]](https://developer.oculus.com/documentation/web/port-vr-xr/).
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepad | data/mdn-content/files/en-us/web/api/gamepad/buttons/index.md | ---
title: "Gamepad: buttons property"
short-title: buttons
slug: Web/API/Gamepad/buttons
page-type: web-api-instance-property
browser-compat: api.Gamepad.buttons
---
{{APIRef("Gamepad API")}}{{SecureContext_Header}}
The **`Gamepad.buttons`** property of the {{domxref("Gamepad")
}} interface returns an array of {{domxref("gamepadButton")}} objects representing the
buttons present on the device.
Each entry in the array is 0 if the button is not pressed, and non-zero (typically 1.0)
if the button is pressed. Each {{domxref("gamepadButton")}} object has two properties:
`pressed` and `value`:
- The `pressed` property is a boolean indicating whether the button is
currently pressed (`true`) or unpressed (`false`).
- The `value` property is a floating point value used to enable
representing analog buttons, such as the triggers on many modern gamepads. The values
are normalized to the range 0.0 β 1.0, with 0.0 representing a button that is not
pressed, and 1.0 representing a button that is fully pressed.
## Value
An array of {{domxref("gamepadButton")}} objects.
## Examples
The following code is taken from my Gamepad API button demo (you can [view the demo live](https://chrisdavidmills.github.io/gamepad-buttons/), and
[find the source code](https://github.com/chrisdavidmills/gamepad-buttons/tree/master) on GitHub.) Note the code fork β in Chrome
{{domxref("Navigator.getGamepads")}} needs a `webkit` prefix and the button
values are stores as an array of double values, whereas in Firefox
{{domxref("Navigator.getGamepads")}} doesn't need a prefix, and the button values are
stored as an array of {{domxref("GamepadButton")}} objects; it is the
{{domxref("GamepadButton.value")}} or {{domxref("GamepadButton.pressed")}} properties of
these we need to access, depending on what type of buttons they are. In this simple
example I've just allowed either.
```js
function gameLoop() {
let a = 0;
let b = 0;
if (navigator.webkitGetGamepads) {
const gp = navigator.webkitGetGamepads()[0];
if (gp.buttons[0] === 1) {
b--;
} else if (gp.buttons[1] === 1) {
a++;
} else if (gp.buttons[2] === 1) {
b++;
} else if (gp.buttons[3] === 1) {
a--;
}
} else {
const gp = navigator.getGamepads()[0];
if (gp.buttons[0].value > 0 || gp.buttons[0].pressed) {
b--;
} else if (gp.buttons[1].value > 0 || gp.buttons[1].pressed) {
a++;
} else if (gp.buttons[2].value > 0 || gp.buttons[2].pressed) {
b++;
} else if (gp.buttons[3].value > 0 || gp.buttons[3].pressed) {
a--;
}
}
ball.style.left = `${a * 2}px`;
ball.style.top = `${b * 2}px`;
const start = rAF(gameLoop);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
[Using the Gamepad API](/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepad | data/mdn-content/files/en-us/web/api/gamepad/id/index.md | ---
title: "Gamepad: id property"
short-title: id
slug: Web/API/Gamepad/id
page-type: web-api-instance-property
browser-compat: api.Gamepad.id
---
{{APIRef("Gamepad API")}}{{SecureContext_Header}}
The **`Gamepad.id`** property of the {{domxref("Gamepad") }}
interface returns a string containing some information about the controller.
The exact syntax is not strictly specified, but in Firefox it will contain three pieces
of information separated by dashes (`-`):
- Two 4-digit hexadecimal strings containing the USB vendor and product id of the
controller
- The name of the controller as provided by the driver.
For example, a PS2 controller returned **810-3-USB Gamepad**.
This information is intended to allow you to find a mapping for the controls on the
device as well as display useful feedback to the user.
## Value
A string primitive.
## Examples
```js
window.addEventListener("gamepadconnected", () => {
const gp = navigator.getGamepads()[0];
gamepadInfo.textContent = `Gamepad connected at index ${gp.index}: ${gp.id}.`;
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
[Using the Gamepad API](/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepad | data/mdn-content/files/en-us/web/api/gamepad/hand/index.md | ---
title: "Gamepad: hand property"
short-title: hand
slug: Web/API/Gamepad/hand
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.Gamepad.hand
---
{{APIRef("Gamepad")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`hand`** read-only property of the {{domxref("Gamepad")}} interface returns an enum defining what hand the controller is being held in, or is most likely to be held in.
## Value
A [`GamepadHand`](https://w3c.github.io/gamepad/extensions.html#gamepadhand-enum) enum; possible values are:
- `left` β the left hand.
- `right` β the right hand.
- `""` (Empty string) β if the other values are not applicable. E.g., the controller is held in both hands or would be fine in either.
## Examples
TBC
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
| 0 |