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/documentpictureinpictureevent | data/mdn-content/files/en-us/web/api/documentpictureinpictureevent/window/index.md | ---
title: "DocumentPictureInPictureEvent: window property"
short-title: window
slug: Web/API/DocumentPictureInPictureEvent/window
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.DocumentPictureInPictureEvent.window
---
{{APIRef("Document Picture-in-Picture API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`window`** read-only property of the
{{domxref("DocumentPictureInPictureEvent")}} interface returns a {{domxref("Window")}} instance representing the browsing context inside the `DocumentPictureInPicture` window the event was fired on.
## Value
A {{domxref("Window")}} object instance.
## Examples
```js
documentPictureInPicture.addEventListener("enter", (event) => {
const pipWindow = event.window;
console.log("Video player has entered the pip window");
const pipMuteButton = pipWindow.document.createElement("button");
pipMuteButton.textContent = "Mute";
pipMuteButton.addEventListener("click", () => {
const pipVideo = pipWindow.document.querySelector("#video");
if (!pipVideo.muted) {
pipVideo.muted = true;
pipMuteButton.textContent = "Unmute";
} else {
pipVideo.muted = false;
pipMuteButton.textContent = "Mute";
}
});
pipWindow.document.body.append(pipMuteButton);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Document Picture-in-Picture API", "Document Picture-in-Picture API", "", "nocode")}}
- [Using the Document Picture-in-Picture API](/en-US/docs/Web/API/Document_Picture-in-Picture_API/Using)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/gpuuncapturederrorevent/index.md | ---
title: GPUUncapturedErrorEvent
slug: Web/API/GPUUncapturedErrorEvent
page-type: web-api-interface
status:
- experimental
browser-compat: api.GPUUncapturedErrorEvent
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`GPUUncapturedErrorEvent`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} is the event object type for the {{domxref("GPUDevice")}} {{domxref("GPUDevice.uncapturederror_event", "uncapturederror")}} event, used for telemetry and to report unexpected errors.
Known error cases should be handled using {{domxref("GPUDevice.pushErrorScope", "pushErrorScope()")}} and {{domxref("GPUDevice.popErrorScope", "popErrorScope()")}}.
{{InheritanceDiagram}}
## Constructor
- {{domxref("GPUUncapturedErrorEvent.GPUUncapturedErrorEvent", "GPUUncapturedErrorEvent()")}} {{Experimental_Inline}}
- : Creates a new `GPUUncapturedErrorEvent` object instance.
## Instance properties
_Inherits properties from its parent, {{domxref("Event")}}._
- {{domxref("GPUUncapturedErrorEvent.error", "error")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : A {{domxref("GPUError")}} object instance providing access to the details of the error.
## Examples
You could use something like the following as a global mechanism to pick up any errors that aren't handled by error scopes and capture them.
```js
// ...
device.addEventListener("uncapturederror", (event) => {
// Re-surface the error
console.error("A WebGPU error was not captured:", event.error.message);
reportErrorToServer({
type: event.error.constructor.name,
message: event.error.message,
});
});
// ...
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
- [WebGPU Error Handling best practices](https://toji.dev/webgpu-best-practices/error-handling)
| 0 |
data/mdn-content/files/en-us/web/api/gpuuncapturederrorevent | data/mdn-content/files/en-us/web/api/gpuuncapturederrorevent/error/index.md | ---
title: "GPUUncapturedErrorEvent: error property"
short-title: error
slug: Web/API/GPUUncapturedErrorEvent/error
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GPUUncapturedErrorEvent.error
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`error`** read-only property of the
{{domxref("GPUUncapturedErrorEvent")}} interface is a {{domxref("GPUError")}} object instance providing access to the details of the error.
## Value
A {{domxref("GPUError")}} object instance.
## Examples
See the main [`GPUUncapturedErrorEvent`](/en-US/docs/Web/API/GPUUncapturedErrorEvent#examples) page for an example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
- [WebGPU Error Handling best practices](https://toji.dev/webgpu-best-practices/error-handling)
| 0 |
data/mdn-content/files/en-us/web/api/gpuuncapturederrorevent | data/mdn-content/files/en-us/web/api/gpuuncapturederrorevent/gpuuncapturederrorevent/index.md | ---
title: "GPUUncapturedErrorEvent: GPUUncapturedErrorEvent() constructor"
short-title: GPUUncapturedErrorEvent()
slug: Web/API/GPUUncapturedErrorEvent/GPUUncapturedErrorEvent
page-type: web-api-constructor
status:
- experimental
browser-compat: api.GPUUncapturedErrorEvent.GPUUncapturedErrorEvent
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`GPUUncapturedErrorEvent()`** constructor creates a new
{{domxref("GPUUncapturedErrorEvent")}} object instance.
## Syntax
```js-nolint
new GPUUncapturedErrorEvent(type, options)
```
### Parameters
- `type`
- : An enumerated value specifying the type of error. Possible values are:
- `"internal"`
- : The error is a {{domxref("GPUInternalError")}}.
- `"out-of-memory"`
- : The error is a {{domxref("GPUOutOfMemoryError")}}.
- `"validation"`
- : The error is a {{domxref("GPUValidationError")}}.
- `options`
- : An object, which can contain the following properties:
- `error`
- : A {{domxref("GPUError")}} object instance providing access to the details of the error.
## Examples
A developer would not manually use the constructor to create a `GPUUncapturedErrorEvent` object. The user agent uses this constructor to create an appropriate object when the {{domxref("GPUDevice")}} {{domxref("GPUDevice.uncapturederror_event", "uncapturederror")}} event fires to allow capturing of an unexpected error.
See the main [`GPUUncapturedErrorEvent`](/en-US/docs/Web/API/GPUUncapturedErrorEvent#examples) page for an example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
- [WebGPU Error Handling best practices](https://toji.dev/webgpu-best-practices/error-handling)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgfefloodelement/index.md | ---
title: SVGFEFloodElement
slug: Web/API/SVGFEFloodElement
page-type: web-api-interface
browser-compat: api.SVGFEFloodElement
---
{{APIRef("SVG")}}
The **`SVGFEFloodElement`** interface corresponds to the {{SVGElement("feFlood")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._
- {{domxref("SVGFEFloodElement.height")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("height")}} attribute of the given element.
- {{domxref("SVGFEFloodElement.result")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("result")}} attribute of the given element.
- {{domxref("SVGFEFloodElement.width")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("width")}} attribute of the given element.
- {{domxref("SVGFEFloodElement.x")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x")}} attribute of the given element.
- {{domxref("SVGFEFloodElement.y")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("y")}} attribute of the given element.
## Instance methods
_This interface doesn't implement any specific methods, but inherits methods from its parent interface, {{domxref("SVGElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{SVGElement("feFlood")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/index.md | ---
title: GPURenderPassEncoder
slug: Web/API/GPURenderPassEncoder
page-type: web-api-interface
status:
- experimental
browser-compat: api.GPURenderPassEncoder
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`GPURenderPassEncoder`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} encodes commands related to controlling the vertex and fragment shader stages, as issued by a {{domxref("GPURenderPipeline")}}. It forms part of the overall encoding activity of a {{domxref("GPUCommandEncoder")}}.
A render pipeline renders graphics to {{domxref("GPUTexture")}} attachments, typically intended for display in a {{htmlelement("canvas")}} element, but it could also render to textures used for other purposes that never appear onscreen. It has two main stages:
- A vertex stage, in which a vertex shader takes positioning data fed into the GPU and uses it to position a series of vertices in 3D space by applying specified effects like rotation, translation, or perspective. The vertices are then assembled into primitives such as triangles (the basic building block of rendered graphics) and rasterized by the GPU to figure out what pixels each one should cover on the drawing canvas.
- A fragment stage, in which a fragment shader computes the color for each pixel covered by the primitives produced by the vertex shader. These computations frequently use inputs such as images (in the form of textures) that provide surface details and the position and color of virtual lights.
A `GPURenderPassEncoder` object instance is created via the {{domxref("GPUCommandEncoder.beginRenderPass()")}} property.
{{InheritanceDiagram}}
## Instance properties
- {{domxref("GPURenderPassEncoder.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("GPURenderPassEncoder.beginOcclusionQuery", "beginOcclusionQuery()")}} {{Experimental_Inline}}
- : Begins an occlusion query at the specified index of the relevant {{domxref("GPUQuerySet")}} (provided as the value of the `occlusionQuerySet` descriptor property when invoking {{domxref("GPUCommandEncoder.beginRenderPass()")}} to run the render pass).
- {{domxref("GPURenderPassEncoder.draw", "draw()")}} {{Experimental_Inline}}
- : Draw primitives based on the vertex buffers provided by {{domxref("GPURenderPassEncoder.setVertexBuffer", "setVertexBuffer()")}}.
- {{domxref("GPURenderPassEncoder.drawIndexed", "drawIndexed()")}} {{Experimental_Inline}}
- : Draw indexed primitives based on the vertex and index buffers provided by {{domxref("GPURenderPassEncoder.setVertexBuffer", "setVertexBuffer()")}} and {{domxref("GPURenderPassEncoder.setIndexBuffer", "setIndexBuffer()")}}
- {{domxref("GPURenderPassEncoder.drawIndirect", "drawIndirect()")}} {{Experimental_Inline}}
- : Draw primitives using parameters read from a {{domxref("GPUBuffer")}}.
- {{domxref("GPURenderPassEncoder.drawIndexedIndirect", "drawIndexedIndirect()")}} {{Experimental_Inline}}
- : Draw indexed primitives using parameters read from a {{domxref("GPUBuffer")}}.
- {{domxref("GPURenderPassEncoder.end", "end()")}} {{Experimental_Inline}}
- : Completes recording of the current render pass command sequence.
- {{domxref("GPURenderPassEncoder.endOcclusionQuery", "endOcclusionQuery()")}} {{Experimental_Inline}}
- : Ends an active occlusion query previously started with {{domxref("GPURenderPassEncoder.beginOcclusionQuery", "beginOcclusionQuery()")}}.
- {{domxref("GPURenderPassEncoder.executeBundles", "executeBundles()")}} {{Experimental_Inline}}
- : Executes commands previously recorded into the referenced {{domxref("GPURenderBundle")}}s, as part of this render pass.
- {{domxref("GPURenderPassEncoder.insertDebugMarker", "insertDebugMarker()")}} {{Experimental_Inline}}
- : Marks a specific point in a series of encoded commands with a label.
- {{domxref("GPURenderPassEncoder.popDebugGroup", "popDebugGroup()")}} {{Experimental_Inline}}
- : Ends a debug group, which is begun with a {{domxref("GPURenderPassEncoder.pushDebugGroup", "pushDebugGroup()")}} call.
- {{domxref("GPURenderPassEncoder.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("GPURenderPassEncoder.popDebugGroup", "popDebugGroup()")}} method is invoked.
- {{domxref("GPURenderPassEncoder.setBindGroup", "setBindGroup()")}} {{Experimental_Inline}}
- : Sets the {{domxref("GPUBindGroup")}} to use for subsequent render commands, for a given index.
- {{domxref("GPURenderPassEncoder.setBlendConstant", "setBlendConstant()")}} {{Experimental_Inline}}
- : Sets the constant blend color and alpha values used with `"constant"` and `"one-minus-constant"` blend factors (as set in the descriptor of the {{domxref("GPUDevice.createRenderPipeline()")}} method, in the `blend` property).
- {{domxref("GPURenderPassEncoder.setIndexBuffer", "setIndexBuffer()")}} {{Experimental_Inline}}
- : Sets the current {{domxref("GPUBuffer")}} that will provide index data for subsequent drawing commands.
- {{domxref("GPURenderPassEncoder.setPipeline", "setPipeline()")}} {{Experimental_Inline}}
- : Sets the {{domxref("GPURenderPipeline")}} to use for this render pass.
- {{domxref("GPURenderPassEncoder.setScissorRect", "setScissorRect()")}} {{Experimental_Inline}}
- : Sets the scissor rectangle used during the rasterization stage. After transformation into viewport coordinates any fragments that fall outside the scissor rectangle will be discarded.
- {{domxref("GPURenderPassEncoder.setStencilReference", "setStencilReference()")}} {{Experimental_Inline}}
- : Sets the stencil reference value using during stencil tests with the `"replace"` stencil operation (as set in the descriptor of the {{domxref("GPUDevice.createRenderPipeline()")}} method, in the properties defining the various stencil operations).
- {{domxref("GPURenderPassEncoder.setVertexBuffer", "setVertexBuffer()")}} {{Experimental_Inline}}
- : Sets or unsets the current {{domxref("GPUBuffer")}} that will provide vertex data for subsequent drawing commands.
- {{domxref("GPURenderPassEncoder.setViewport", "setViewport()")}} {{Experimental_Inline}}
- : Sets the viewport used during the rasterization stage to linearly map from normalized device coordinates to viewport coordinates.
## Examples
In our [basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/), several commands are recorded via a {{domxref("GPUCommandEncoder")}}. Most of these commands originate from the `GPURenderPassEncoder` created via {{domxref("GPUCommandEncoder.beginRenderPass()")}}.
```js
// ...
const renderPipeline = device.createRenderPipeline(pipelineDescriptor);
// Create GPUCommandEncoder to issue commands to the GPU
// Note: render pass descriptor, command encoder, etc. are destroyed after use, fresh one needed for each frame.
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 the triangle
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);
// End the render pass
passEncoder.end();
// 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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/drawindirect/index.md | ---
title: "GPURenderPassEncoder: drawIndirect() method"
short-title: drawIndirect()
slug: Web/API/GPURenderPassEncoder/drawIndirect
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.drawIndirect
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`drawIndirect()`** method of the
{{domxref("GPURenderPassEncoder")}} interface draws primitives using parameters read from a {{domxref("GPUBuffer")}}.
## Syntax
```js-nolint
drawIndirect(indirectBuffer, indirectOffset)
```
### Parameters
- `indirectBuffer`
- : A {{domxref("GPUBuffer")}} containing the `vertexCount`, `instanceCount`, `firstVertex`, and `firstInstance` values needed to carry out the drawing operation. The buffer must contain a tightly packed block of four 32-bit unsigned integer values representing the values (16 bytes total), given in the same order as the arguments for {{domxref("GPURenderPassEncoder.draw()")}}. So for example:
```js
const uint32 = new Uint32Array(4);
uint32[0] = 3; // The vertexCount value
uint32[1] = 1; // The instanceCount value
uint32[2] = 0; // The firstVertex value
uint32[3] = 0; // The firstInstance value
// Write values into a GPUBuffer
device.queue.writeBuffer(buffer, 0, uint32, 0, uint32.length);
```
- `indirectOffset`
- : The offset, in bytes, into `indirectBuffer` where the value data begins.
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`drawIndirect()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPURenderPassEncoder")}} becomes invalid:
- `indirectBuffer`'s {{domxref("GPUBuffer.usage")}} contains the `GPUBufferUsage.INDIRECT` flag.
- `indirectOffset` + the total size specified by the value parameters in the `indirectBuffer` is less than or equal to the `indirectBuffer`'s {{domxref("GPUBuffer.size")}}.
- `indirectOffset` is a multiple of 4.
## Examples
```js
// ...
// Create GPURenderPassEncoder
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
// Set pipeline and vertex buffer
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
// Create drawIndirect values
const uint32 = new Uint32Array(4);
uint32[0] = 3;
uint32[1] = 1;
uint32[2] = 0;
uint32[3] = 0;
// Create a GPUBuffer and write the draw values into it
const drawValues = device.createBuffer({
size: 16,
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.INDIRECT,
});
device.queue.writeBuffer(drawValues, 0, uint32, 0, uint32.length);
// Draw the vertices
passEncoder.drawIndirect(drawValues, 0);
// End the render pass
passEncoder.end();
// End frame by passing array of GPUCommandBuffers 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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/setblendconstant/index.md | ---
title: "GPURenderPassEncoder: setBlendConstant() method"
short-title: setBlendConstant()
slug: Web/API/GPURenderPassEncoder/setBlendConstant
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.setBlendConstant
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`setBlendConstant()`** method of the
{{domxref("GPURenderPassEncoder")}} interface sets the constant blend color and alpha values used with `"constant"` and `"one-minus-constant"` blend factors (as set in the descriptor of the {{domxref("GPUDevice.createRenderPipeline()")}} method, in the `blend` property).
## Syntax
```js-nolint
setBlendConstant(color)
```
### Parameters
- `color`
- : An object or array representing the color to use when blending — the `r`, `g`, `b`, and `a` components are represented as floating point numbers between 0.0 and 1.0.
What follows is an object example:
```js
const color = { r: 0.0, g: 0.5, b: 1.0, a: 1.0 };
```
The array equivalent would look like this:
```js
const color = [0.0, 0.5, 1.0, 1.0];
```
> **Note:** If a `setBlendConstant()` call is not made, the blend constant color value defaults to `(0, 0, 0, 0)` for each render pass.
### Return value
None ({{jsxref("Undefined")}}).
## Examples
```js
// ...
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.setBlendConstant([1.0, 0.0, 0.0, 1.0]);
passEncoder.draw(3);
passEncoder.end();
// ...
```
## 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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/setvertexbuffer/index.md | ---
title: "GPURenderPassEncoder: setVertexBuffer() method"
short-title: setVertexBuffer()
slug: Web/API/GPURenderPassEncoder/setVertexBuffer
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.setVertexBuffer
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`setVertexBuffer()`** method of the
{{domxref("GPURenderPassEncoder")}} interface sets or unsets the current {{domxref("GPUBuffer")}} for the given slot that will provide vertex data for subsequent drawing commands.
## Syntax
```js-nolint
setVertexBuffer(slot, buffer, offset, size)
```
### Parameters
- `slot`
- : A number referencing the vertex buffer slot to set the vertex buffer for.
- `buffer`
- : A {{domxref("GPUBuffer")}} representing the buffer containing the vertex data to use for subsequent drawing commands, or `null`, in which case any previously-set buffer in the given slot is unset.
- `offset` {{optional_inline}}
- : A number representing the offset, in bytes, into `buffer` where the vertex data begins. If omitted, `offset` defaults to 0.
- `size` {{optional_inline}}
- : A number representing the size, in bytes, of the vertex data contained in `buffer`. If omitted, `size` defaults to the `buffer`'s {{domxref("GPUBuffer.size")}} - `offset`.
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`setVertexBuffer()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPURenderPassEncoder")}} becomes invalid:
- `buffer`'s {{domxref("GPUBuffer.usage")}} contains the `GPUBufferUsage.VERTEX` flag.
- `slot` is less than the {{domxref("GPUDevice")}}'s `maxVertexBuffers` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}.
- `offset` + `size` is less than or equal to the `buffer`'s {{domxref("GPUBuffer.size")}}.
- `offset` is a multiple of 4.
## Examples
### Set vertex buffer
In our [basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/), several commands are recorded via a {{domxref("GPUCommandEncoder")}}. Most of these commands originate from the `GPURenderPassEncoder` created via {{domxref("GPUCommandEncoder.beginRenderPass()")}}. `setVertexBuffer()` is used as appropriate to set the source of vertex data.
```js
// ...
const renderPipeline = device.createRenderPipeline(pipelineDescriptor);
// Create GPUCommandEncoder to issue commands to the GPU
// Note: render pass descriptor, command encoder, etc. are destroyed after use, fresh one needed for each frame.
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 the triangle
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);
// End the render pass
passEncoder.end();
// End frame by passing array of command buffers to command queue for execution
device.queue.submit([commandEncoder.finish()]);
// ...
```
### Unset vertex buffer
```js
// Set vertex buffer in slot 0
passEncoder.setVertexBuffer(0, vertexBuffer);
// Later, unset vertex buffer in slot 0
passEncoder.setVertexBuffer(0, null);
```
## 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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/setviewport/index.md | ---
title: "GPURenderPassEncoder: setViewport() method"
short-title: setViewport()
slug: Web/API/GPURenderPassEncoder/setViewport
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.setViewport
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`setViewport()`** method of the
{{domxref("GPURenderPassEncoder")}} interface sets the viewport used during the rasterization stage to linearly map from normalized device coordinates to viewport coordinates.
## Syntax
```js-nolint
setViewport(x, y, width, height, minDepth, maxDepth)
```
### Parameters
- `x`
- : A number representing the minimum X value of the viewport, in pixels.
- `y`
- : A number representing the minimum Y value of the viewport, in pixels.
- `width`
- : A number representing the width of the viewport, in pixels.
- `height`
- : A number representing the height of the viewport, in pixels.
- `minDepth`
- : A number representing the minimum depth value of the viewport.
- `maxDepth`
- : A number representing the maximum depth value of the viewport.
> **Note:** If a `setViewport()` call is not made, the default values are `(0, 0, attachment width, attachment height, 0, 1)` for each render pass.
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`setViewport()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPURenderPassEncoder")}} becomes invalid:
- `x`, `y`, `width`, and `height` are all greater than or equal to 0.
- `x` + `width` is less than or equal to the width of the render pass's render attachments (see note below).
- `y` + `height` is less than or equal to the height of the render pass's render attachments (see note below).
- `minDepth` and `maxDepth` are both inside the range 0.0–1.0 inclusive.
- `minDepth` is less than `maxDepth`.
> **Note:** See the color and depth/stencil attachments specified in the descriptor of {{domxref("GPUCommandEncoder.beginRenderPass()")}}; the width and height are based on that of the {{domxref("GPUTexture")}} that their `view`s originate from.
## Examples
### Basic snippet
In a typical canvas render, the following could be used to halve the width and height of the rendered graphics:
```js
passEncoder.setViewport(0, 0, canvas.width / 2, canvas.height / 2, 0, 1);
```
### In context
In the WebGPU Samples [reversedZ example](https://webgpu.github.io/webgpu-samples/samples/reversedZ), `setViewport` is used several times to set the viewport for the different render passes. Study the example code listing for the full context.
For example:
```js
// ...
colorPass.setViewport(
(canvas.width * m) / 2,
0,
canvas.width / 2,
canvas.height,
0,
1,
);
// ...
```
## 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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/pushdebuggroup/index.md | ---
title: "GPURenderPassEncoder: pushDebugGroup() method"
short-title: pushDebugGroup()
slug: Web/API/GPURenderPassEncoder/pushDebugGroup
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.pushDebugGroup
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`pushDebugGroup()`** method of the
{{domxref("GPURenderPassEncoder")}} interface begins a render pass debug group, which is marked with a specified label, and will contain all subsequent encoded commands up until a {{domxref("GPURenderPassEncoder.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
// ...
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
passEncoder.pushDebugGroup("mygroupmarker"); // Start labeled debug group
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);
passEncoder.popDebugGroup();
// ...
```
## 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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/insertdebugmarker/index.md | ---
title: "GPURenderPassEncoder: insertDebugMarker() method"
short-title: insertDebugMarker()
slug: Web/API/GPURenderPassEncoder/insertDebugMarker
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.insertDebugMarker
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`insertDebugMarker()`** method of the
{{domxref("GPURenderPassEncoder")}} interface marks a specific point in a series of encoded render pass 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
// ...
passEncoder.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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/setindexbuffer/index.md | ---
title: "GPURenderPassEncoder: setIndexBuffer() method"
short-title: setIndexBuffer()
slug: Web/API/GPURenderPassEncoder/setIndexBuffer
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.setIndexBuffer
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`setIndexBuffer()`** method of the
{{domxref("GPURenderPassEncoder")}} interface sets the current {{domxref("GPUBuffer")}} that will provide index data for subsequent drawing commands.
## Syntax
```js-nolint
setIndexBuffer(buffer, indexFormat, offset, size)
```
### Parameters
- `buffer`
- : A {{domxref("GPUBuffer")}} representing the buffer containing the index data to use for subsequent drawing commands.
- `indexFormat`
- : An enumerated value that defines the format of the index data contained in `buffer`. Possible values are:
- `"uint16"`
- `"uint32"`
- `offset` {{optional_inline}}
- : A number representing the offset, in bytes, into `buffer` where the index data begins. If omitted, `offset` defaults to 0.
- `size` {{optional_inline}}
- : A number representing the size, in bytes, of the index data contained in `buffer`. If omitted, `size` defaults to the `buffer`'s {{domxref("GPUBuffer.size")}} - `offset`.
#### Note on indexFormat
`indexFormat` determines both the data type of index values in a buffer and, when used with a pipeline that specifies a strip primitive topology (`"line-strip"` or `"triangle-strip"`), also determines the primitive restart value. The primitive restart value is an index value indicating that a new primitive should be started rather than continuing to construct the strip with the prior indexed vertices. The value is `0xFFFF` for `"uint16"`, or `0xFFFFFFFF` for `"uint32"`.
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`setIndexBuffer()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPURenderPassEncoder")}} becomes invalid:
- `buffer`'s {{domxref("GPUBuffer.usage")}} contains the `GPUBufferUsage.INDEX` flag.
- `offset` + `size` is less than or equal to the `buffer`'s {{domxref("GPUBuffer.size")}}.
- `offset` is a multiple of `indexFormat`'s byte size (2 for `"uint16"`, 4 for `"uint32"`).
## Examples
In the WebGPU Samples [Shadow Mapping](https://webgpu.github.io/webgpu-samples/samples/shadowMapping) example, `setIndexBuffer()` is used in two separate render passes in each animation frame, one to draw the main model and one to draw its shadow. Study the example code listing for the full context.
```js
// ...
const commandEncoder = device.createCommandEncoder();
{
const shadowPass = commandEncoder.beginRenderPass(shadowPassDescriptor);
shadowPass.setPipeline(shadowPipeline);
shadowPass.setBindGroup(0, sceneBindGroupForShadow);
shadowPass.setBindGroup(1, modelBindGroup);
shadowPass.setVertexBuffer(0, vertexBuffer);
shadowPass.setIndexBuffer(indexBuffer, "uint16");
shadowPass.drawIndexed(indexCount);
shadowPass.end();
}
{
const renderPass = commandEncoder.beginRenderPass(renderPassDescriptor);
renderPass.setPipeline(pipeline);
renderPass.setBindGroup(0, sceneBindGroupForRender);
renderPass.setBindGroup(1, modelBindGroup);
renderPass.setVertexBuffer(0, vertexBuffer);
renderPass.setIndexBuffer(indexBuffer, "uint16");
renderPass.drawIndexed(indexCount);
renderPass.end();
}
// ...
```
## 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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/popdebuggroup/index.md | ---
title: "GPURenderPassEncoder: popDebugGroup() method"
short-title: popDebugGroup()
slug: Web/API/GPURenderPassEncoder/popDebugGroup
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.popDebugGroup
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`popDebugGroup()`** method of the
{{domxref("GPURenderPassEncoder")}} interface ends a render pass debug group, which is begun with a {{domxref("GPURenderPassEncoder.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("GPURenderPassEncoder")}} becomes invalid:
- The render pass encoder's debug stack is not empty (i.e. at least one render pass debug group was previously started with {{domxref("GPURenderPassEncoder.pushDebugGroup", "pushDebugGroup()")}}).
## Examples
```js
// ...
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
passEncoder.pushDebugGroup("mygroupmarker"); // Start labeled debug group
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);
passEncoder.popDebugGroup();
// ...
```
## 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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/executebundles/index.md | ---
title: "GPURenderPassEncoder: executeBundles() method"
short-title: executeBundles()
slug: Web/API/GPURenderPassEncoder/executeBundles
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.executeBundles
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`executeBundles()`** method of the
{{domxref("GPURenderPassEncoder")}} interface executes commands previously recorded into the referenced {{domxref("GPURenderBundle")}}s, as part of this render pass.
> **Note:** After calling `executeBundles()` the currently set vertex buffers, index buffers, bind groups, and pipeline are all cleared, even if no bundles are actually executed.
## Syntax
```js-nolint
executeBundles(bundles)
```
### Parameters
- `bundles`
- : An array of {{domxref("GPURenderBundle")}} objects, containing the pre-recorded commands to execute.
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`executeBundles()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPURenderPassEncoder")}} becomes invalid.
For each {{domxref("GPURenderBundle")}}:
- If the render pass's `depthReadOnly` property (as specified in the descriptor of the originating {{domxref("GPUCommandEncoder.beginRenderPass()")}} call) is `true`, then the bundle's `depthReadOnly` property (as specified in the descriptor of the {{domxref("GPUDevice.createRenderBundleEncoder()")}} call that created the originating {{domxref("GPURenderBundleEncoder")}}) is also `true`.
- If the render pass's `stencilReadOnly` property (as specified in the descriptor of the originating {{domxref("GPUCommandEncoder.beginRenderPass()")}} call) is `true`, then the bundle's `stencilReadOnly` property (as specified in the descriptor of the {{domxref("GPUDevice.createRenderBundleEncoder()")}} call that created the originating {{domxref("GPURenderBundleEncoder")}}) is also `true`.
- The layout of the render pipeline specified in {{domxref("GPURenderPassEncoder.setPipeline()")}} (as defined in the descriptor of the originating {{domxref("GPUDevice.createRenderPipeline()")}} call) equals the layout of the render bundle pipeline specified in {{domxref("GPURenderBundleEncoder.setPipeline()")}}.
## Examples
In the WebGPU Samples [Animometer example](https://webgpu.github.io/webgpu-samples/samples/animometer), a lot of like operations are done on many different objects simultaneously. `executeBundles()` is used to reuse the work on multiple render passes to improve performance. Study the example code listing for the full context.
```js
// ...
return function doDraw(timestamp) {
if (startTime === undefined) {
startTime = timestamp;
}
uniformTime[0] = (timestamp - startTime) / 1000;
device.queue.writeBuffer(uniformBuffer, timeOffset, uniformTime.buffer);
renderPassDescriptor.colorAttachments[0].view = context
.getCurrentTexture()
.createView();
const commandEncoder = device.createCommandEncoder();
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
if (settings.renderBundles) {
passEncoder.executeBundles([renderBundle]);
} else {
recordRenderPass(passEncoder);
}
passEncoder.end();
device.queue.submit([commandEncoder.finish()]);
};
// ...
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
| 0 |
data/mdn-content/files/en-us/web/api/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/beginocclusionquery/index.md | ---
title: "GPURenderPassEncoder: beginOcclusionQuery() method"
short-title: beginOcclusionQuery()
slug: Web/API/GPURenderPassEncoder/beginOcclusionQuery
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.beginOcclusionQuery
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`beginOcclusionQuery()`** method of the
{{domxref("GPURenderPassEncoder")}} interface begins an occlusion query at the specified index of the relevant {{domxref("GPUQuerySet")}} (provided as the value of the `occlusionQuerySet` descriptor property when invoking {{domxref("GPUCommandEncoder.beginRenderPass()")}} to run the render pass).
## Syntax
```js-nolint
beginOcclusionQuery(queryIndex)
```
### Parameters
- `queryIndex`
- : The index in the {{domxref("GPUQuerySet")}} to begin the occlusion query at.
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`beginOcclusionQuery()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPURenderPassEncoder")}} becomes invalid:
- A {{domxref("GPUQuerySet")}} was specified in the `occlusionQuerySet` descriptor property when invoking the originating {{domxref("GPUCommandEncoder.beginRenderPass()")}}.
- `queryIndex` is smaller than {{domxref("GPUQuerySet.count")}}.
- The `queryIndex` has not already been written to in the same render pass.
- An occlusion query is not already active for this render pass (i.e. via a previous `beginOcclusionQuery()` call).
## Examples
```js
// ...
// Create a query set to hold the occlusion queries
const querySet = device.createQuerySet({
type: "occlusion",
count: 32,
});
// Render pass descriptor object, including the querySet
const renderPassDescriptor = {
colorAttachments: [
{
clearValue: clearColor,
loadOp: "clear",
storeOp: "store",
view: context.getCurrentTexture().createView(),
},
],
occlusionQuerySet: querySet,
};
// Begin the render pass
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
// Begin an occlusion query at index 0
passEncoder.beginOcclusionQuery(0);
// Run some rendering commands
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);
// End the occlusion query
passEncoder.endOcclusionQuery();
// ...
```
## 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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/drawindexed/index.md | ---
title: "GPURenderPassEncoder: drawIndexed() method"
short-title: drawIndexed()
slug: Web/API/GPURenderPassEncoder/drawIndexed
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.drawIndexed
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`drawIndexed()`** method of the
{{domxref("GPURenderPassEncoder")}} interface draws indexed primitives based on the vertex and index buffers provided by {{domxref("GPURenderPassEncoder.setVertexBuffer", "setVertexBuffer()")}} and {{domxref("GPURenderPassEncoder.setIndexBuffer", "setIndexBuffer()")}}.
## Syntax
```js-nolint
drawIndexed(indexCount)
drawIndexed(indexCount, instanceCount)
drawIndexed(indexCount, instanceCount, firstIndex)
drawIndexed(indexCount, instanceCount, firstIndex, baseVertex)
drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance)
```
### Parameters
- `indexCount`
- : A number defining the number of indices to draw.
- `instanceCount` {{optional_inline}}
- : A number defining the number of instances to draw. If omitted, `instanceCount` defaults to 1.
- `firstIndex` {{optional_inline}}
- : A number defining the offset into the index buffer, in indices, to begin drawing from. If omitted, `firstIndex` defaults to 0.
- `baseVertex` {{optional_inline}}
- : A number added to each index value before indexing into the vertex buffers. If omitted, `baseVertex` defaults to 0.
- `firstInstance` {{optional_inline}}
- : A number defining the first instance to draw. If omitted, `firstInstance` defaults to 0.
### Return value
None ({{jsxref("Undefined")}}).
## Examples
In the WebGPU Samples [Shadow Mapping](https://webgpu.github.io/webgpu-samples/samples/shadowMapping) example, `drawIndexed()` is used in two separate render passes in each animation frame, one to populate the shadow buffer and one to draw the primary view of the scene. Study the example code listing for the full context.
```js
// ...
const commandEncoder = device.createCommandEncoder();
{
const shadowPass = commandEncoder.beginRenderPass(shadowPassDescriptor);
shadowPass.setPipeline(shadowPipeline);
shadowPass.setBindGroup(0, sceneBindGroupForShadow);
shadowPass.setBindGroup(1, modelBindGroup);
shadowPass.setVertexBuffer(0, vertexBuffer);
shadowPass.setIndexBuffer(indexBuffer, "uint16");
shadowPass.drawIndexed(indexCount);
shadowPass.end();
}
{
const renderPass = commandEncoder.beginRenderPass(renderPassDescriptor);
renderPass.setPipeline(pipeline);
renderPass.setBindGroup(0, sceneBindGroupForRender);
renderPass.setBindGroup(1, modelBindGroup);
renderPass.setVertexBuffer(0, vertexBuffer);
renderPass.setIndexBuffer(indexBuffer, "uint16");
renderPass.drawIndexed(indexCount);
renderPass.end();
}
// ...
```
## 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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/end/index.md | ---
title: "GPURenderPassEncoder: end() method"
short-title: end()
slug: Web/API/GPURenderPassEncoder/end
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.end
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`end()`** method of the
{{domxref("GPURenderPassEncoder")}} interface completes recording of the current render pass command sequence.
## Syntax
```js-nolint
end()
```
### Parameters
None.
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`end()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPURenderPassEncoder")}} becomes invalid:
- The {{domxref("GPURenderPassEncoder")}} is open (i.e. not already ended via an `end()` call).
- There is no occlusion query (i.e. started via {{domxref("GPURenderPassEncoder.beginOcclusionQuery", "beginOcclusionQuery()")}}) active on the current render pass.
- The debug stack for the current render pass is empty (i.e. no render pass debug group is currently open, as opened by {{domxref("GPURenderPassEncoder.pushDebugGroup", "pushDebugGroup()")}}).
- The number of draw commands encoded in this render pass is less than or equal to the `maxDrawCount` property set in the {{domxref("GPUCommandEncoder.beginRenderPass()")}} descriptor.
## Examples
In our [basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/), several commands are recorded via a {{domxref("GPUCommandEncoder")}}. Most of these commands originate from the `GPURenderPassEncoder` created via {{domxref("GPUCommandEncoder.beginRenderPass()")}}. `end()` is called in an appropriate place to end the render pass.
```js
// ...
const renderPipeline = device.createRenderPipeline(pipelineDescriptor);
// Create GPUCommandEncoder to issue commands to the GPU
// Note: render pass descriptor, command encoder, etc. are destroyed after use, fresh one needed for each frame.
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 the triangle
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);
// End the render pass
passEncoder.end();
// 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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/setbindgroup/index.md | ---
title: "GPURenderPassEncoder: setBindGroup() method"
short-title: setBindGroup()
slug: Web/API/GPURenderPassEncoder/setBindGroup
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.setBindGroup
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`setBindGroup()`** method of the
{{domxref("GPURenderPassEncoder")}} interface sets the {{domxref("GPUBindGroup")}} to use for subsequent render commands, for a given index.
## Syntax
```js-nolint
setBindGroup(index, bindGroup)
setBindGroup(index, bindGroup, dynamicOffsets)
setBindGroup(index, bindGroup, dynamicOffsets, dynamicOffsetsStart,
dynamicOffsetsLength)
```
#### Parameters
- `index`
- : The index to set the bind group at. This matches the `n` index value of the corresponding [`@group(n)`](https://gpuweb.github.io/gpuweb/wgsl/#attribute-group) attribute in the shader code ({{domxref("GPUShaderModule")}}) used in the related pipeline.
- `bindGroup`
- : The {{domxref("GPUBindGroup")}} to use for subsequent render commands.
- `dynamicOffsets` {{optional_inline}}
- : A value specifying the offset, in bytes, for each entry in `bindGroup` with `hasDynamicOffset: true` set (i.e. in the descriptor of the {{domxref("GPUDevice.createBindGroupLayout()")}} call that created the {{domxref("GPUBindGroupLayout")}} object that the `bindGroup` is based on). This value can be:
- An array of numbers specifying the different offsets.
- A {{jsxref("Uint32Array")}} containing numbers specifying the offsets.
If a {{jsxref("Uint32Array")}} value is specified for `dynamicOffsets`, both of the following parameters are also required:
- `dynamicOffsetsStart`
- : A number specifying the offset, in array elements, into `dynamicOffsetsData`, where the dynamic offset data begins.
- `dynamicOffsetsLength`
- : A number specifying the number of dynamic offset values to be read from in `dynamicOffsetsData`.
### Return value
None ({{jsxref("Undefined")}}).
### Exceptions
For `setBindGroup()` calls that use a {{jsxref("Uint32Array")}} value for `dynamicOffsets`, the call will throw with a `RangeError` {{domxref("DOMException")}} if:
- `dynamicOffsetsStart` is less than 0.
- `dynamicOffsetsStart` + `dynamicOffsetsLength` is greater than `dynamicOffsets.length`.
### Validation
The following criteria must be met when calling **`setBindGroup()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPURenderPassEncoder")}} becomes invalid:
- `index` is less than or equal to the {{domxref("GPUDevice")}}'s `maxBindGroups` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}.
- `dynamicOffsets.length` is the same as the number of entries in `bindGroup` with `hasDynamicOffset: true` set.
- For `bindGroup` entries where the bound `buffer`'s `type` is `"uniform"` (see {{domxref("GPUDevice.createBindGroupLayout()")}}), each number in `dynamicOffsets` is a multiple of the {{domxref("GPUDevice")}}'s `minUniformBufferOffsetAlignment` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}.
- For `bindGroup` entries where the bound `buffer`'s `type` is `"storage"` or `"read-only-storage"` (see {{domxref("GPUDevice.createBindGroupLayout()")}}), each number in `dynamicOffsets` is a multiple of the {{domxref("GPUDevice")}}'s `minStorageBufferOffsetAlignment` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}.
- For each `bindGroup` entry, the bound `buffer`'s `offset`, plus the corresponding layout entry's `minBindingSize`, plus the corresponding dynamic offset specified in `dynamicOffsets`, is less than or equal to the bound `buffer`'s `size`.
## Examples
In the WebGPU Samples [Textured Cube example](https://webgpu.github.io/webgpu-samples/samples/texturedCube), `setBindGroup()` is used to bind the `uniformBindGroup` to index position 0. Check out the example for the full context.
```js
// ...
const commandEncoder = device.createCommandEncoder();
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
passEncoder.setPipeline(pipeline);
passEncoder.setBindGroup(0, uniformBindGroup);
passEncoder.setVertexBuffer(0, verticesBuffer);
passEncoder.draw(cubeVertexCount, 1, 0, 0);
passEncoder.end();
device.queue.submit([commandEncoder.finish()]);
// ...
```
> **Note:** Study the other [WebGPU Samples](https://webgpu.github.io/webgpu-samples) for more examples of `setBindGroup()` usage.
## 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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/draw/index.md | ---
title: "GPURenderPassEncoder: draw() method"
short-title: draw()
slug: Web/API/GPURenderPassEncoder/draw
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.draw
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`draw()`** method of the
{{domxref("GPURenderPassEncoder")}} interface draws primitives based on the vertex buffers provided by {{domxref("GPURenderPassEncoder.setVertexBuffer", "setVertexBuffer()")}}.
## Syntax
```js-nolint
draw(vertexCount)
draw(vertexCount, instanceCount)
draw(vertexCount, instanceCount, firstVertex)
draw(vertexCount, instanceCount, firstVertex, firstInstance)
```
### Parameters
- `vertexCount`
- : A number defining the number of vertices to draw.
- `instanceCount` {{optional_inline}}
- : A number defining the number of instances to draw. If omitted, `instanceCount` defaults to 1.
- `firstVertex` {{optional_inline}}
- : A number defining the offset into the vertex buffers, in vertices, to begin drawing from. If omitted, `firstVertex` defaults to 0.
- `firstInstance` {{optional_inline}}
- : A number defining the first instance to draw. If omitted, `firstInstance` defaults to 0.
### Return value
None ({{jsxref("Undefined")}}).
## Examples
In our [basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/), several commands are recorded via a {{domxref("GPUCommandEncoder")}}. Most of these commands originate from the `GPURenderPassEncoder` created via {{domxref("GPUCommandEncoder.beginRenderPass()")}}. `draw()` is used to specify that three vertices should be drawn to create our triangle.
```js
// ...
const renderPipeline = device.createRenderPipeline(pipelineDescriptor);
// Create GPUCommandEncoder to issue commands to the GPU
// Note: render pass descriptor, command encoder, etc. are destroyed after use, fresh one needed for each frame.
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 the triangle
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);
// End the render pass
passEncoder.end();
// 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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/setscissorrect/index.md | ---
title: "GPURenderPassEncoder: setScissorRect() method"
short-title: setScissorRect()
slug: Web/API/GPURenderPassEncoder/setScissorRect
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.setScissorRect
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`setScissorRect()`** method of the
{{domxref("GPURenderPassEncoder")}} interface sets the scissor rectangle used during the rasterization stage. After transformation into viewport coordinates any fragments that fall outside the scissor rectangle will be discarded.
## Syntax
```js-nolint
setScissorRect(x, y, width, height)
```
### Parameters
- `x`
- : A number representing the minimum X value of the scissor rectangle, in pixels.
- `y`
- : A number representing the minimum Y value of the scissor rectangle, in pixels.
- `width`
- : A number representing the width of the scissor rectangle, in pixels.
- `height`
- : A number representing the height of the scissor rectangle, in pixels.
> **Note:** If a `setScissorRect()` call is not made, the default values are `(0, 0, attachment width, attachment height)` for each render pass.
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`setViewport()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPURenderPassEncoder")}} becomes invalid:
- `x` + `width` is less than or equal to the width of the render pass's render attachments (see note below).
- `y` + `height` is less than or equal to the height of the render pass's render attachments (see note below).
> **Note:** See the color and depth/stencil attachments specified in the descriptor of {{domxref("GPUCommandEncoder.beginRenderPass()")}}; the width and height are based on that of the {{domxref("GPUTexture")}} that their `view`s originate from.
## Examples
### Basic snippet
In a typical canvas render, the following could be used to discard any rendering outside of the top-left quarter of the canvas:
```js
passEncoder.setScissorRect(0, 0, canvas.width / 2, canvas.height / 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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/label/index.md | ---
title: "GPURenderPassEncoder: label property"
short-title: label
slug: Web/API/GPURenderPassEncoder/label
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GPURenderPassEncoder.label
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`label`** read-only property of the
{{domxref("GPURenderPassEncoder")}} 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("GPUCommandEncoder.beginRenderPass()")}} call, or you can get and set it directly on the `GPURenderPassEncoder` 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 `GPURenderPassEncoder.label`:
```js
const commandEncoder = device.createCommandEncoder();
const renderPassDescriptor = {
colorAttachments: [
{
clearValue: clearColor,
loadOp: "clear",
storeOp: "store",
view: context.getCurrentTexture().createView(),
},
],
};
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
passEncoder.label = "myrenderpassencoder";
console.log(passEncoder.label); // "myrenderpassencoder"
```
Setting a label via the originating {{domxref("GPUCommandEncoder.beginRenderPass()")}} call, and then getting it via `GPURenderPassEncoder.label`:
```js
const commandEncoder = device.createCommandEncoder();
const renderPassDescriptor = {
colorAttachments: [
{
clearValue: clearColor,
loadOp: "clear",
storeOp: "store",
view: context.getCurrentTexture().createView(),
},
],
label: "myrenderpassencoder",
};
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
console.log(passEncoder.label); // "myrenderpassencoder"
```
## 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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/drawindexedindirect/index.md | ---
title: "GPURenderPassEncoder: drawIndexedIndirect() method"
short-title: drawIndexedIndirect()
slug: Web/API/GPURenderPassEncoder/drawIndexedIndirect
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.drawIndexedIndirect
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`drawIndexedIndirect()`** method of the
{{domxref("GPURenderPassEncoder")}} interface draws indexed primitives using parameters read from a {{domxref("GPUBuffer")}}.
## Syntax
```js-nolint
drawIndexedIndirect(indirectBuffer, indirectOffset)
```
### Parameters
- `indirectBuffer`
- : A {{domxref("GPUBuffer")}} containing the `indexCount`, `instanceCount`, `firstIndex`, `baseVertex`, and `firstInstance` values needed to carry out the drawing operation. The buffer must contain a tightly packed block of five 32-bit unsigned integer values representing the values (20 bytes total), given in the same order as the arguments for {{domxref("GPURenderPassEncoder.drawIndexed()")}}. So for example:
```js
const uint32 = new Uint32Array(5);
uint32[0] = 3; // The indexCount value
uint32[1] = 1; // The instanceCount value
uint32[2] = 0; // The firstIndex value
uint32[3] = 0; // The baseVertex value
uint32[4] = 0; // The firstInstance value
// Write values into a GPUBuffer
device.queue.writeBuffer(buffer, 0, uint32, 0, uint32.length);
```
- `indirectOffset`
- : The offset, in bytes, into `indirectBuffer` where the value data begins.
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`drawIndirect()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPURenderPassEncoder")}} becomes invalid:
- `indirectBuffer`'s {{domxref("GPUBuffer.usage")}} contains the `GPUBufferUsage.INDIRECT` flag.
- `indirectOffset` + the total size specified by the value parameters in the `indirectBuffer` is less than or equal to the `indirectBuffer`'s {{domxref("GPUBuffer.size")}}.
- `indirectOffset` is a multiple of 4.
## Examples
```js
// ...
// Create GPURenderPassEncoder
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
// Set pipeline and vertex buffer
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.setIndexBuffer(indexBuffer, "uint16");
// Create drawIndexedIndirect values
const uint32 = new Uint32Array(5);
uint32[0] = 3;
uint32[1] = 1;
uint32[2] = 0;
uint32[3] = 0;
uint32[4] = 0;
// Create a GPUBuffer and write the draw values into it
const drawValues = device.createBuffer({
size: 20,
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.INDIRECT,
});
device.queue.writeBuffer(drawValues, 0, uint32, 0, uint32.length);
// Draw the vertices
passEncoder.drawIndexedIndirect(drawValues, 0);
// End the render pass
passEncoder.end();
// End frame by passing array of GPUCommandBuffers 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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/setpipeline/index.md | ---
title: "GPURenderPassEncoder: setPipeline() method"
short-title: setPipeline()
slug: Web/API/GPURenderPassEncoder/setPipeline
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.setPipeline
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`setPipeline()`** method of the
{{domxref("GPURenderPassEncoder")}} interface sets the {{domxref("GPURenderPipeline")}} to use for subsequent render pass commands.
## Syntax
```js-nolint
setPipeline(pipeline)
```
### Parameters
- `pipeline`
- : The {{domxref("GPURenderPipeline")}} to use for subsequent render pass commands.
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`setPipeline()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPURenderPassEncoder")}} becomes invalid:
- If the {{domxref("GPURenderPipeline")}} writes to the depth component of the depth/stencil attachment, `depthReadOnly` (as specified in the descriptor of the originating {{domxref("GPUCommandEncoder.beginRenderPass()")}} call) is `true`.
- If the {{domxref("GPURenderPipeline")}} writes to the stencil component of the depth/stencil attachment, `stencilReadOnly` (as specified in the descriptor of the originating {{domxref("GPUCommandEncoder.beginRenderPass()")}} call) is `true`.
## Examples
In our [basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/), several commands are recorded via a {{domxref("GPUCommandEncoder")}}. Most of these commands originate from the `GPURenderPassEncoder` created via {{domxref("GPUCommandEncoder.beginRenderPass()")}}. `setPipeline()` is called in an appropriate place to set the render pipeline.
```js
// ...
const renderPipeline = device.createRenderPipeline(pipelineDescriptor);
// Create GPUCommandEncoder to issue commands to the GPU
// Note: render pass descriptor, command encoder, etc. are destroyed after use, fresh one needed for each frame.
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 the triangle
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);
// End the render pass
passEncoder.end();
// 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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/endocclusionquery/index.md | ---
title: "GPURenderPassEncoder: endOcclusionQuery() method"
short-title: endOcclusionQuery()
slug: Web/API/GPURenderPassEncoder/endOcclusionQuery
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.endOcclusionQuery
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`endOcclusionQuery()`** method of the
{{domxref("GPURenderPassEncoder")}} interface ends an active occlusion query previously started with {{domxref("GPURenderPassEncoder.beginOcclusionQuery", "beginOcclusionQuery()")}}.
## Syntax
```js-nolint
endOcclusionQuery()
```
### Parameters
None.
### Return value
None ({{jsxref("Undefined")}}).
### Validation
The following criteria must be met when calling **`endOcclusionQuery()`**, otherwise a {{domxref("GPUValidationError")}} is generated and the {{domxref("GPURenderPassEncoder")}} becomes invalid:
- An occlusion query is active for this render pass (i.e. via a previous `beginOcclusionQuery()` call).
## Examples
```js
// ...
// Create a query set to hold the occlusion queries
const querySet = device.createQuerySet({
type: "occlusion",
count: 32,
});
// Render pass descriptor object, including the querySet
const renderPassDescriptor = {
colorAttachments: [
{
clearValue: clearColor,
loadOp: "clear",
storeOp: "store",
view: context.getCurrentTexture().createView(),
},
],
occlusionQuerySet: querySet,
};
// Begin the render pass
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
// Begin an occlusion query at index 0
passEncoder.beginOcclusionQuery(0);
// Run some rendering commands
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);
// End the occlusion query
passEncoder.endOcclusionQuery();
// ...
```
## 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/gpurenderpassencoder | data/mdn-content/files/en-us/web/api/gpurenderpassencoder/setstencilreference/index.md | ---
title: "GPURenderPassEncoder: setStencilReference() method"
short-title: setStencilReference()
slug: Web/API/GPURenderPassEncoder/setStencilReference
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPassEncoder.setStencilReference
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`setStencilReference()`** method of the
{{domxref("GPURenderPassEncoder")}} interface sets the stencil reference value using during stencil tests with the `"replace"` stencil operation (as set in the descriptor of the {{domxref("GPUDevice.createRenderPipeline()")}} method, in the properties defining the various stencil operations).
## Syntax
```js-nolint
setStencilReference(reference)
```
### Parameters
- `reference`
- : A number representing the new stencil reference value to set for the render pass.
> **Note:** If a `setStencilReference()` call is not made, the stencil reference value defaults to 0 for each render pass.
### Return value
None ({{jsxref("Undefined")}}).
## Examples
```js
// ...
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.setStencilReference(1);
passEncoder.draw(3);
passEncoder.end();
// ...
```
## 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/worker/index.md | ---
title: Worker
slug: Web/API/Worker
page-type: web-api-interface
browser-compat: api.Worker
---
{{APIRef("Web Workers API")}}
The **`Worker`** interface of the [Web Workers API](/en-US/docs/Web/API/Web_Workers_API) represents a background task that can be created via script, which can send messages back to its creator.
Creating a worker is done by calling the `Worker("path/to/worker/script")` constructor.
Workers may themselves spawn new workers, as long as those workers are hosted at the same [origin](/en-US/docs/Web/Security/Same-origin_policy) as the parent page.
Note that not all interfaces and functions are available to web workers. See [Functions and classes available to Web Workers](/en-US/docs/Web/API/Web_Workers_API/Functions_and_classes_available_to_workers) for details.
{{InheritanceDiagram}}
## Constructors
- {{domxref("Worker.Worker", "Worker()")}}
- : Creates a dedicated web worker that executes the script at the specified URL. This also works for [Blob URLs](/en-US/docs/Web/API/Blob).
## Instance properties
_Inherits properties from its parent, {{domxref("EventTarget")}}._
## Instance methods
_Inherits methods from its parent, {{domxref("EventTarget")}}._
- {{domxref("Worker.postMessage()")}}
- : Sends a message — consisting of any JavaScript object — to the worker's inner scope.
- {{domxref("Worker.terminate()")}}
- : Immediately terminates the worker. This does not let worker finish its operations; it is halted at once. [`ServiceWorker`](/en-US/docs/Web/API/ServiceWorker) instances do not support this method.
## Events
- [`error`](/en-US/docs/Web/API/Worker/error_event)
- : Fires when an error occurs in the worker.
- [`message`](/en-US/docs/Web/API/Worker/message_event)
- : Fires when the worker's parent receives a message from that worker.
- [`messageerror`](/en-US/docs/Web/API/Worker/messageerror_event)
- : Fires when a `Worker` object receives a message that can't be [deserialized](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
## Example
The following code snippet creates a {{domxref("Worker")}} object using the {{domxref("Worker.Worker", "Worker()")}} constructor, then uses the worker object:
```js
const myWorker = new Worker("/worker.js");
const first = document.querySelector("input#number1");
const second = document.querySelector("input#number2");
first.onchange = () => {
myWorker.postMessage([first.value, second.value]);
console.log("Message posted to worker");
};
```
For a full example, see our [Basic dedicated worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-web-worker) ([run dedicated worker](https://mdn.github.io/dom-examples/web-workers/simple-web-worker/)).
## Specifications
{{Specifications}}
## Browser compatibility
Support varies for different types of workers. See each worker type's page for specifics.
{{Compat}}
### Cross-origin worker error behavior
In early versions of the spec, loading a cross-origin worker script threw a `SecurityError`. Nowadays, an {{domxref("Worker/error_event", "error")}} event is thrown instead.
## See also
- [Using Web Workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
- [Functions and classes available to Web Workers](/en-US/docs/Web/API/Web_Workers_API/Functions_and_classes_available_to_workers)
- Other kind of workers: {{domxref("SharedWorker")}} and [Service Worker](/en-US/docs/Web/API/Service_Worker_API).
- [`OffscreenCanvas`](/en-US/docs/Web/API/OffscreenCanvas) interface
| 0 |
data/mdn-content/files/en-us/web/api/worker | data/mdn-content/files/en-us/web/api/worker/terminate/index.md | ---
title: "Worker: terminate() method"
short-title: terminate()
slug: Web/API/Worker/terminate
page-type: web-api-instance-method
browser-compat: api.Worker.terminate
---
{{APIRef("Web Workers API")}}
The **`terminate()`** method of the {{domxref("Worker")}} interface immediately terminates the {{domxref("Worker")}}. This does not offer the worker an opportunity to finish its operations; it is stopped at once.
## Syntax
```js-nolint
terminate()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Examples
The following code snippet shows creation of a {{domxref("Worker")}} object using the {{domxref("Worker.Worker", "Worker()")}} constructor, which is then immediately terminated.
```js
const myWorker = new Worker("worker.js");
myWorker.terminate();
```
> **Note:** DedicatedWorkers and SharedWorkers can also be stopped from the {{domxref("Worker")}} instance using the {{domxref("DedicatedWorkerGlobalScope.close()")}} or {{domxref("SharedWorkerGlobalScope.close()")}} methods.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Worker")}} interface
- {{domxref("DedicatedWorkerGlobalScope.close()")}}
- {{domxref("SharedWorkerGlobalScope.close()")}}
| 0 |
data/mdn-content/files/en-us/web/api/worker | data/mdn-content/files/en-us/web/api/worker/messageerror_event/index.md | ---
title: "Worker: messageerror event"
short-title: messageerror
slug: Web/API/Worker/messageerror_event
page-type: web-api-event
browser-compat: api.Worker.messageerror_event
---
{{APIRef}}
The `messageerror` event is fired on a {{domxref('Worker')}} object when it receives a message that can't be deserialized.
This event is not cancellable and does not bubble.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("messageerror", (event) => {});
onmessageerror = (event) => {};
```
## Event type
A {{domxref("MessageEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("MessageEvent")}}
## Event properties
_This interface also inherits properties from its parent, {{domxref("Event")}}._
- {{domxref("MessageEvent.data")}} {{ReadOnlyInline}}
- : The data sent by the message emitter.
- {{domxref("MessageEvent.origin")}} {{ReadOnlyInline}}
- : A string representing the origin of the message emitter.
- {{domxref("MessageEvent.lastEventId")}} {{ReadOnlyInline}}
- : A string representing a unique ID for the event.
- {{domxref("MessageEvent.source")}} {{ReadOnlyInline}}
- : A `MessageEventSource` (which can be a {{glossary("WindowProxy")}}, {{domxref("MessagePort")}}, or {{domxref("ServiceWorker")}} object) representing the message emitter.
- {{domxref("MessageEvent.ports")}} {{ReadOnlyInline}}
- : An array of {{domxref("MessagePort")}} objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker).
## Examples
Create a worker, and listen for `message` and `messageerror` events using [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener):
```js
// main.js
const worker = new Worker("static/scripts/worker.js");
worker.addEventListener("message", (event) => {
console.error(`Received message from worker: ${event}`);
});
worker.addEventListener("messageerror", (event) => {
console.error(`Error receiving message from worker: ${event}`);
});
```
The same, but using the `onmessageerror` event handler property:
```js
// main.js
const worker = new Worker("static/scripts/worker.js");
worker.onmessage = (event) => {
console.error(`Received message from worker: ${event}`);
};
worker.onmessageerror = (event) => {
console.error(`Error receiving message from worker: ${event}`);
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`Worker.postMessage()`](/en-US/docs/Web/API/Worker/postMessage)
- Related events: [`message`](/en-US/docs/Web/API/Worker/message_event)
| 0 |
data/mdn-content/files/en-us/web/api/worker | data/mdn-content/files/en-us/web/api/worker/worker/index.md | ---
title: "Worker: Worker() constructor"
short-title: Worker()
slug: Web/API/Worker/Worker
page-type: web-api-constructor
browser-compat: api.Worker.Worker
---
{{APIRef("Web Workers API")}}
The **`Worker()`** constructor creates a {{domxref("Worker")}} object that executes the script at the specified URL. This script must obey the [same-origin policy](/en-US/docs/Web/Security/Same-origin_policy).
> **Note:** that there is a disagreement among browser manufacturers about whether a data URL is of the same origin or not. Though Firefox 10 and later accept data URLs, that's not the case in all other browsers.
## Syntax
```js-nolint
new Worker(aURL)
new Worker(aURL, options)
```
### Parameters
- `aURL`
- : A string representing the URL of the script the worker will execute. It must obey the same-origin policy.
- `options` {{optional_inline}}
- : An object containing option properties that can be set when creating the object instance. Available properties are as follows:
- `type`
- : A string specifying the type of worker to create. The value can be `classic` or `module`. If not specified, the default used is `classic`.
- `credentials`
- : A string specifying the type of credentials to use for the worker. The value can be `omit`, `same-origin`, or _`include`. If not specified, or if type is `classic`, the default used is `omit` (no credentials required)._
- `name`
- : A string specifying an identifying name for the {{domxref("DedicatedWorkerGlobalScope")}} representing the scope of the worker, which is mainly useful for debugging purposes.
### Exceptions
- `SecurityError` {{domxref("DOMException")}}
- : Thrown if the document is not allowed to start workers, e.g. if the URL has an invalid syntax or if the same-origin policy is violated.
- `NetworkError` {{domxref("DOMException")}}
- : Thrown if the MIME type of the worker script is incorrect. It _should_ always be `text/javascript`
(for historical reasons [other JavaScript MIME types](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#legacy_javascript_mime_types) may be accepted).
- `SyntaxError` {{domxref("DOMException")}}
- : Thrown if _aURL_ cannot be parsed.
## Examples
The following code snippet shows creation of a {{domxref("Worker")}} object using the `Worker()` constructor and subsequent usage of the object:
```js
const myWorker = new Worker("worker.js");
first.onchange = () => {
myWorker.postMessage([first.value, second.value]);
console.log("Message posted to worker");
};
```
For a full example, see our [Basic dedicated worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-web-worker) ([run dedicated worker](https://mdn.github.io/dom-examples/web-workers/simple-web-worker/)).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
The {{domxref("Worker")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/worker | data/mdn-content/files/en-us/web/api/worker/postmessage/index.md | ---
title: "Worker: postMessage() method"
short-title: postMessage()
slug: Web/API/Worker/postMessage
page-type: web-api-instance-method
browser-compat: api.Worker.postMessage
---
{{APIRef("Web Workers API")}}
The **`postMessage()`** method of the {{domxref("Worker")}} interface sends a message to the worker. The first parameter is the data to send to the worker. The data may be any JavaScript object that can be handled by the [structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
The {{domxref("Worker")}} `postMessage()` method delegates to the {{domxref("MessagePort")}} {{domxref("MessagePort.postMessage", "postMessage()")}} method, which adds a task on the event loop corresponding to the receiving {{domxref("MessagePort")}}.
The `Worker` can send back information to the thread that spawned it using the {{domxref("DedicatedWorkerGlobalScope.postMessage")}} method.
## Syntax
```js-nolint
postMessage(message)
postMessage(message, options)
postMessage(message, transfer)
```
### Parameters
- `message`
- : The object to deliver to the worker; this will be in the `data` field in the event delivered to the {{domxref("DedicatedWorkerGlobalScope.message_event")}} event. This may be any value or JavaScript object handled by the [structured clone](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) algorithm, which includes cyclical references.
If the `message` parameter is _not_ provided, a {{jsxref("SyntaxError")}} will be thrown by the parser. If the data to be passed to the worker is unimportant, `null` or `undefined` can be passed explicitly.
- `options` {{optional_inline}}
- : An optional object containing a `transfer` field with an [array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of [transferable objects](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) to transfer ownership of. If the ownership of an object is transferred, it becomes unusable in the context it was sent from, and becomes available only to the worker it was sent to.
- `transfer` {{optional_inline}}
- : An optional [array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of [transferable objects](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) to transfer ownership of. If the ownership of an object is transferred, it becomes unusable in the context it was sent from and becomes available only to the worker it was sent to.
Transferable objects are instances of classes like {{jsxref("ArrayBuffer")}}, {{domxref("MessagePort")}} or {{domxref("ImageBitmap")}} objects that can be transferred. `null` is not an acceptable value for `transfer`.
### Return value
None ({{jsxref("undefined")}}).
## Examples
The following code snippet shows the creation of a {{domxref("Worker")}} object using the {{domxref("Worker.Worker", "Worker()")}} constructor. When either of two form inputs (`first` and `second`) have their values changed, {{domxref("HTMLElement/change_event", "change")}} events invoke `postMessage()` to send the value of both inputs to the current worker.
```js
const myWorker = new Worker("worker.js");
first.onchange = () => {
myWorker.postMessage([first.value, second.value]);
console.log("Message posted to worker");
};
second.onchange = () => {
myWorker.postMessage([first.value, second.value]);
console.log("Message posted to worker");
};
```
For a full example, see our [simple worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-web-worker) ([run example](https://mdn.github.io/dom-examples/web-workers/simple-web-worker/)).
> **Note:** `postMessage()` can only send a single object at once. As seen above, if you want to pass multiple values you can send an array.
### Transfer Example
This minimum example has `main` create an `ArrayBuffer` and transfer it to `myWorker`, then has `myWorker` transfer it back to `main`, with the size logged at each step.
#### main.js code
```js
// create worker
const myWorker = new Worker("myWorker.js");
// listen for myWorker to transfer the buffer back to main
myWorker.addEventListener("message", function handleMessageFromWorker(msg) {
console.log("message from worker received in main:", msg);
const bufTransferredBackFromWorker = msg.data;
console.log(
"buf.byteLength in main AFTER transfer back from worker:",
bufTransferredBackFromWorker.byteLength,
);
});
// create the buffer
const myBuf = new ArrayBuffer(8);
console.log(
"buf.byteLength in main BEFORE transfer to worker:",
myBuf.byteLength,
);
// send myBuf to myWorker and transfer the underlying ArrayBuffer
myWorker.postMessage(myBuf, [myBuf]);
console.log(
"buf.byteLength in main AFTER transfer to worker:",
myBuf.byteLength,
);
```
#### myWorker.js code
```js
// listen for main to transfer the buffer to myWorker
self.onmessage = function handleMessageFromMain(msg) {
console.log("message from main received in worker:", msg);
const bufTransferredFromMain = msg.data;
console.log(
"buf.byteLength in worker BEFORE transfer back to main:",
bufTransferredFromMain.byteLength,
);
// send buf back to main and transfer the underlying ArrayBuffer
self.postMessage(bufTransferredFromMain, [bufTransferredFromMain]);
console.log(
"buf.byteLength in worker AFTER transfer back to main:",
bufTransferredFromMain.byteLength,
);
};
```
#### Output logged
```bash
buf.byteLength in main BEFORE transfer to worker: 8 main.js:19
buf.byteLength in main AFTER transfer to worker: 0 main.js:27
message from main received in worker: MessageEvent { ... } myWorker.js:3
buf.byteLength in worker BEFORE transfer back to main: 8 myWorker.js:7
buf.byteLength in worker AFTER transfer back to main: 0 myWorker.js:15
message from worker received in main: MessageEvent { ... } main.js:6
buf.byteLength in main AFTER transfer back from worker: 8 main.js:10
```
`byteLength` goes to 0 after the `ArrayBuffer` is transferred. For a more sophisticated full working example of `ArrayBuffer` transfer, see this Firefox demo add-on: [GitHub :: ChromeWorker - demo-transfer-arraybuffer](https://github.com/Noitidart/ChromeWorker/tree/aca57d9cadc4e68af16201bdecbfb6f9a6f9ca6b)
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("Worker")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/worker | data/mdn-content/files/en-us/web/api/worker/message_event/index.md | ---
title: "Worker: message event"
short-title: message
slug: Web/API/Worker/message_event
page-type: web-api-event
browser-compat: api.Worker.message_event
---
{{APIRef}}
The `message` event is fired on a {{domxref('Worker')}} object when the worker's parent receives a message from its worker (i.e. when the worker sends a message using [`DedicatedWorkerGlobalScope.postMessage()`](/en-US/docs/Web/API/DedicatedWorkerGlobalScope/postMessage)).
This event is not cancellable and does not bubble.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("message", (event) => {});
onmessage = (event) => {};
```
## Event type
A {{domxref("MessageEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("MessageEvent")}}
## Event properties
_This interface also inherits properties from its parent, {{domxref("Event")}}._
- {{domxref("MessageEvent.data")}} {{ReadOnlyInline}}
- : The data sent by the message emitter.
- {{domxref("MessageEvent.origin")}} {{ReadOnlyInline}}
- : A string representing the origin of the message emitter.
- {{domxref("MessageEvent.lastEventId")}} {{ReadOnlyInline}}
- : A string representing a unique ID for the event.
- {{domxref("MessageEvent.source")}} {{ReadOnlyInline}}
- : A `MessageEventSource` (which can be a {{glossary("WindowProxy")}}, {{domxref("MessagePort")}}, or {{domxref("ServiceWorker")}} object) representing the message emitter.
- {{domxref("MessageEvent.ports")}} {{ReadOnlyInline}}
- : An array of {{domxref("MessagePort")}} objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker).
## Examples
This code creates a new worker and listens to messages from it using [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener):
```js
const worker = new Worker("static/scripts/worker.js");
worker.addEventListener("message", (event) => {
console.log(`Received message from worker: ${event.data}`);
});
```
Alternatively, it could listen using the `onmessage` event handler property:
```js
const worker = new Worker("static/scripts/worker.js");
worker.onmessage = (event) => {
console.log(`Received message from worker: ${event.data}`);
};
```
The worker posts messages using [`self.postMessage()`](/en-US/docs/Web/API/DedicatedWorkerGlobalScope/postMessage):
```js
// static/scripts/worker.js
self.postMessage("I'm alive!");
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- Related events: [`messageerror`](/en-US/docs/Web/API/Worker/messageerror_event).
- [`DedicatedWorkerGlobalScope.postMessage()`](/en-US/docs/Web/API/DedicatedWorkerGlobalScope/postMessage).
| 0 |
data/mdn-content/files/en-us/web/api/worker | data/mdn-content/files/en-us/web/api/worker/error_event/index.md | ---
title: "Worker: error event"
short-title: error
slug: Web/API/Worker/error_event
page-type: web-api-event
browser-compat: api.Worker.error_event
---
{{APIRef("Web Workers API")}}
The **`error`** event of the {{domxref("Worker")}} interface fires when an error occurs in the worker.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("error", (event) => {});
onerror = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Example
The following code snippet creates a {{domxref("Worker")}} object using the {{domxref("Worker.Worker", "Worker()")}} constructor and sets up an `onerror` handler on the resulting object:
```js
const myWorker = new Worker("worker.js");
myWorker.onerror = (event) => {
console.log("There is an error with your worker!");
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/contentindexevent/index.md | ---
title: ContentIndexEvent
slug: Web/API/ContentIndexEvent
page-type: web-api-interface
status:
- experimental
browser-compat: api.ContentIndexEvent
---
{{APIRef("Content Index API")}}{{SeeCompatTable}}
The **`ContentIndexEvent`** interface of the [content index](/en-US/docs/Web/API/Content_Index_API) defines the object used to represent the {{domxref("ServiceWorkerGlobalScope.contentdelete_event", 'contentdelete')}} event.
This event is sent to the [global scope](/en-US/docs/Web/API/ServiceWorkerGlobalScope) of a {{domxref('ServiceWorker')}}. It contains the id of the indexed content to be removed.
The {{domxref("ServiceWorkerGlobalScope.contentdelete_event", 'contentdelete')}} event is only fired when the deletion happens due to interaction with the browser's built-in user interface. It is not fired when the {{domxref('ContentIndex.delete')}} method is called.
{{InheritanceDiagram}}
## Constructor
- {{domxref("ContentIndexEvent.ContentIndexEvent", "ContentIndexEvent()")}} {{Experimental_Inline}}
- : Creates and returns a new `ContentIndexEvent` object whose type and other options are configured as specified.
## Instance properties
_In addition to the properties listed below, this interface inherits the properties of its parent interface, {{domxref("ExtendableEvent")}}._
- {{domxref("ContentIndexEvent.id", "id")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A {{jsxref('String')}} which identifies the deleted content index via it's `id`.
## Instance methods
_While `ContentIndexEvent` offers no methods of its own, it inherits any specified by its parent interface, {{domxref("ExtendableEvent")}}._
## Examples
This example shows the [service worker](/en-US/docs/Web/API/ServiceWorker) script listening for the {{domxref("ServiceWorkerGlobalScope.contentdelete_event", 'contentdelete')}} event and logs the removed content index id.
```js
self.addEventListener("contentdelete", (event) => {
console.log(event.id);
// logs content index id, which can then be used to determine what content to delete from your cache
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [An introductory article on the Content Index API](https://developer.chrome.com/docs/capabilities/web-apis/content-indexing-api)
- [An app which uses the Content Index API to list and remove 'save for later' content](https://contentindex.dev/)
- [Service Worker API, along with information about Cache and CacheStorage](/en-US/docs/Web/API/Service_Worker_API)
| 0 |
data/mdn-content/files/en-us/web/api/contentindexevent | data/mdn-content/files/en-us/web/api/contentindexevent/contentindexevent/index.md | ---
title: "ContentIndexEvent: ContentIndexEvent() constructor"
short-title: ContentIndexEvent()
slug: Web/API/ContentIndexEvent/ContentIndexEvent
page-type: web-api-constructor
status:
- experimental
browser-compat: api.ContentIndexEvent.ContentIndexEvent
---
{{APIRef("Content Index API")}}{{SeeCompatTable}}
The **`ContentIndexEvent()`** constructor creates a new {{domxref("ContentIndexEvent")}} object
whose type and other options are configured as specified.
## Syntax
```js-nolint
new ContentIndexEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers always set it to `contentdelete`.
- `options`
- : An object that, _in addition of the properties defined in {{domxref("ExtendableEvent/ExtendableEvent", "ExtendableEvent()")}}_, has the following properties:
- `id`
- : The id of the indexed content you want the {{domxref("ContentIndex")}} object to remove.
### Return value
A new {{domxref("ContentIndexEvent")}} object configured using the given options.
## Examples
This examples constructs a new {{domxref('ContentIndexEvent')}} with the relevant id.
```js
const removeData = {
id: "unique-content-id",
};
const ciEvent = new ContentIndexEvent("contentdelete", removeData);
ciEvent.id; // should return 'unique-content-id'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [An introductory article on the Content Index API](https://developer.chrome.com/docs/capabilities/web-apis/content-indexing-api)
- [An app which uses the Content Index API to list and remove 'save for later' content](https://contentindex.dev/)
- [Service Worker API, along with information about Cache and CacheStorage](/en-US/docs/Web/API/Service_Worker_API)
| 0 |
data/mdn-content/files/en-us/web/api/contentindexevent | data/mdn-content/files/en-us/web/api/contentindexevent/id/index.md | ---
title: "ContentIndexEvent: id property"
short-title: id
slug: Web/API/ContentIndexEvent/id
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ContentIndexEvent.id
---
{{APIRef("Content Index API")}}{{SeeCompatTable}}
The read-only **`id`** property of the
{{domxref("ContentIndexEvent")}} interface is a {{jsxref('String')}} which identifies
the deleted content index via its `id`.
## Value
A {{jsxref("String")}} representation of the deleted content index id.
## Examples
This example listens for the {{domxref('ContentIndexEvent', 'contentdelete')}} event
and logs the removed content index id.
The {{domxref('ContentIndexEvent')}} is only available to the
[global scope](/en-US/docs/Web/API/ServiceWorkerGlobalScope) of a
{{domxref('ServiceWorker')}}.
```js
self.addEventListener("contentdelete", (event) => {
console.log(event.id);
// logs content index id, which can then be used to determine what content to delete from your cache
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [An introductory article on the Content Index API](https://developer.chrome.com/docs/capabilities/web-apis/content-indexing-api)
- [An app which uses the Content Index API to list and remove 'save for later' content](https://contentindex.dev/)
- [Service Worker API, along with information about Cache and CacheStorage](/en-US/docs/Web/API/Service_Worker_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/paintworkletglobalscope/index.md | ---
title: PaintWorkletGlobalScope
slug: Web/API/PaintWorkletGlobalScope
page-type: web-api-interface
status:
- experimental
browser-compat: api.PaintWorkletGlobalScope
---
{{APIRef("CSS Painting API")}}{{SeeCompatTable}}
The **`PaintWorkletGlobalScope`** interface of the [CSS Painting API](/en-US/docs/Web/API/CSS_Painting_API) represents the global object available inside a paint {{domxref("Worklet")}}.
## Privacy concerns
To avoid leaking visited links, this feature is currently disabled in Chrome-based browsers for {{HTMLElement("a")}} elements with an [`href`](/en-US/docs/Web/HTML/Element/a#href) attribute, and for children of such elements. For details, see the following:
- The CSS Painting API [Privacy Considerations section](https://drafts.css-houdini.org/css-paint-api/#privacy-considerations)
- The CSS Painting API spec issue ["CSS Paint API leaks browsing history"](https://github.com/w3c/css-houdini-drafts/issues/791)
## Instance properties
_This interface inherits methods from {{domxref('WorkletGlobalScope')}}._
- {{domxref('PaintWorkletGlobalScope.devicePixelRatio')}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the current device's ratio of physical pixels to logical pixels.
## Instance methods
_This interface inherits methods from {{domxref('WorkletGlobalScope')}}._
- {{domxref('PaintWorkletGlobalScope.registerPaint()')}} {{Experimental_Inline}}
- : Registers a class to programmatically generate an image where a CSS property expects a file.
## Examples
The following three examples go together to show creating, loading, and using a paint `Worklet`.
### Create a paint worklet
The following shows an example worklet module. This should be in a separate js file. Note that `registerPaint()` is called without a reference to a paint `Worklet`.
```js
class CheckerboardPainter {
paint(ctx, geom, properties) {
// The global object here is a PaintWorkletGlobalScope
// Methods and properties can be accessed directly
// as global features or prefixed using self
const dpr = self.devicePixelRatio;
// Use `ctx` as if it was a normal canvas
const colors = ["red", "green", "blue"];
const size = 32;
for (let y = 0; y < geom.height / size; y++) {
for (let x = 0; x < geom.width / size; x++) {
const color = colors[(x + y) % colors.length];
ctx.beginPath();
ctx.fillStyle = color;
ctx.rect(x * size, y * size, size, size);
ctx.fill();
}
}
}
}
// Register our class under a specific name
registerPaint("checkerboard", CheckerboardPainter);
```
### Load a paint worklet
The following example demonstrates loading the above worklet from its js file and does so by feature detection.
```js
if ("paintWorklet" in CSS) {
CSS.paintWorklet.addModule("checkerboard.js");
}
```
### Use a paint worklet
This example shows how to use a paint `Worklet` in a stylesheet, including the simplest way to provide a fallback if `CSS.paintWorklet` isn't supported.
```html
<style>
textarea {
background-image: url(checkerboard);
background-image: paint(checkerboard);
}
</style>
<textarea></textarea>
```
You can also use the {{cssxref('@supports')}} at-rule.
```css
@supports (background: paint(id)) {
background-image: paint(checkerboard);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [CSS Painting API](/en-US/docs/Web/API/CSS_Painting_API)
- [Houdini APIs](/en-US/docs/Web/API/Houdini_APIs)
| 0 |
data/mdn-content/files/en-us/web/api/paintworkletglobalscope | data/mdn-content/files/en-us/web/api/paintworkletglobalscope/devicepixelratio/index.md | ---
title: "PaintWorkletGlobalScope: devicePixelRatio property"
short-title: devicePixelRatio
slug: Web/API/PaintWorkletGlobalScope/devicePixelRatio
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.PaintWorkletGlobalScope.devicePixelRatio
---
{{APIRef("CSS Painting API")}}{{SeeCompatTable}}
The **`devicePixelRatio`** read-only property of the {{domxref("PaintWorkletGlobalScope")}} interface returns the current device's ratio of physical pixels to logical pixels.
## Value
A double-precision integer.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [CSS.paintWorklet](/en-US/docs/Web/API/CSS/paintWorklet_static)
- [Worklet](/en-US/docs/Web/API/Worklet)
- [CSS Painting API](/en-US/docs/Web/API/CSS_Painting_API)
- [Houdini APIs](/en-US/docs/Web/API/Houdini_APIs)
- [window.devicePixelRatio](/en-US/docs/Web/API/Window/devicePixelRatio)
| 0 |
data/mdn-content/files/en-us/web/api/paintworkletglobalscope | data/mdn-content/files/en-us/web/api/paintworkletglobalscope/registerpaint/index.md | ---
title: "PaintWorkletGlobalScope: registerPaint() method"
short-title: registerPaint()
slug: Web/API/PaintWorkletGlobalScope/registerPaint
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.PaintWorkletGlobalScope.registerPaint
---
{{APIRef("CSS Painting API")}}{{SeeCompatTable}}
The **`registerPaint()`** method of the
{{domxref("PaintWorkletGlobalScope")}} interface registers a class to programmatically generate an
image where a CSS property expects a file.
## Syntax
```js-nolint
registerPaint(name, classRef)
```
### Parameters
- `name`
- : The name of the worklet class to register.
- `classRef`
- : A reference to the class that implements the worklet.
## Return value
None ({{jsxref("undefined")}}).
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown when one of the arguments is invalid or missing.
- `InvalidModificationError` {{domxref("DOMException")}}
- : Thrown when the a worklet already exists with the specified name.
## Examples
The following shows registering an example worklet module. This should be in a separate
js file. Note that `registerPaint()` is called without a reference to
`PaintWorkletGlobalScope`. The file itself is loaded
through `CSS.paintWorklet.addModule()` (documented here on the parent class
of PaintWorklet, at {{domxref('Worklet.addModule()')}}.
```js
/* checkboardWorklet.js */
class CheckerboardPainter {
paint(ctx, geom, properties) {
// Use `ctx` as if it was a normal canvas
const colors = ["red", "green", "blue"];
const size = 32;
for (let y = 0; y < geom.height / size; y++) {
for (let x = 0; x < geom.width / size; x++) {
const color = colors[(x + y) % colors.length];
ctx.beginPath();
ctx.fillStyle = color;
ctx.rect(x * size, y * size, size, size);
ctx.fill();
}
}
}
}
// Register our class under a specific name
registerPaint("checkerboard", CheckerboardPainter);
```
The first step in using a paintworklet is defining the paint worklet using the
`registerPaint()` function, as done above. To use it, you register it with
the `CSS.paintWorklet.addModule()` method:
```html
<script>
CSS.paintWorklet.addModule("checkboardWorklet.js");
</script>
```
You can then use the `{{cssxref('image/paint', 'paint()')}}` CSS function in your
CSS anywhere an `{{cssxref('<image>')}}` value is valid.
```css
li {
background-image: paint(checkerboard);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [CSS Painting API](/en-US/docs/Web/API/CSS_Painting_API)
- [Houdini APIs](/en-US/docs/Web/API/Houdini_APIs)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/aeskeygenparams/index.md | ---
title: AesKeyGenParams
slug: Web/API/AesKeyGenParams
page-type: web-api-interface
spec-urls: https://w3c.github.io/webcrypto/#dfn-AesKeyGenParams
---
{{ APIRef("Web Crypto API") }}
The **`AesKeyGenParams`** dictionary of the [Web Crypto API](/en-US/docs/Web/API/Web_Crypto_API) represents the object that should be passed as the `algorithm` parameter into {{domxref("SubtleCrypto.generateKey()")}}, when generating an AES key: that is, when the algorithm is identified as any of [AES-CBC](/en-US/docs/Web/API/SubtleCrypto/encrypt#aes-cbc), [AES-CTR](/en-US/docs/Web/API/SubtleCrypto/encrypt#aes-ctr), [AES-GCM](/en-US/docs/Web/API/SubtleCrypto/encrypt#aes-gcm), or [AES-KW](/en-US/docs/Web/API/SubtleCrypto/wrapKey#aes-kw).
## Instance properties
- `name`
- : A string. This should be set to `AES-CBC`, `AES-CTR`, `AES-GCM`, or `AES-KW`, depending on the algorithm you want to use.
- `length`
- : A `Number` — the length in bits of the key to generate. This must be one of: 128, 192, or 256.
## Examples
See the examples for {{domxref("SubtleCrypto.generateKey()")}}.
## Specifications
{{Specifications}}
## Browser compatibility
Browsers that support any of the AES-based algorithms for the {{domxref("SubtleCrypto.generateKey()")}} method will support this type.
## See also
- {{domxref("SubtleCrypto.generateKey()")}}.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/usbdevice/index.md | ---
title: USBDevice
slug: Web/API/USBDevice
page-type: web-api-interface
status:
- experimental
browser-compat: api.USBDevice
---
{{SeeCompatTable}}{{APIRef("WebUSB API")}}{{SecureContext_Header}}
The **`USBDevice`** interface of the [WebUSB API](/en-US/docs/Web/API/WebUSB_API) provides access to metadata about a paired USB device and methods for controlling it.
## Instance properties
- {{domxref("USBDevice.configuration")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A {{domxref("USBConfiguration")}} object for the currently selected interface for a paired USB device.
- {{domxref("USBDevice.configurations")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : An {{jsxref("array")}} of device-specific interfaces for controlling a paired USB device.
- {{domxref("USBDevice.deviceClass")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : One of three properties that identify USB devices for the purpose of loading a USB driver that will work with that device. The other two properties are `USBDevice.deviceSubclass` and `USBDevice.deviceProtocol`.
- {{domxref("USBDevice.deviceProtocol")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : One of three properties that identify USB devices for the purpose of loading a USB driver that will work with that device. The other two properties are `USBDevice.deviceClass` and `USBDevice.deviceSubclass`.
- {{domxref("USBDevice.deviceSubclass")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : One of three properties that identify USB devices for the purpose of loading a USB driver that will work with that device. The other two properties are `USBDevice.deviceClass` and `USBDevice.deviceProtocol`.
- {{domxref("USBDevice.deviceVersionMajor")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : The major version number of the device in a semantic versioning scheme.
- {{domxref("USBDevice.deviceVersionMinor")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : The minor version number of the device in a semantic versioning scheme.
- {{domxref("USBDevice.deviceVersionSubminor")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : The patch version number of the device in a semantic versioning scheme.
- {{domxref("USBDevice.manufacturerName")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : The name of the organization that manufactured the USB device.
- {{domxref("USBDevice.opened")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Indicates whether a session has been started with a paired USB device.
- {{domxref("USBDevice.productId")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : The manufacturer-defined code that identifies a USB device.
- {{domxref("USBDevice.productName")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : The manufacturer-defined name that identifies a USB device.
- {{domxref("USBDevice.serialNumber")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : The manufacturer-defined serial number for the specific USB device.
- {{domxref("USBDevice.usbVersionMajor")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : One of three properties that declare the USB protocol version supported by the device. The other two properties are `USBDevice.usbVersionMinor` and `USBDevice.usbVersionSubminor`.
- {{domxref("USBDevice.usbVersionMinor")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : One of three properties that declare the USB protocol version supported by the device. The other two properties are `USBDevice.usbVersionMajor` and `USBDevice.usbVersionSubminor`.
- {{domxref("USBDevice.usbVersionSubminor")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : One of three properties that declare the USB protocol version supported by the device. The other two properties are `USBDevice.usbVersionMajor` and `USBDevice.usbVersionMinor`.
- {{domxref("USBDevice.vendorId")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : The official usb.org-assigned vendor ID.
## Instance methods
- {{domxref("USBDevice.claimInterface()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves when the requested interface is claimed for exclusive access.
- {{domxref("USBDevice.clearHalt()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves when a halt condition is cleared.
- {{domxref("USBDevice.controlTransferIn()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves with a {{domxref("USBInTransferResult")}} when a command or status operation has been transmitted to the USB device.
- {{domxref("USBDevice.controlTransferOut()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves with a {{domxref("USBOutTransferResult")}} when a command or status operation has been transmitted from the USB device.
- {{domxref("USBDevice.close()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves when all open interfaces are released and the device session has ended.
- {{domxref("USBDevice.forget()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves after all open interfaces are released, the device session has ended, and the permission is reset.
- {{domxref("USBDevice.isochronousTransferIn()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves with a {{domxref("USBIsochronousInTransferResult")}} when time sensitive information has been transmitted to the USB device.
- {{domxref("USBDevice.isochronousTransferOut()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves with a {{domxref("USBIsochronousOutTransferResult")}} when time sensitive information has been transmitted from the USB device.
- {{domxref("USBDevice.open()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves when a device session has started.
- {{domxref("USBDevice.releaseInterface()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves when a claimed interface is released from exclusive access.
- {{domxref("USBDevice.reset()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves when the device is reset and all app operations canceled and their promises rejected.
- {{domxref("USBDevice.selectAlternateInterface()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves when the specified alternative endpoint is selected.
- {{domxref("USBDevice.selectConfiguration()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves when the specified configuration is selected.
- {{domxref("USBDevice.transferIn()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves with a {{domxref("USBInTransferResult")}} when bulk or interrupt data is received from the USB device.
- {{domxref("USBDevice.transferOut()")}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves with a {{domxref("USBOutTransferResult")}} when bulk or interrupt data is sent to the USB device.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/selectalternateinterface/index.md | ---
title: "USBDevice: selectAlternateInterface() method"
short-title: selectAlternateInterface()
slug: Web/API/USBDevice/selectAlternateInterface
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.USBDevice.selectAlternateInterface
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`selectAlternateInterface()`** method of the
{{domxref("USBDevice")}} interface returns a {{jsxref("promise")}} that resolves when
the specified alternative endpoint is selected.
## Syntax
```js-nolint
selectAlternateInterface(interfaceNumber, alternateSetting)
```
### Parameters
- `interfaceNumber`
- : The index of one of the interfaces supported by the device. Interfaces are
device-specific.
- `alternateSetting`
- : The configuration of the selected interface.
### Return value
A {{jsxref("promise")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/usbversionsubminor/index.md | ---
title: "USBDevice: usbVersionSubminor property"
short-title: usbVersionSubminor
slug: Web/API/USBDevice/usbVersionSubminor
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.USBDevice.usbVersionSubminor
---
{{SeeCompatTable}}{{APIRef("WebUSB API")}}{{SecureContext_Header}}
The **`usbVersionSubminor`** read only property of the
{{domxref("USBDevice")}} interface is one of three properties that declare the USB
protocol version supported by the device. The other two properties
are USBDevice.usbVersionMajor and USBDevice.usbVersionMinor.
## Value
The first of three properties that declare the USB protocol version supported by the
device.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/deviceversionmajor/index.md | ---
title: "USBDevice: deviceVersionMajor property"
short-title: deviceVersionMajor
slug: Web/API/USBDevice/deviceVersionMajor
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.USBDevice.deviceVersionMajor
---
{{SeeCompatTable}}{{APIRef("WebUSB API")}}{{SecureContext_Header}}
The **`deviceVersionMajor`** read only property of the
{{domxref("USBDevice")}} interface he major version number of the device in a semantic
versioning scheme.
## Value
A number.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/isochronoustransferout/index.md | ---
title: "USBDevice: isochronousTransferOut() method"
short-title: isochronousTransferOut()
slug: Web/API/USBDevice/isochronousTransferOut
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.USBDevice.isochronousTransferOut
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`isochronousTransferOut()`** method of the
{{domxref("USBDevice")}} interface returns a {{jsxref("Promise")}} that resolves with a {{domxref("USBIsochronousOutTransferResult")}} when time sensitive information has been transmitted from the USB device.
## Syntax
```js-nolint
isochronousTransferOut(endpointNumber, data, packetLengths)
```
### Parameters
- `endpointNumber`
- : The number of a device-specific endpoint (buffer).
- `data`
- : A {{jsxref("TypedArray")}} containing the data to send to the device.
- `packetLengths`
- : An array of lengths for the packets being transferred.
### Return value
A {{jsxref("Promise")}} that resolves with a {{domxref("USBIsochronousOutTransferResult")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/deviceversionsubminor/index.md | ---
title: "USBDevice: deviceVersionSubminor property"
short-title: deviceVersionSubminor
slug: Web/API/USBDevice/deviceVersionSubminor
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.USBDevice.deviceVersionSubminor
---
{{SeeCompatTable}}{{APIRef("WebUSB API")}}{{SecureContext_Header}}
The **`deviceVersionSubminor`** read only property of the
{{domxref("USBDevice")}} interface the patch version number of the device in a semantic
versioning scheme.
## Value
A number.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/productname/index.md | ---
title: "USBDevice: productName property"
short-title: productName
slug: Web/API/USBDevice/productName
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.USBDevice.productName
---
{{SeeCompatTable}}{{APIRef("WebUSB API")}}{{SecureContext_Header}}
The **`productName`** read only property of the
{{domxref("USBDevice")}} interface the manufacturer-defined name that identifies a USB
device.
## Value
The manufacturer-defined name that identifies a USB device.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/manufacturername/index.md | ---
title: "USBDevice: manufacturerName property"
short-title: manufacturerName
slug: Web/API/USBDevice/manufacturerName
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.USBDevice.manufacturerName
---
{{SeeCompatTable}}{{APIRef("WebUSB API")}}{{SecureContext_Header}}
The **`manufacturerName`** read only property of the
{{domxref("USBDevice")}} interface the of the organization that manufactured the USB
device.
## Value
A string.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/controltransferin/index.md | ---
title: "USBDevice: controlTransferIn() method"
short-title: controlTransferIn()
slug: Web/API/USBDevice/controlTransferIn
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.USBDevice.controlTransferIn
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`controlTransferIn()`** method of the {{domxref("USBDevice")}} interface returns a {{jsxref("Promise")}} that resolves with a {{domxref("USBInTransferResult")}} when a command or status request has been transmitted to (received by) the USB device.
## Syntax
```js-nolint
controlTransferIn(setup, length)
```
### Parameters
- `setup`
- : An object that sets options for. The available options are:
- `requestType`
- : Must be one of three values specifying whether the transfer is `"standard"` (common to all USB devices) `"class"` (common to an industry-standard class of devices) or `"vendor"`.
- `recipient`
- : Specifies the target of the transfer on the device, one of `"device"`, `"interface"`, `"endpoint"`, or `"other"`.
- `request`
- : A vendor-specific command.
- `value`
- : Vendor-specific request parameters.
- `index`
- : The interface number of the recipient.
- `length`
- : The maximum number of bytes to read from the device. The actual data is in the {{domxref("USBInTransferResult")}} in the resolved Promise.
### Return value
{{jsxref("promise")}} that resolves with a {{domxref("USBInTransferResult")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/deviceversionminor/index.md | ---
title: "USBDevice: deviceVersionMinor property"
short-title: deviceVersionMinor
slug: Web/API/USBDevice/deviceVersionMinor
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.USBDevice.deviceVersionMinor
---
{{SeeCompatTable}}{{APIRef("WebUSB API")}}{{SecureContext_Header}}
The **`deviceVersionMinor`** read only property of the
{{domxref("USBDevice")}} interface the minor version number of the device in a semantic
versioning scheme.
## Value
A number.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/claiminterface/index.md | ---
title: "USBDevice: claimInterface() method"
short-title: claimInterface()
slug: Web/API/USBDevice/claimInterface
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.USBDevice.claimInterface
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`claimInterface()`** method of the
{{domxref("USBDevice")}} interface returns a {{jsxref("promise")}} that resolves when
the requested interface is claimed for exclusive access.
## Syntax
```js-nolint
claimInterface(interfaceNumber)
```
### Parameters
- `interfaceNumber`
- : The index of one of the interfaces supported by the device. Interfaces are
device specific.
### Return value
A {{jsxref("promise")}}.
## Examples
The following example shows `claimInterface()` in the context of connecting
to a USB device.
```js
async function connectDevice(usbDevice) {
await usbDevice.open();
if (usbDevice.configuration === null) await usbDevice.selectConfiguration(1);
await usbDevice.claimInterface(0);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/deviceclass/index.md | ---
title: "USBDevice: deviceClass property"
short-title: deviceClass
slug: Web/API/USBDevice/deviceClass
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.USBDevice.deviceClass
---
{{SeeCompatTable}}{{APIRef("WebUSB API")}}{{SecureContext_Header}}
The **`deviceClass`** read only property of the
{{domxref("USBDevice")}} interface one of three properties that identify USB devices for
the purpose of loading a USB driver that will work with that device. The other two
properties are USBDevice.deviceSubclass and USBDevice.deviceprotocol.
## Value
A number.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/forget/index.md | ---
title: "USBDevice: forget() method"
short-title: forget()
slug: Web/API/USBDevice/forget
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.USBDevice.forget
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`forget()`** method of the {{domxref("USBDevice")}} interface returns a {{jsxref("Promise")}} that resolves when all pending operations are aborted, all open interfaces are released, the device session has ended, and the permission is reset.
## Syntax
```js-nolint
forget()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} which resolves with `undefined` once the device access permission is revoked.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/configurations/index.md | ---
title: "USBDevice: configurations property"
short-title: configurations
slug: Web/API/USBDevice/configurations
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.USBDevice.configurations
---
{{SeeCompatTable}}{{APIRef("WebUSB API")}}{{SecureContext_Header}}
The **`configurations`** read only property of the
{{domxref("USBDevice")}} interface an {{jsxref("array")}} of device-specific interfaces
for controlling a paired USB device.
## Value
An {{jsxref("array")}} of {{domxref("USBConfiguration")}} objects.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/releaseinterface/index.md | ---
title: "USBDevice: releaseInterface() method"
short-title: releaseInterface()
slug: Web/API/USBDevice/releaseInterface
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.USBDevice.releaseInterface
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`releaseInterface()`** method of the
{{domxref("USBDevice")}} interface returns a {{jsxref("promise")}} that resolves when a
claimed interface is released from exclusive access.
## Syntax
```js-nolint
releaseInterface(interfaceNumber)
```
### Parameters
- `interfaceNumber`
- : The device-specific index of the currently-claimed interface.
### Return value
A {{jsxref("promise")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/productid/index.md | ---
title: "USBDevice: productId property"
short-title: productId
slug: Web/API/USBDevice/productID
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.USBDevice.productId
---
{{SeeCompatTable}}{{APIRef("WebUSB API")}}
The **`productId`** read only property of the
{{domxref("USBDevice")}} interface the manufacturer-defined code that identifies a USB
device.
## Value
The manufacturer-defined code that identifies a USB device.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/controltransferout/index.md | ---
title: "USBDevice: controlTransferOut() method"
short-title: controlTransferOut()
slug: Web/API/USBDevice/controlTransferOut
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.USBDevice.controlTransferOut
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`controlTransferOut()`** method of the {{domxref("USBDevice")}} interface returns a {{jsxref("Promise")}} that resolves with a {{domxref("USBOutTransferResult")}} when a command or status operation has been transmitted from the USB device.
## Syntax
```js-nolint
controlTransferOut(setup, data)
```
### Parameters
- `setup`
- : An object that sets options for. The available options are:
- `requestType`
- : Must be one of three values specifying whether the transfer is `"standard"` (common to all USB devices) `"class"` (common to an industry-standard class of devices) or `"vendor"`.
- `recipient`
- : Specifies the target of the transfer on the device, one of `"device"`, `"interface"`, `"endpoint"`, or `"other"`.
- `request`
- : A vendor-specific command.
- `value`
- : Vendor-specific request parameters.
- `index`
- : The interface number of the recipient.
- `data`
- : A {{jsxref("TypedArray")}} containing the data that will be transferred to the device.
Not all commands require data; some commands can send data just through the value parameter.
Check with your device to see what the specific request requires.
### Return value
A {{jsxref("promise")}} that resolves with a {{domxref("USBOutTransferResult")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/transferin/index.md | ---
title: "USBDevice: transferIn() method"
short-title: transferIn()
slug: Web/API/USBDevice/transferIn
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.USBDevice.transferIn
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`transferIn()`** method of the {{domxref("USBDevice")}}
interface returns a {{jsxref("promise")}} that resolves with a
{{domxref("USBInTransferResult")}} when bulk or interrupt data is received from the USB
device.
## Syntax
```js-nolint
transferIn(endpointNumber, length)
```
### Parameters
- `endpointNumber`
- : The number of a device-specific endpoint (buffer).
- `length`
- : The maximum number of bytes that will be read back from the device. The actual data
is in the {{domxref("USBInTransferResult")}} in the resolved Promise.
### Return value
A {{jsxref("promise")}} that resolves with a {{domxref("USBInTransferResult")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/deviceprotocol/index.md | ---
title: "USBDevice: deviceProtocol property"
short-title: deviceProtocol
slug: Web/API/USBDevice/deviceProtocol
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.USBDevice.deviceProtocol
---
{{SeeCompatTable}}{{APIRef("WebUSB API")}}{{SecureContext_Header}}
The **`deviceProtocol`** read only property of the
{{domxref("USBDevice")}} interface one of three properties that identify USB devices for
the purpose of loading a USB driver that will work with that device. The other two
properties are `USBDevice.deviceClass`
and `USBDevice.deviceSubclass`.
## Value
A number.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/clearhalt/index.md | ---
title: "USBDevice: clearHalt() method"
short-title: clearHalt()
slug: Web/API/USBDevice/clearHalt
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.USBDevice.clearHalt
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`clearHalt()`** method of the {{domxref("USBDevice")}}
interface returns a {{jsxref("promise")}} that resolves when a halt condition is
cleared. A halt condition is when a data transfer to or from the device has a status
of `'stall'`, which requires the web page (the _host_ system, in USB
terminology) to clear that condition. See the for details.
## Syntax
```js-nolint
clearHalt(direction, endpointNumber)
```
### Parameters
- `direction`
- : Indicates whether the devices input or output should be cleared. Valid values
are `'in'` or `'out'`.
- `endpointNumber`
- : Indicates the number of the endpoint to clear. The promise will reject if an invalid
endpoint is supplied.
### Return value
A {{jsxref("promise")}}.
## Examples
The following example shows how to test for and clear a `'stall'` condition
in the result of a data transfer.
> **Note:** What data can be passed to a USB device and how it is passed is particular and unique
> to each device.
```js
while (true) {
let result = await data.transferIn(1, 6);
if (result.data && result.data.byteLength === 6) {
console.log(`Channel 1: ${result.data.getUint16(0)}`);
console.log(`Channel 2: ${result.data.getUint16(2)}`);
console.log(`Channel 5: ${result.data.getUint16(4)}`);
}
if (result.status === "stall") {
console.warn("Endpoint stalled. Clearing.");
await device.clearHalt("in", 1);
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/configuration/index.md | ---
title: "USBDevice: configuration property"
short-title: configuration
slug: Web/API/USBDevice/configuration
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.USBDevice.configuration
---
{{SeeCompatTable}}{{APIRef("WebUSB API")}}{{SecureContext_Header}}
The **`configuration`** read only property of the
{{domxref("USBDevice")}} interface returns a {{domxref("USBConfiguration")}} object for
the currently selected interface for a paired USB device.
## Value
A {{domxref("USBConfiguration")}} object.
## Examples
The following example uses this property to test for the existence of a
USBConfiguration property to select a configuration before claiming an interface.
```js
async function connectDevice(usbDevice) {
await usbDevice.open();
if (usbDevice.configuration === null) await usbDevice.selectConfiguration(1);
await usbDevice.claimInterface(0);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/selectconfiguration/index.md | ---
title: "USBDevice: selectConfiguration() method"
short-title: selectConfiguration()
slug: Web/API/USBDevice/selectConfiguration
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.USBDevice.selectConfiguration
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`selectConfiguration()`** method of the
{{domxref("USBDevice")}} interface returns a {{jsxref("promise")}} that resolves when
the specified configuration is selected.
## Syntax
```js-nolint
selectConfiguration(configurationValue)
```
### Parameters
- `configurationValue`
- : The number of a device-specific configuration.
### Return value
A {{jsxref("promise")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/vendorid/index.md | ---
title: "USBDevice: vendorId property"
short-title: vendorId
slug: Web/API/USBDevice/vendorID
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.USBDevice.vendorId
---
{{SeeCompatTable}}{{APIRef("WebUSB API")}}
The **`vendorId`** read only property of the
{{domxref("USBDevice")}} interface is the official usb.org-assigned vendor ID.
## Value
The official usb.org-assigned vendor ID.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/reset/index.md | ---
title: "USBDevice: reset() method"
short-title: reset()
slug: Web/API/USBDevice/reset
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.USBDevice.reset
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`reset()`** method of the {{domxref("USBDevice")}}
interface returns a {{jsxref("promise")}} that resolves when the device is reset and all
app operations canceled and their promises rejected.
## Syntax
```js-nolint
reset()
```
### Parameters
None.
### Return value
A {{jsxref("promise")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/usbversionminor/index.md | ---
title: "USBDevice: usbVersionMinor property"
short-title: usbVersionMinor
slug: Web/API/USBDevice/usbVersionMinor
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.USBDevice.usbVersionMinor
---
{{SeeCompatTable}}{{APIRef("WebUSB API")}}{{SecureContext_Header}}
The **`usbVersionMinor`** read only property of the
{{domxref("USBDevice")}} interface is one of three properties that declare the USB
protocol version supported by the device. The other two properties
are USBDevice.usbVersionMajor and USBDevice.usbVersionSubminor.
## Value
The second of three properties that declare the USB protocol version supported by the
device.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/opened/index.md | ---
title: "USBDevice: opened property"
short-title: opened
slug: Web/API/USBDevice/opened
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.USBDevice.opened
---
{{SeeCompatTable}}{{APIRef("WebUSB API")}}{{SecureContext_Header}}
The **`opened`** read only property of the
{{domxref("USBDevice")}} interface indicates whether a session has been started with a
paired USB device. A device must be opened before it can be controlled by a web page.
## Value
A {{jsxref("boolean")}}.
## Examples
This example is for a hypothetical USB device with a multi-colored LED. It shows how to
test that a device is open before calling {{domxref("USBDevice.controlTransferOut")}} to
set a specified LED color.
> **Note:** What data can be passed to a USB device and how it is passed is particular and unique
> to each device.
```js
async function setDeviceColor(usbDevice, r, g, b) {
if (device.opened) {
// This hypothetical USB device requires that the data passed to
// it be in a Uint8Array.
const payload = new Uint8Array([r, g, b]);
await usbDevice.controlTransferOut(
{
requestType: "vendor",
recipient: "device",
request: 1,
value: 0,
index: 0,
},
payload,
);
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/serialnumber/index.md | ---
title: "USBDevice: serialNumber property"
short-title: serialNumber
slug: Web/API/USBDevice/serialNumber
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.USBDevice.serialNumber
---
{{SeeCompatTable}}{{APIRef("WebUSB API")}}{{SecureContext_Header}}
The **`serialNumber`** read only property of the
{{domxref("USBDevice")}} interface is the manufacturer-defined serial number for the
specific USB device.
## Value
The serial number for the specified USB device
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/usbversionmajor/index.md | ---
title: "USBDevice: usbVersionMajor property"
short-title: usbVersionMajor
slug: Web/API/USBDevice/usbVersionMajor
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.USBDevice.usbVersionMajor
---
{{SeeCompatTable}}{{APIRef("WebUSB API")}}{{SecureContext_Header}}
The **`usbVersionMajor`** read only property of the
{{domxref("USBDevice")}} interface is one of three properties that declare the USB
protocol version supported by the device. The other two properties
are USBDevice.usbVersionMinor and USBDevice.usbVersionSubminor.
## Value
The last of three properties that declare the USB protocol version supported by the
device.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/devicesubclass/index.md | ---
title: "USBDevice: deviceSubclass property"
short-title: deviceSubclass
slug: Web/API/USBDevice/deviceSubclass
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.USBDevice.deviceSubclass
---
{{SeeCompatTable}}{{APIRef("WebUSB API")}}{{SecureContext_Header}}
The **`deviceSubclass`** read only property of the
{{domxref("USBDevice")}} interface one of three properties that identify USB devices for
the purpose of loading a USB driver that will work with that device. The other two
properties are USBDevice.deviceClass and USBDevice.deviceProtocol.
## Value
A number.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/isochronoustransferin/index.md | ---
title: "USBDevice: isochronousTransferIn() method"
short-title: isochronousTransferIn()
slug: Web/API/USBDevice/isochronousTransferIn
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.USBDevice.isochronousTransferIn
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`isochronousTransferIn()`** method of the {{domxref("USBDevice")}} interface returns a {{jsxref("Promise")}} that resolves with a {{domxref("USBIsochronousInTransferResult")}} when time sensitive information has been transmitted to (received by) the USB device.
## Syntax
```js-nolint
isochronousTransferIn(endpointNumber, packetLengths)
```
### Parameters
- `endpointNumber`
- : The number of a device-specific endpoint (buffer).
- `packetLengths`
- : An array of lengths for the packets being received.
### Return value
A {{jsxref("Promise")}} that resolves with a {{domxref("USBIsochronousInTransferResult")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/transferout/index.md | ---
title: "USBDevice: transferOut() method"
short-title: transferOut()
slug: Web/API/USBDevice/transferOut
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.USBDevice.transferOut
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`transferOut()`** method of the {{domxref("USBDevice")}}
interface returns a {{jsxref("promise")}} that resolves with a
{{domxref("USBOutTransferResult")}} when bulk or interrupt data is sent to the USB
device.
## Syntax
```js-nolint
transferOut(endpointNumber, data)
```
### Parameters
- `endpointNumber`
- : The number of a device-specific endpoint (buffer).
- `data`
- : A {{jsxref("TypedArray")}} containing the data to send to the device.
### Return value
A {{jsxref("promise")}} that resolves with a {{domxref("USBOutTransferResult")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/close/index.md | ---
title: "USBDevice: close() method"
short-title: close()
slug: Web/API/USBDevice/close
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.USBDevice.close
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`close()`** method of the {{domxref("USBDevice")}}
interface returns a {{jsxref("promise")}} that resolves when all open interfaces are
released and the device session has ended.
## Syntax
```js-nolint
close()
```
### Parameters
None.
### Return value
A {{jsxref("promise")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/usbdevice | data/mdn-content/files/en-us/web/api/usbdevice/open/index.md | ---
title: "USBDevice: open() method"
short-title: open()
slug: Web/API/USBDevice/open
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.USBDevice.open
---
{{APIRef("WebUSB API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`open()`** method of the {{domxref("USBDevice")}}
interface returns a {{jsxref("promise")}} that resolves when a device session has
started.
## Syntax
```js-nolint
open()
```
### Parameters
None.
### Return value
A {{jsxref("promise")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/storagemanager/index.md | ---
title: StorageManager
slug: Web/API/StorageManager
page-type: web-api-interface
browser-compat: api.StorageManager
---
{{securecontext_header}}{{APIRef("Storage")}}
The **`StorageManager`** interface of the [Storage API](/en-US/docs/Web/API/Storage_API) provides an interface for managing persistence permissions and estimating available storage. You can get a reference to this interface using either {{domxref("navigator.storage")}} or {{domxref("WorkerNavigator.storage")}}.
{{AvailableInWorkers}}
## Instance methods
- {{domxref("StorageManager.estimate()")}}
- : Returns a {{jsxref('Promise')}} that resolves to an object containing usage and quota numbers for your origin.
- {{domxref("StorageManager.getDirectory()")}}
- : Used to obtain a reference to a {{domxref("FileSystemDirectoryHandle")}} object allowing access to a directory and its contents, stored in the [origin private file system](/en-US/docs/Web/API/File_System_API/Origin_private_file_system). Returns a {{jsxref('Promise')}} that fulfills with a {{domxref("FileSystemDirectoryHandle")}} object.
- {{domxref("StorageManager.persist()")}}
- : Returns a {{jsxref('Promise')}} that resolves to `true` if the user agent is able to persist your site's storage.
- {{domxref("StorageManager.persisted()")}}
- : Returns a {{jsxref('Promise')}} that resolves to `true` if persistence has already been granted for your site's storage.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/storagemanager | data/mdn-content/files/en-us/web/api/storagemanager/persisted/index.md | ---
title: "StorageManager: persisted() method"
short-title: persisted()
slug: Web/API/StorageManager/persisted
page-type: web-api-instance-method
browser-compat: api.StorageManager.persisted
---
{{securecontext_header}}{{APIRef("Storage")}}
The **`persisted()`** method of the {{domxref("StorageManager")}} interface returns a {{jsxref('Promise')}} that resolves to `true` if your site's storage bucket is persistent.
{{AvailableInWorkers}}
## Syntax
```js-nolint
persisted()
```
### Parameters
None.
### Returns
A {{jsxref('Promise')}} that resolves to a {{jsxref('Boolean')}}.
### Exceptions
- `TypeError`
- : Thrown if obtaining a local storage shelf failed. For example, if the current origin is an opaque origin or if the user has disabled storage.
## Example
```js
if (navigator.storage && navigator.storage.persist) {
navigator.storage.persisted().then((persistent) => {
if (persistent) {
console.log("Storage will not be cleared except by explicit user action");
} else {
console.log("Storage may be cleared by the UA under storage pressure.");
}
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/storagemanager | data/mdn-content/files/en-us/web/api/storagemanager/getdirectory/index.md | ---
title: "StorageManager: getDirectory() method"
short-title: getDirectory()
slug: Web/API/StorageManager/getDirectory
page-type: web-api-instance-method
browser-compat: api.StorageManager.getDirectory
---
{{securecontext_header}}{{APIRef("File System API")}}
The **`getDirectory()`** method of the {{domxref("StorageManager")}} interface is used to obtain a reference to a {{domxref("FileSystemDirectoryHandle")}} object allowing access to a directory and its contents, stored in the [origin private file system](/en-US/docs/Web/API/File_System_API/Origin_private_file_system) (OPFS).
{{AvailableInWorkers}}
## Syntax
```js-nolint
getDirectory()
```
### Parameters
None.
### Return value
A {{jsxref('Promise')}} that fulfills with a {{domxref("FileSystemDirectoryHandle")}} object.
### Exceptions
- `SecurityError` {{domxref("DOMException")}}
- : Thrown if the user agent is not able to map the requested directory to the local OPFS.
## Examples
The following asynchronous event handler function is contained inside a Web Worker. On receiving a message from the main thread it:
1. Gets a {{domxref("FileSystemDirectoryHandle")}} representing the root of the OPFS using `getDirectory()`, storing it in the `root` variable.
2. Gets a file handle using {{domxref("FileSystemDirectoryHandle.getFileHandle()")}}.
3. Creates a synchronous file access handle using {{domxref("FileSystemFileHandle.createSyncAccessHandle()")}}.
4. Gets the size of the file and creates an {{jsxref("ArrayBuffer")}} to contain it.
5. Reads and writes to the file.
6. Persists the changes to disk and closes the synchronous access handle.
```js
onmessage = async (e) => {
// Retrieve message sent to work from main script
const message = e.data;
// Get handle to draft file
const root = await navigator.storage.getDirectory();
const draftHandle = await root.getFileHandle("draft.txt", { create: true });
// Get sync access handle
const accessHandle = await draftHandle.createSyncAccessHandle();
// Get size of the file.
const fileSize = accessHandle.getSize();
// Read file content to a buffer.
const buffer = new DataView(new ArrayBuffer(fileSize));
const readBuffer = accessHandle.read(buffer, { at: 0 });
// Write the message to the end of the file.
const encoder = new TextEncoder();
const encodedMessage = encoder.encode(message);
const writeBuffer = accessHandle.write(encodedMessage, { at: readBuffer });
// Persist changes to disk.
accessHandle.flush();
// Always close FileSystemSyncAccessHandle if done.
accessHandle.close();
};
```
> **Note:** In earlier versions of the spec, {{domxref("FileSystemSyncAccessHandle.close()", "close()")}}, {{domxref("FileSystemSyncAccessHandle.flush()", "flush()")}}, {{domxref("FileSystemSyncAccessHandle.getSize()", "getSize()")}}, and {{domxref("FileSystemSyncAccessHandle.truncate()", "truncate()")}} were wrongly specified as asynchronous methods, and older versions of some browsers implement them in this way. However, all current browsers that support these methods implement them as synchronous methods.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("StorageManager")}}
- {{domxref("navigator.storage")}}
- {{domxref("FileSystemDirectoryHandle")}}
| 0 |
data/mdn-content/files/en-us/web/api/storagemanager | data/mdn-content/files/en-us/web/api/storagemanager/estimate/index.md | ---
title: "StorageManager: estimate() method"
short-title: estimate()
slug: Web/API/StorageManager/estimate
page-type: web-api-instance-method
browser-compat: api.StorageManager.estimate
---
{{securecontext_header}}{{APIRef("Storage")}}
The **`estimate()`** method of the {{domxref("StorageManager")}} interface asks the Storage Manager for how much storage the current [origin](/en-US/docs/Glossary/Same-origin_policy) takes up (`usage`), and how much space is available (`quota`).
This method operates asynchronously, so it returns a {{jsxref("Promise")}} which resolves once the information is available. The promise's fulfillment handler is called with an object containing the usage and quota data.
{{AvailableInWorkers}}
## Syntax
```js-nolint
estimate()
```
### Parameters
None.
### Return value
A {{jsxref('Promise')}} that resolves to an object with the following properties:
- `quota`
- : A numeric value in bytes which provides a conservative approximation of the total storage the user's device or computer has available for the site origin or Web app. It's possible that there's more than this amount of space available though you can't rely on that being the case.
- `usage`
- : A numeric value in bytes approximating the amount of storage space currently being used by the site or Web app, out of the available space as indicated by `quota`. Unit is byte.
- `usageDetails` {{Non-standard_Inline}}
- : An object containing a breakdown of `usage` by storage system. All included properties will have a `usage` greater than 0 and any storage system with 0 `usage` will be excluded from the object.
> **Note:** The returned values are not exact: between compression, deduplication, and obfuscation for security reasons, they will be imprecise.
You may find that the `quota` varies from origin to origin. This variance is based on factors such as:
- How often the user visits
- Public site popularity data
- User engagement signals like bookmarking, adding to homescreen, or accepting push notifications
### Exceptions
- `TypeError`
- : Thrown if obtaining a local storage shelf failed. For example, if the current origin is an opaque origin or if the user has disabled storage.
## Examples
In this example, we obtain the usage estimates and present the percentage of storage capacity currently used to the user.
### HTML
```html
<label>
You're currently using about <output id="percent"> </output>% of your
estimated storage quota (<output id="quota"></output>).
</label>
```
### JavaScript
```js
navigator.storage.estimate().then((estimate) => {
document.getElementById("percent").value = (
(estimate.usage / estimate.quota) *
100
).toFixed(2);
document.getElementById("quota").value =
(estimate.quota / 1024 / 1024).toFixed(2) + "MB";
});
```
### Result
{{ EmbedLiveSample('Examples', 600, 40) }}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Storage API](/en-US/docs/Web/API/Storage_API)
- {{domxref("Storage")}}, the object returned by {{domxref("Window.localStorage")}}
- {{domxref("StorageManager")}}
- {{domxref("navigator.storage")}}
| 0 |
data/mdn-content/files/en-us/web/api/storagemanager | data/mdn-content/files/en-us/web/api/storagemanager/persist/index.md | ---
title: "StorageManager: persist() method"
short-title: persist()
slug: Web/API/StorageManager/persist
page-type: web-api-instance-method
browser-compat: api.StorageManager.persist
---
{{securecontext_header}}{{APIRef("Storage")}}
The **`persist()`** method of the {{domxref("StorageManager")}} interface requests permission to use persistent storage, and returns a {{jsxref('Promise')}} that resolves to `true` if permission is granted and bucket mode is persistent, and `false` otherwise.
> **Note:** This method is not available in [Web Workers](/en-US/docs/Web/API/Web_Workers_API), though the {{domxref("StorageManager")}} interface is.
## Syntax
```js-nolint
persist()
```
### Parameters
None.
### Return value
A {{jsxref('Promise')}} that resolves to a {{jsxref('Boolean')}}.
### Exceptions
- `TypeError`
- : Thrown if obtaining a local storage shelf failed. For example, if the current origin is an opaque origin or if the user has disabled storage.
## Example
```js
if (navigator.storage && navigator.storage.persist) {
navigator.storage.persist().then((persistent) => {
if (persistent) {
console.log("Storage will not be cleared except by explicit user action");
} else {
console.log("Storage may be cleared by the UA under storage pressure.");
}
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/overconstrainederror/index.md | ---
title: OverconstrainedError
slug: Web/API/OverconstrainedError
page-type: web-api-interface
browser-compat: api.OverconstrainedError
---
{{APIRef("Media Capture and Streams")}}
The **`OverconstrainedError`** interface of the [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API) indicates that the set of desired capabilities for the current {{domxref('MediaStreamTrack')}} cannot currently be met. When this event is thrown on a MediaStreamTrack, it is muted until either the current constraints can be established or until satisfiable constraints are applied.
{{InheritanceDiagram}}
## Constructor
- {{domxref("OverconstrainedError.OverconstrainedError", "OverconstrainedError()")}}
- : Creates a new `OverconstrainedError` object.
## Instance properties
_Also inherits properties from its parent interface, {{domxref('DOMException')}}._
- {{domxref("OverconstrainedError.constraint")}} {{ReadOnlyInline}}
- : Returns the constraint that was supplied in the constructor, meaning the constraint that was not satisfied.
## Instance methods
_Also inherits methods from its parent interface, {{domxref('DOMException')}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/overconstrainederror | data/mdn-content/files/en-us/web/api/overconstrainederror/constraint/index.md | ---
title: "OverconstrainedError: constraint property"
short-title: constraint
slug: Web/API/OverconstrainedError/constraint
page-type: web-api-instance-property
browser-compat: api.OverconstrainedError.constraint
---
{{APIRef("Media Capture and Streams")}}
The **`constraint`** read-only property of the
{{domxref("OverconstrainedError")}} interface returns the constraint that was supplied
in the constructor, meaning the constraint that was not satisfied.
## Value
A string.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/overconstrainederror | data/mdn-content/files/en-us/web/api/overconstrainederror/overconstrainederror/index.md | ---
title: "OverconstrainedError: OverconstrainedError() constructor"
short-title: OverconstrainedError()
slug: Web/API/OverconstrainedError/OverconstrainedError
page-type: web-api-constructor
browser-compat: api.OverconstrainedError.OverconstrainedError
---
{{APIRef("Media Capture and Streams")}}
The **`OverconstrainedError()`** constructor
creates a new {{domxref("OverconstrainedError")}} object which indicates that the set of
desired capabilities for the current {{domxref("MediaStreamTrack")}} cannot currently be
met. When this event is thrown on a `MediaStreamTrack`, it is muted until
either the current constraints can be established or until satisfiable constraints are
applied.
## Syntax
```js-nolint
new OverconstrainedError()
```
### Parameters
- `constraint`
- : The constraint that was not satisfied.
- `message` {{optional_inline}}
- : Text for the error's `message` property. Defaults to an empty string.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmltemplateelement/index.md | ---
title: HTMLTemplateElement
slug: Web/API/HTMLTemplateElement
page-type: web-api-interface
browser-compat: api.HTMLTemplateElement
---
{{APIRef("Web Components")}}
The **`HTMLTemplateElement`** interface enables access to the contents of an HTML {{HTMLElement("template")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface inherits the properties of {{domxref("HTMLElement")}}._
- {{domxref("HTMLTemplateElement.content", "content")}} {{ReadOnlyInline}}
- : A read-only {{domxref("DocumentFragment")}} which contains the DOM subtree representing the {{HTMLElement("template")}} element's template contents.
## Instance methods
_This interface inherits the methods of {{domxref("HTMLElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmltemplateelement | data/mdn-content/files/en-us/web/api/htmltemplateelement/content/index.md | ---
title: "HTMLTemplateElement: content property"
short-title: content
slug: Web/API/HTMLTemplateElement/content
page-type: web-api-instance-property
browser-compat: api.HTMLTemplateElement.content
---
{{APIRef("Web Components")}}
The **`HTMLTemplateElement.content`** property returns a
`<template>` element's template contents (a
{{domxref("DocumentFragment")}}).
## Value
A {{domxref("DocumentFragment")}}.
## Examples
```js
const templateElement = document.querySelector("#foo");
const documentFragment = templateElement.content.cloneNode(true);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLTemplateElement")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/domrectreadonly/index.md | ---
title: DOMRectReadOnly
slug: Web/API/DOMRectReadOnly
page-type: web-api-interface
browser-compat: api.DOMRectReadOnly
---
{{APIRef("Geometry Interfaces")}}
The **`DOMRectReadOnly`** interface specifies the standard properties (also used by {{domxref("DOMRect")}}) to define a rectangle whose properties are immutable.
## Constructor
- {{domxref("DOMRectReadOnly.DOMRectReadOnly","DOMRectReadOnly()")}}
- : Defined to create a new `DOMRectReadOnly` object.
## Instance properties
- {{domxref("DOMRectReadOnly.x")}} {{ReadOnlyInline}}
- : Returns the x coordinate of the `DOMRectReadOnly`'s origin.
- {{domxref("DOMRectReadOnly.y")}} {{ReadOnlyInline}}
- : Returns the y coordinate of the `DOMRectReadOnly`'s origin.
- {{domxref("DOMRectReadOnly.width")}} {{ReadOnlyInline}}
- : Returns the width of the `DOMRectReadOnly`.
- {{domxref("DOMRectReadOnly.height")}} {{ReadOnlyInline}}
- : Returns the height of the `DOMRectReadOnly`.
- {{domxref("DOMRectReadOnly.top")}} {{ReadOnlyInline}}
- : Returns the top coordinate value of the `DOMRectReadOnly` (usually the same as `y`).
- {{domxref("DOMRectReadOnly.right")}} {{ReadOnlyInline}}
- : Returns the right coordinate value of the `DOMRectReadOnly` (usually the same as `x + width`).
- {{domxref("DOMRectReadOnly.bottom")}} {{ReadOnlyInline}}
- : Returns the bottom coordinate value of the `DOMRectReadOnly` (usually the same as `y + height`).
- {{domxref("DOMRectReadOnly.left")}} {{ReadOnlyInline}}
- : Returns the left coordinate value of the `DOMRectReadOnly` (usually the same as `x`).
## Static methods
- {{domxref("DOMRectReadOnly/fromRect_static", "DOMRectReadOnly.fromRect()")}}
- : Creates a new `DOMRectReadOnly` object with a given location and dimensions.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("DOMPoint")}}
| 0 |
data/mdn-content/files/en-us/web/api/domrectreadonly | data/mdn-content/files/en-us/web/api/domrectreadonly/y/index.md | ---
title: "DOMRectReadOnly: y property"
short-title: "y"
slug: Web/API/DOMRectReadOnly/y
page-type: web-api-instance-property
browser-compat: api.DOMRectReadOnly.y
---
{{APIRef("Geometry Interfaces")}}
The **`y`** read-only property of the **`DOMRectReadOnly`** interface represents the y coordinate of the `DOMRect`'s origin.
## Value
A double.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("DOMRect")}}
| 0 |
data/mdn-content/files/en-us/web/api/domrectreadonly | data/mdn-content/files/en-us/web/api/domrectreadonly/x/index.md | ---
title: "DOMRectReadOnly: x property"
short-title: x
slug: Web/API/DOMRectReadOnly/x
page-type: web-api-instance-property
browser-compat: api.DOMRectReadOnly.x
---
{{APIRef("Geometry Interfaces")}}
The **`x`** read-only property of the **`DOMRectReadOnly`** interface represents the x coordinate of the `DOMRect`'s origin.
## Value
A double.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("DOMRect")}}
| 0 |
data/mdn-content/files/en-us/web/api/domrectreadonly | data/mdn-content/files/en-us/web/api/domrectreadonly/top/index.md | ---
title: "DOMRectReadOnly: top property"
short-title: top
slug: Web/API/DOMRectReadOnly/top
page-type: web-api-instance-property
browser-compat: api.DOMRectReadOnly.top
---
{{APIRef("Geometry Interfaces")}}
The **`top`** read-only property of the **`DOMRectReadOnly`** interface returns the top coordinate value of the `DOMRect`. (Has the same value as `y`, or `y + height` if `height` is negative.)
## Value
A double.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("DOMRect")}}
| 0 |
data/mdn-content/files/en-us/web/api/domrectreadonly | data/mdn-content/files/en-us/web/api/domrectreadonly/domrectreadonly/index.md | ---
title: "DOMRectReadOnly: DOMRectReadOnly() constructor"
short-title: DOMRectReadOnly()
slug: Web/API/DOMRectReadOnly/DOMRectReadOnly
page-type: web-api-constructor
browser-compat: api.DOMRectReadOnly.DOMRectReadOnly
---
{{APIRef("Geometry Interfaces")}}
The **`DOMRectReadOnly()`** constructor creates a new {{domxref("DOMRectReadOnly")}} object.
## Syntax
```js-nolint
new DOMRectReadOnly(x, y, width, height)
```
### Parameters
- `x`
- : The `x` coordinate of the `DOMRectReadOnly`'s
origin.
- `y`
- : The `y` coordinate of the `DOMRectReadOnly`'s
origin.
- `width`
- : The width of the `DOMRectReadOnly`.
- `height`
- : The height of the `DOMRectReadOnly`.
## Examples
To create a new `DOMRectReadOnly`, you could run a line of code like so:
```js
const myDOMRect = new DOMRectReadOnly(0, 0, 100, 100);
// running 'myDOMRect' in the console would then return
// DOMRectReadOnly { x: 0, y: 0, width: 100, height: 100, top: 0, right: 100, bottom: 100, left: 0 }
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("DOMPoint")}}
- {{domxref("DOMRect")}}
| 0 |
data/mdn-content/files/en-us/web/api/domrectreadonly | data/mdn-content/files/en-us/web/api/domrectreadonly/bottom/index.md | ---
title: "DOMRectReadOnly: bottom property"
short-title: bottom
slug: Web/API/DOMRectReadOnly/bottom
page-type: web-api-instance-property
browser-compat: api.DOMRectReadOnly.bottom
---
{{APIRef("Geometry Interfaces")}}
The **`bottom`** read-only property of the **`DOMRectReadOnly`** interface returns the bottom coordinate value of the `DOMRect`. (Has the same value as `y + height`, or `y` if `height` is negative.)
## Value
A double.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("DOMRect")}}
| 0 |
data/mdn-content/files/en-us/web/api/domrectreadonly | data/mdn-content/files/en-us/web/api/domrectreadonly/right/index.md | ---
title: "DOMRectReadOnly: right property"
short-title: right
slug: Web/API/DOMRectReadOnly/right
page-type: web-api-instance-property
browser-compat: api.DOMRectReadOnly.right
---
{{APIRef("Geometry Interfaces")}}
The **`right`** read-only property of the **`DOMRectReadOnly`** interface returns the right coordinate value of the `DOMRect`. (Has the same value as `x + width`, or `x` if `width` is negative.)
## Value
A double.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("DOMRect")}}
| 0 |
data/mdn-content/files/en-us/web/api/domrectreadonly | data/mdn-content/files/en-us/web/api/domrectreadonly/width/index.md | ---
title: "DOMRectReadOnly: width property"
short-title: width
slug: Web/API/DOMRectReadOnly/width
page-type: web-api-instance-property
browser-compat: api.DOMRectReadOnly.width
---
{{APIRef("Geometry Interfaces")}}
The **`width`** read-only property of the **`DOMRectReadOnly`** interface represents the width of the `DOMRect`.
## Value
A double.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("DOMRect")}}
| 0 |
data/mdn-content/files/en-us/web/api/domrectreadonly | data/mdn-content/files/en-us/web/api/domrectreadonly/left/index.md | ---
title: "DOMRectReadOnly: left property"
short-title: left
slug: Web/API/DOMRectReadOnly/left
page-type: web-api-instance-property
browser-compat: api.DOMRectReadOnly.left
---
{{APIRef("Geometry Interfaces")}}
The **`left`** read-only property of the **`DOMRectReadOnly`** interface returns the left coordinate value of the `DOMRect`. (Has the same value as `x`, or `x + width` if `width` is negative.)
## Value
A double.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("DOMRect")}}
| 0 |
data/mdn-content/files/en-us/web/api/domrectreadonly | data/mdn-content/files/en-us/web/api/domrectreadonly/height/index.md | ---
title: "DOMRectReadOnly: height property"
short-title: height
slug: Web/API/DOMRectReadOnly/height
page-type: web-api-instance-property
browser-compat: api.DOMRectReadOnly.height
---
{{APIRef("Geometry Interfaces")}}
The **`height`** read-only property of the **`DOMRectReadOnly`** interface represents the height of the `DOMRect`.
## Value
A double.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("DOMRect")}}
| 0 |
data/mdn-content/files/en-us/web/api/domrectreadonly | data/mdn-content/files/en-us/web/api/domrectreadonly/fromrect_static/index.md | ---
title: "DOMRectReadOnly: fromRect() static method"
short-title: fromRect()
slug: Web/API/DOMRectReadOnly/fromRect_static
page-type: web-api-static-method
browser-compat: api.DOMRectReadOnly.fromRect_static
---
{{APIRef("Geometry Interfaces")}}
The **`fromRect()`** static method of the
{{domxref("DOMRectReadOnly")}} object creates a new `DOMRectReadOnly`
object with a given location and dimensions.
## Syntax
```js-nolint
DOMRectReadOnly.fromRect()
DOMRectReadOnly.fromRect(rectangle)
```
### Parameters
- `rectangle` {{optional_inline}}
- : An object specifying the location and dimensions of a rectangle. All properties
default to `0`. The properties are:
- `x`: The coordinate of the left side of the rectangle.
- `y`: The coordinate of the top side of the rectangle.
- `width`: The width of the rectangle.
- `height`: The height of the rectangle.
### Return value
An instance of {{domxref("DOMRectReadOnly")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgstyleelement/index.md | ---
title: SVGStyleElement
slug: Web/API/SVGStyleElement
page-type: web-api-interface
browser-compat: api.SVGStyleElement
---
{{APIRef("SVG")}}
The **`SVGStyleElement`** interface corresponds to the SVG {{SVGElement("style")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._
- {{domxref("SVGStyleElement.type")}} {{deprecated_inline}}
- : A string corresponding to the {{SVGAttr("type")}} attribute of the given element.
- {{domxref("SVGStyleElement.media")}}
- : A string corresponding to the {{SVGAttr("media")}} attribute of the given element.
- {{domxref("SVGStyleElement.title")}}
- : A string corresponding to the [`title`](/en-US/docs/Web/SVG/Element/style#title) attribute of the given element.
- {{domxref("SVGStyleElement.sheet")}} {{ReadOnlyInline}}
- : Returns the {{domxref("CSSStyleSheet")}} object associated with the given element, or `null` if there is none.
- {{domxref("SVGStyleElement.disabled")}}
- : A boolean value indicating whether or not the associated stylesheet is disabled.
## Instance methods
_This interface doesn't implement any specific methods, but inherits methods from its parent interface, {{domxref("SVGElement")}}._
## Examples
### Dynamically adding an SVG style element
To dynamically create an SVG style element (`SVGStyleElement`), you need to use [`Document.createElementNS()`](/en-US/docs/Web/API/Document/createElementNS), specifying a `style` element in the SVG namespace.
> **Note:** [`Document.createElement()`](/en-US/docs/Web/API/Document/createElement) can't be used to create SVG style elements (it returns an [`HTMLStyleElement`](/en-US/docs/Web/API/HTMLStyleElement)).
Given the following SVG element:
```html
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<circle cx="50" cy="50" r="25" />
</svg>
```
You can create an SVG style element as shown:
```js
// Get the SVG element object by tag name
const svg = document.querySelector("svg");
// Create the `style` element in the SVG namespace
const style = document.createElementNS("http://www.w3.org/2000/svg", "style");
const node = document.createTextNode("circle { fill: red; }");
style.appendChild(node);
// Append the style element to the SVG element
svg.appendChild(style);
```
### Accessing an existing SVG style
You can access an SVG style element that was defined in HTML (or an SVG file) using the normal HTML methods for getting tags, ids, and so on.
These include: {{domxref("Document.getElementsByTagName()")}}, {{domxref("Document.getElementById()")}}, {{domxref("Document.querySelector()")}}, {{domxref("Document.querySelectorAll()")}}, and so on.
For example, consider the HTML below that defines an SVG file with a style element.
```html
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<style id="circle_style_id">
circle {
fill: gold;
stroke: green;
stroke-width: 3px;
}
</style>
<circle cx="50" cy="50" r="25" />
</svg>
```
To fetch the first `style` element in the first `svg` element, you might use {{domxref("Document.querySelector()")}} as shown below.
```js
const svg = document.querySelector("svg");
const style = svg.querySelector("style");
```
Alternatively, you can could use {{domxref("Document.getElementById()")}}, specifying the tag id:
```js
const svg = document.querySelector("svg");
const style = svg.getElementById("circle_style_id");
```
Or just get the element from document by id (in this case using `document.querySelector()`):
```js
const style = document.querySelector("#circle_style_id");
```
## Getting and setting properties
This example demonstrates how to get and set the properties of a style element, which in this case was specified in an SVG definition.
### HTML
The HTML contains an SVG definition for a [`<circle>`](/en-US/docs/Web/SVG/Element/circle) with a [`<style>`](/en-US/docs/Web/SVG/Element/style) element, along with an HTML [`<button>`](/en-US/docs/Web/HTML/Element/button) element that will be used to enable and disable the style, and an HTML [`<textarea>`](/en-US/docs/Web/HTML/Element/button) element for logging the property values.
```html
<button>Disable</button>
<textarea id="log" rows="6" cols="90"></textarea>
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<style id="circle_style_id" media="all and (min-width: 600px)">
circle {
fill: gold;
stroke: green;
stroke-width: 3px;
}
</style>
<circle cx="60" cy="60" r="50" />
</svg>
```
Note that above we have set the `media` attribute on the `style` tag.
We have not set `type` as it is deprecated, or `disabled` because there is no such attribute (only the property on the element).
### JavaScript
The code below gets the `style` element (an `SVGStyleElement`) using its id.
```js
const svg = document.querySelector("svg");
const style = svg.getElementById("circle_style_id");
```
We then add a function to log the style properties.
This is called after initialization, whenever the frame resizes, and if the button is pressed.
```js
// Get logging text area
const log = document.getElementById("log");
function setLogText() {
//Log current values of properties
log.value = `style.media: ${style.media} (frame width: ${window.innerWidth})\n`; // 'all' by default
log.value += `style.title: ${style.title}\n`; // no default value
log.value += `style.disabled: ${style.disabled}\n`; // 'false' by default
log.value += `style.type: ${style.type}\n`; // deprecated (do not use)
log.value += `style.sheet.rules[0].cssText: ${style.sheet.rules[0].cssText}\n`;
}
// Log initial property values
setLogText();
// Log when the frame resizes
addEventListener("resize", () => {
setLogText();
});
```
Last of all we set an event handler for the button.
When the button is clicked the {{domxref("SVGStyleElement.disabled","disabled")}} property is toggled.
This also updates the log and the button text.
```js
const button = document.querySelector("button");
button.addEventListener("click", () => {
style.disabled = !style.disabled;
button.textContent = style.disabled ? "Enable" : "Disable";
// Log after button presses
setLogText();
});
```
### Result
The result is shown below.
Toggle the button to enable and disable the SVG style element.
If the SVG style is not disabled, you can also resize the window width to see the effect of the `media` property on the style when the frame holding the live example is 600px wide.
{{EmbedLiveSample("Getting and setting properties","200","250")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLStyleElement")}}
| 0 |
data/mdn-content/files/en-us/web/api/svgstyleelement | data/mdn-content/files/en-us/web/api/svgstyleelement/title/index.md | ---
title: "SVGStyleElement: title property"
short-title: title
slug: Web/API/SVGStyleElement/title
page-type: web-api-instance-property
browser-compat: api.SVGStyleElement.title
---
{{APIRef("SVG")}}
The **`SVGStyleElement.title`** property is a string corresponding to the [`title`](/en-US/docs/Web/SVG/Element/style#title) attribute of the given SVG style element.
It may be used to select between [alternate style sheets](/en-US/docs/Web/CSS/Alternative_style_sheets).
## Value
A string with any value.
The value is initialized with the string specified in the corresponding style's [`title`](/en-US/docs/Web/SVG/Element/style#title) attribute.
## Examples
This example demonstrates programmatically getting and setting the `title` property on a style that was defined in an SVG definition.
### HTML
The HTML contains an SVG definition for a [`<circle>`](/en-US/docs/Web/SVG/Element/circle) with a [`<style>`](/en-US/docs/Web/SVG/Element/style) element that has a `title`.
We also define a text area for logging the current title.
```html
<textarea id="log" rows="3" cols="50"></textarea>
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<style title="gold fill style">
circle {
fill: gold;
}
</style>
<circle cx="50" cy="40" r="25" />
</svg>
```
### JavaScript
The code below gets the `style` element (an `SVGStyleElement`) using its tag name, logs the title, then changes and logs the title again.
```js
const log = document.getElementById("log");
const svg = document.querySelector("svg");
const style = svg.querySelector("style");
log.value = `Initial title: ${style.title}\n`;
style.title = "Altered Title";
log.value += `New title: ${style.title}`;
```
### Result
The text in the log below shows that the title initially reflects the matching attribute on the `<style>` element, but can then be changed to another value.
{{EmbedLiveSample("Examples")}}
Note that alternate styles are not applied by default; they must be selected as the preferred stylesheet by the user.
To apply the alternate stylesheets on Firefox:
1. Open the Menu Bar (Press `F10` or tap the `Alt` key)
2. Open **View > Page Style** submenu
3. Select the stylesheets based on their names.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/svgstyleelement | data/mdn-content/files/en-us/web/api/svgstyleelement/media/index.md | ---
title: "SVGStyleElement: media property"
short-title: media
slug: Web/API/SVGStyleElement/media
page-type: web-api-instance-property
browser-compat: api.SVGStyleElement.media
---
{{APIRef("SVG")}}
The **`SVGStyleElement.media`** property is a media query string corresponding to the [`media`](/en-US/docs/Web/SVG/Element/style#media) attribute of the given SVG style element.
The query must be matched for the style to apply.
## Value
A string defining a valid media query list with one or more comma separated values.
For example `"screen, print"`, or `"all"` (the default).
The value is initialized with the string specified in the corresponding style's [`media`](/en-US/docs/Web/SVG/Element/style#media) attribute.
## Examples
This example demonstrates programmatically getting and setting the media property on a style that was defined in an SVG definition.
### HTML
The HTML contains an SVG definition for a [`<circle>`](/en-US/docs/Web/SVG/Element/circle) with a [`<style>`](/en-US/docs/Web/SVG/Element/style) element that is conditional on the media query `"all and (min-width: 600px)"`.
We also define a `button` that will be used to display the current style and change the style.
```html
<button></button>
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<circle cx="60" cy="60" r="50" />
</svg>
```
### JavaScript
The code below gets the `style` element (an `SVGStyleElement`) using its id.
```js
const svg = document.querySelector("svg");
// Create the `style` element in the SVG namespace
const style = document.createElementNS("http://www.w3.org/2000/svg", "style");
const node = document.createTextNode("circle { fill: red; }");
svg.appendChild(style);
style.appendChild(node);
```
We then add a function to set the button text to show the current value of the style's `media` property along with the current window width.
This function is called to set the initial button text, and also when the window is resized or the button is pressed.
The button event handler also sets the value of the style's `media` property.
```js
const button = document.querySelector("button");
function setButtonText() {
button.textContent = `Media: ${style.media} (Width: ${window.innerWidth})`;
}
setButtonText();
addEventListener("resize", () => {
setButtonText();
});
button.addEventListener("click", () => {
style.media = "all and (min-width: 700px)";
setButtonText();
});
```
### Result
The result is shown below.
The button text shows the value of the media attribute originally applied to the SVG style along with the width of the current frame (since the code is run in a frame).
Shrink the width of the frame to the media query width shown in the button to watch the style being applied.
Press the button to toggle the value of the `media` property on the style (which will be reflected on the button).
{{EmbedLiveSample("Examples")}}
> **Note:** The `media` property may be set to any string, but will be ignored if the string is not a valid media query.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLStyleElement.media")}}
| 0 |
data/mdn-content/files/en-us/web/api/svgstyleelement | data/mdn-content/files/en-us/web/api/svgstyleelement/sheet/index.md | ---
title: "SVGStyleElement: sheet property"
short-title: sheet
slug: Web/API/SVGStyleElement/sheet
page-type: web-api-instance-property
browser-compat: api.SVGStyleElement.sheet
---
{{APIRef("SVG")}}
The **`SVGStyleElement.sheet`** read-only property returns the {{domxref("CSSStyleSheet")}} corresponding to the given SVG style element, or `null` if there is none.
## Value
A {{domxref("CSSStyleSheet")}}, or `null` if the element has no associated style sheet.
## Examples
This example demonstrates how to get the CSS sheet associated with an element.
### HTML
The HTML contains an SVG definition for a [`<circle>`](/en-US/docs/Web/SVG/Element/circle).
```html
<textarea id="log" rows="3" cols="50"></textarea>
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<circle cx="50" cy="50" r="25" />
</svg>
```
### JavaScript
The code below creates a `style` element (an `SVGStyleElement`) and adds it to the SVG.
```js
const svg = document.querySelector("svg");
// Create the `style` element in the SVG namespace
const style = document.createElementNS("http://www.w3.org/2000/svg", "style");
const node = document.createTextNode("circle { fill: red; }");
svg.appendChild(style);
style.appendChild(node);
```
The code below then logs the sheet and CSS rule associated with this new element, using `style.sheet`.
To make
```js
// Log the sheet associated with this new element.
const log = document.getElementById("log");
log.value = `${style.sheet} with rules[0].cssText:\n ${style.sheet.rules[0].cssText}`;
```
### Result
The result is shown below.
On success, the log shows the `CSSStyleSheet` object applied to the SVG circle.
{{EmbedLiveSample("Examples")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLStyleElement.sheet")}}
| 0 |
data/mdn-content/files/en-us/web/api/svgstyleelement | data/mdn-content/files/en-us/web/api/svgstyleelement/disabled/index.md | ---
title: "SVGStyleElement: disabled property"
short-title: disabled
slug: Web/API/SVGStyleElement/disabled
page-type: web-api-instance-property
browser-compat: api.SVGStyleElement.disabled
---
{{APIRef("SVG")}}
The **`SVGStyleElement.disabled`** property can be used to get and set whether the stylesheet is disabled (`true`) or not (`false`).
Note that there is no corresponding `disabled` attribute on the [SVG `<style>` element](/en-US/docs/Web/SVG/Element/style).
## Value
Returns `true` if the stylesheet is disabled, or there is no associated stylesheet; otherwise `false`.
The value is `false` by default (if there is an associated stylesheet).
The property can be used to enable or disable an associated stylesheet.
Setting the property to `true` when there is no associated stylesheet has no effect.
## Examples
### Disabling a style defined in the SVG
This example demonstrates programmatically setting the disabled property on a style that was defined in the HTML SVG definition.
#### HTML
The HTML contains an SVG definition for a [`<circle>`](/en-US/docs/Web/SVG/Element/circle) with a [`<style>`](/en-US/docs/Web/SVG/Element/style) element, along with a button that will be used to disable the style.
```html
<button>Enable</button>
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<style id="circle_style_id">
circle {
fill: gold;
stroke: green;
stroke-width: 3px;
}
</style>
<circle cx="50" cy="50" r="25" />
</svg>
```
#### JavaScript
The code below gets the `style` element (an `SVGStyleElement`) using its id, and then sets it as disabled.
The style already exists because it is defined in the SVG, so this should succeed.
```js
const svg = document.querySelector("svg");
const style = svg.getElementById("circle_style_id");
style.disabled = true;
```
We then add an event handler for the button that toggles the disabled state and button text.
```js
const button = document.querySelector("button");
button.addEventListener("click", () => {
style.disabled = !style.disabled;
button.textContent = style.disabled ? "Enable" : "Disable";
});
```
#### Result
The result is shown below.
Press the button to toggle the `disabled` property on the style used for the circle.
{{EmbedLiveSample("Disabling a style defined in the SVG")}}
### Disabling a programmatically defined style
This example is very similar to the one above, except that the style is defined programmatically.
Note that you can have multiple styles applied both in SVG source and programmatically.
This example is primarily provided to demonstrate how to create the style externally, and show at what point the style can be disabled.
#### HTML
The HTML is similar to the previous case, but the SVG definition does not include any default styling.
```html
<button>Enable</button>
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<circle cx="50" cy="50" r="25" />
</svg>
```
#### JavaScript
First we create the new SVG style node.
This is done by first creating a style element in the SVG namespace using [`Document.createElementNS()`](/en-US/docs/Web/API/Document/createElementNS), creating and appending a text node with the style definition, and then appending the node to the SVG defined above.
> **Note:** You must use [`Document.createElementNS()`](/en-US/docs/Web/API/Document/createElementNS) and not [`Document.createElement()`](/en-US/docs/Web/API/Document/createElement) to create the style, or by default you'll create the equivalent HTML style element.
```js
const svg = document.querySelector("svg");
// Create the `style` element in the SVG namespace
const style = document.createElementNS("http://www.w3.org/2000/svg", "style");
const node = document.createTextNode("circle { fill: red; }");
svg.appendChild(style);
style.appendChild(node);
```
Then we disable the style.
Note that this is the earliest point at which setting the property to `true` will succeed.
Before this point the SVG did not have a style associated, and so the value defaults to `false`.
```js
//Disable the style
style.disabled = true;
```
Last of all we add an event handler for the button that toggles the disabled state and button text (this is the same as in the previous example).
```js
const button = document.querySelector("button");
button.addEventListener("click", () => {
style.disabled = !style.disabled;
button.textContent = style.disabled ? "Enable" : "Disable";
});
```
#### Result
The result is shown below.
Press the button to toggle the `disabled` state on the style used for the circle.
{{EmbedLiveSample("Disabling a programmatically defined style")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLStyleElement.disabled")}}
| 0 |
data/mdn-content/files/en-us/web/api/svgstyleelement | data/mdn-content/files/en-us/web/api/svgstyleelement/type/index.md | ---
title: "SVGStyleElement: type property"
short-title: type
slug: Web/API/SVGStyleElement/type
page-type: web-api-instance-property
status:
- deprecated
browser-compat: api.SVGStyleElement.type
---
{{APIRef("SVG")}} {{Deprecated_Header}}
The **`SVGStyleElement.type`** property returns the type of the current style.
The value reflects the associated SVG `<style>` element's [`type`](/en-US/docs/Web/SVG/Element/style#type) attribute.
Authors should not use this property or rely on the value.
## Value
The permitted values are an empty string or a case-insensitive match for "text/css".
## Exceptions
SVG 1.1 defined that a {{domxref("DOMException")}} is raised with code `NO_MODIFICATION_ALLOWED_ERR` on an attempt to change the value of a read-only attribute.
This restriction was removed in SVG 2.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLStyleElement.type")}}
| 0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.