CSSPrimitiveValue: getStringValue() method - Web APIs

CSSPrimitiveValue: getStringValue() method
==========================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The **`getStringValue()`** method of the
 `CSSPrimitiveValue` interface is used to get a string value. If this CSS
 value doesn't contain a string value, a `DOMException` is raised.

**Note:** This method was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do
 not implement it.

To achieve your purpose, you can use:

* the untyped CSS Object Model, widely supported, or
* the modern CSS Typed Object Model API, less supported and considered experimental.

Syntax
------

```js
getStringValue()
```

### Parameters

None.

### Return value

A `string` value.

### Exceptions

| **Type** | **Description** |
| --- | --- |
| `DOMException` | An `INVALID_ACCESS_ERR` is raised if the CSS value doesn't contain a string value. |

Examples
--------

```js
const cs = window.getComputedStyle(document.body);
const cssValue = cs.getPropertyCSSValue("display");
console.log(cssValue.getStringValue());
```

Specifications
--------------

 This feature was originally defined in the DOM Style Level 2 specification, but has been dropped from any
 standardization effort since then.

It has been superseded by a modern, but incompatible, CSS Typed Object Model API that is now on the standard track.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


DelayNode: delayTime property - Web APIs

DelayNode: delayTime property
=============================

The `delayTime` property of the `DelayNode` interface is an a-rate `AudioParam` representing the amount of delay to apply.

`delayTime` is expressed in seconds, its minimal value is `0`, and its maximum value is defined by the `maxDelayTime` argument of the `BaseAudioContext.createDelay` method that created it.

**Note:** Though the `AudioParam` returned is read-only, the value it represents is not.

Value
-----

An `AudioParam`.

Examples
--------

See `BaseAudioContext.createDelay()` for example code.

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-delaynode-delaytime |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


DelayNode: DelayNode() constructor - Web APIs

DelayNode: DelayNode() constructor
==================================

 The **`DelayNode()`**
 constructor of the Web Audio API
 creates a new `DelayNode` object with a delay-line; an AudioNode
 audio-processing module that causes a delay between the arrival of an input data, and
 its propagation to the output.

Syntax
------

```js
new DelayNode(context)
new DelayNode(context, options)
```

### Parameters

`context`

A reference to an `AudioContext` or `OfflineAudioContext`.

`options` Optional

An object specifying the delay node options. Can contain the following members:

`delayTime`

 The initial delay time for the node, in seconds. The
 default is `0`.

`maxDelayTime`

 The maximum delay time for the node, in seconds.
 Defaults to `1`.

`channelCount`

 Represents an integer used to determine how many channels are used when up-mixing and down-mixing connections to any inputs to the node. (See
 `AudioNode.channelCount` for more information.) Its usage and precise
 definition depend on the value of `channelCountMode`.

`channelCountMode`

 Represents an enumerated value describing the way channels must be matched between
 the node's inputs and outputs. (See `AudioNode.channelCountMode` for more
 information including default values.)

`channelInterpretation`

 Represents an enumerated value describing the meaning of the channels. This
 interpretation will define how audio up-mixing and down-mixing will happen.
 The possible values are `"speakers"` or `"discrete"`. (See
 `AudioNode.channelCountMode` for more information including default
 values.)

### Return value

A new `DelayNode` object instance.

Examples
--------

```js
const audioCtx = new AudioContext();
const delayNode = new DelayNode(audioCtx, {
  delayTime: 0.5,
  maxDelayTime: 2,
});
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-delaynode-constructor-delaynode |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


GeolocationCoordinates: speed property - Web APIs

GeolocationCoordinates: speed property
======================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **`speed`** read-only property of the `GeolocationCoordinates` interface is a `double` representing the velocity of the device in meters per second. This value is `null` if the implementation is not able to measure it.

Value
-----

A `double` representing the velocity of the device in meters per second.

Specifications
--------------

| Specification |
| --- |
| Geolocation API # speed-attribute |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Geolocation API
* `GeolocationCoordinates`


GeolocationCoordinates: latitude property - Web APIs

GeolocationCoordinates: latitude property
=========================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **`latitude`** read-only property of the `GeolocationCoordinates` interface is a `double` representing the latitude of the position in decimal degrees.

Value
-----

A `double` representing the latitude of the position in decimal degrees.

Specifications
--------------

| Specification |
| --- |
| Geolocation API # latitude-longitude-and-accuracy-attributes |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Geolocation API
* `GeolocationCoordinates`


GeolocationCoordinates: altitudeAccuracy property - Web APIs

GeolocationCoordinates: altitudeAccuracy property
=================================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **`altitudeAccuracy`** read-only property of the `GeolocationCoordinates` interface is a strictly positive `double` representing the accuracy, with a 95% confidence level, of the `altitude` expressed in meters. This value is `null` if the implementation doesn't support measuring altitude.

Value
-----

 A positive `double` representing the accuracy, with a 95% confidence level,
 of the `altitude` expressed in meters.

Specifications
--------------

| Specification |
| --- |
| Geolocation API # altitude-and-altitudeaccuracy-attributes |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Geolocation API
* `GeolocationCoordinates`


GeolocationCoordinates: heading property - Web APIs

GeolocationCoordinates: heading property
========================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **`heading`** read-only property of the `GeolocationCoordinates` interface is a `double` representing the direction in which the device is traveling. This value, specified in degrees, indicates how far off from heading due north the device is. `0` degrees represents true north, and the direction is determined clockwise (which means that east is `90` degrees and west is `270` degrees). If `GeolocationCoordinates.speed` is `0`, `heading` is `NaN`. If the device is not able to provide heading information, this value is `null`.

Value
-----

A `double` representing the direction in which the device is traveling.

Specifications
--------------

| Specification |
| --- |
| Geolocation API # heading-attribute |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Geolocation API
* `GeolocationCoordinates`


GeolocationCoordinates: longitude property - Web APIs

GeolocationCoordinates: longitude property
==========================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

 The **`longitude`** read-only property of the `GeolocationCoordinates` interface is a number which represents the longitude of a geographical position, specified in decimal degrees.
 Together with a timestamp, given as Unix time in milliseconds, indicating a time of measurement, the `GeolocationCoordinates` object is part of the `GeolocationPosition` interface, which is the object type returned by Geolocation API functions that obtain and return a geographical position.

Value
-----

 The value in `longitude` is the geographical longitude of the location on
 Earth described by the `Coordinates` object, in decimal degrees. The value is
 defined by the World Geodetic System 1984 specification (WGS 84).

**Note:** The zero meridian (also known as the prime meridian or the
 reference meridian) is not precisely the same as the Greenwich meridian that most
 people think of. It is, instead, the IERS Reference Meridian, which is located 5.3 arcseconds (102
 meters / 335 feet) east of the Greenwich meridian. This
 is the same standard used by the Global Positioning System (GPS).

Examples
--------

 In this simple example, we fetch the user's location and display the resulting
 coordinates once they're returned.

### JavaScript

 The JavaScript code below creates an event listener so that when the user clicks on a
 button, the location information is retrieved and displayed.

```js
let button = document.getElementById("get-location");
let latText = document.getElementById("latitude");
let longText = document.getElementById("longitude");

button.addEventListener("click", () => {
  navigator.geolocation.getCurrentPosition((position) => {
    let lat = position.coords.latitude;
    let long = position.coords.longitude;

    latText.innerText = lat.toFixed(2);
    longText.innerText = long.toFixed(2);
  });
});
```

 After setting up variables to more conveniently reference the button element and the
 two elements into which the latitude and longitude will be drawn, the event listener is
 established by calling `addEventListener()`
 on the `<button>` element. When the user clicks the button, we'll fetch
 and display the location information.

 Upon receiving a `click` event, we call
 `getCurrentPosition()` to request the
 device's current position. This is an asynchronous request, so we provide a callback
 which receives as in put a `GeolocationPosition` object describing the
 determined position.

 From the `GeolocationPosition` object, we obtain the user's latitude and
 longitude using `position.coords.latitude` and
 `position.coords.longitude` so we can update the displayed coordinates. The
 two `<span>` elements are updated to display the corresponding values
 after being converted to a value with two decimal places.

### HTML

The HTML used to present the results looks like this:

```html
<p>
  Your location is <span id="latitude">0.00</span>° latitude by
  <span id="longitude">0.00</span>° longitude.
</p>
<button id="get-location">Get My Location</button>
```

### Result

Take this example for a test drive here:

Specifications
--------------

| Specification |
| --- |
| Geolocation API # latitude-longitude-and-accuracy-attributes |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Geolocation API
* The `GeolocationCoordinates` interface it belongs to.
* The `GeolocationPosition` interface, which is the top-level interface
 used to return geolocation data from the Geolocation API functions
 `Geolocation.getCurrentPosition()` and
 `watchPosition()`.


GeolocationCoordinates: accuracy property - Web APIs

GeolocationCoordinates: accuracy property
=========================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **`accuracy`** read-only property of the `GeolocationCoordinates` interface is a strictly positive `double` representing the accuracy, with a 95% confidence level, of the `GeolocationCoordinates.latitude` and `GeolocationCoordinates.longitude` properties expressed in meters.

Value
-----

 A positive `double` representing the accuracy, with a 95% confidence level,
 of the `GeolocationCoordinates.latitude` and
 `GeolocationCoordinates.longitude` properties expressed in meters.

Specifications
--------------

| Specification |
| --- |
| Geolocation API # latitude-longitude-and-accuracy-attributes |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Geolocation API
* `GeolocationCoordinates`


GeolocationCoordinates: altitude property - Web APIs

GeolocationCoordinates: altitude property
=========================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **`altitude`** read-only property of the `GeolocationCoordinates` interface is a `double` representing the altitude of the position in meters above the WGS84 ellipsoid (which defines the nominal sea level surface). This value is `null` if the implementation cannot provide this data.

Value
-----

 A `double` representing the altitude of the position in meters above the WGS84
 ellipsoid.

Specifications
--------------

| Specification |
| --- |
| Geolocation API # altitude-and-altitudeaccuracy-attributes |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Geolocation API
* The `GeolocationCoordinates` interface it belongs to.
* National Imagery and Mapping Agency Technical Report 8350.2, Third Edition (WGS84)


BeforeInstallPromptEvent: prompt() method - Web APIs

BeforeInstallPromptEvent: prompt() method
=========================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The **`prompt()`** method of the `BeforeInstallPromptEvent` interface allows a developer to show the
 install prompt at a time of their own choosing. Typically this will be called in the event handler for the app's custom install UI.

This method must be called in the event handler for a user action (such as a button click) and may only be called once on a given `BeforeInstallPromptEvent` instance.

Syntax
------

```js
prompt()
```

### Parameters

None.

### Return value

A `Promise` resolving to an object containing the following properties:

`outcome`
Experimental

Non-standard

A string indicating whether the user chose to install the app or not. It must be one of the following values:

* `"accepted"`: The user installed the app.
* `"dismissed"`: The user did not install the app.

`platform`
Experimental

Non-standard

If the user chose to install the app, this is a string naming the selected platform, which is one of the values from the `BeforeInstallPromptEvent.platforms` property. If the user chose not to install the app, this is an empty string.

Examples
--------

See the example for the `BeforeInstallPromptEvent` interface.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Making PWAs installable
* How to provide your own in-app install experience on web.dev (2021)


BeforeInstallPromptEvent: BeforeInstallPromptEvent() constructor - Web APIs

BeforeInstallPromptEvent: BeforeInstallPromptEvent() constructor
================================================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`BeforeInstallPromptEvent()`** constructor creates a new `BeforeInstallPromptEvent` object.

Syntax
------

```js
new BeforeInstallPromptEvent(type)
new BeforeInstallPromptEvent(type, eventInitDict)
```

### Parameters

`type`

A string with the name of the event, set to `beforeinstallpromptevent`.

`eventInitDict` Optional

An object with a single optional property `platforms`, which is an array of strings, listing the platforms on which the event will be dispatched.

Specifications
--------------

#### No specification found

No specification data found for `api.BeforeInstallPromptEvent.BeforeInstallPromptEvent`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Making PWAs installable
* How to provide your own in-app install experience on web.dev (2021)


BeforeInstallPromptEvent: userChoice property - Web APIs

BeforeInstallPromptEvent: userChoice property
=============================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`userChoice`** property of the `BeforeInstallPromptEvent` interface represents the installation choice that the user made, when they were prompted to install the app.

Value
-----

A `Promise` which resolves to an object containing two properties:

`outcome`
Experimental

Non-standard

A string indicating whether the user chose to install the app or not. It must be one of the following values:

* `"accepted"`: The user installed the app.
* `"dismissed"`: The user did not install the app.

`platform`
Experimental

Non-standard

If the user chose to install the app, this is a string naming the selected platform, which is one of the values from the `BeforeInstallPromptEvent.platforms` property. If the user chose not to install the app, this is an empty string.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Making PWAs installable
* How to provide your own in-app install experience on web.dev (2021)


BeforeInstallPromptEvent: platforms property - Web APIs

BeforeInstallPromptEvent: platforms property
============================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`platforms`** property of the `BeforeInstallPromptEvent` interface lists the platforms on which the event was dispatched. This is provided for user agents that want to present a choice of versions to the user such as, for example, "web" or "play" which would allow the user to choose between a web version or an Android version.

Value
-----

An array of strings, in which each string identifies a target platform for the installation.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Making PWAs installable
* How to provide your own in-app install experience on web.dev (2021)


StyleSheetList: item() method - Web APIs

StyleSheetList: item() method
=============================

The **`item()`** method of the `StyleSheetList` interface returns a single `CSSStyleSheet` object.

Syntax
------

```js
item(index)
```

### Parameters

`index`

An integer which is the index of the item in the collection to be returned.

### Return value

A `CSSStyleSheet` object, or `null` if one does not exist for this index.

Examples
--------

In the following example, a for loop prints each individual `CSSStyleSheet` object to the console, by calling `item` with the value of `i`.

```js
let list = document.styleSheets;

for (let i = 0; i < list.length; i++) {
  console.log(list.item(i));
}
```

Specifications
--------------

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-stylesheetlist-item |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


StyleSheetList: length property - Web APIs

StyleSheetList: length property
===============================

The **`length`** read-only property of the `StyleSheetList` interface returns the number of `CSSStyleSheet` objects in the collection.

Value
-----

An integer indicating the number of items in the collection.

Examples
--------

In the following example, `length` is printed to the console, and also used in a for loop to print each individual `CSSStyleSheet` object to the console.

```js
let length = document.styleSheets.length;
console.log(length);

for (let i = 0; i < length; i++) {
  console.log(document.styleSheets[i]);
}
```

Specifications
--------------

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-stylesheetlist-length |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


XSLTProcessor: reset() method - Web APIs

XSLTProcessor: reset() method
=============================

The `reset()` method of the `XSLTProcessor` interface removes all parameters (`<xsl:param>`) and the XSLT stylesheet from the processor. The `XSLTProcessor` will then be in its original state when it was created.

Syntax
------

```js
reset()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-xsltprocessor-reset |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `XSLTProcessor.getParameter()`
* `XSLTProcessor.setParameter()`
* `XSLTProcessor.removeParameter()`
* `XSLTProcessor.clearParameters()`


XSLTProcessor: getParameter() method - Web APIs

XSLTProcessor: getParameter() method
====================================

The `getParameter()` method of the `XSLTProcessor` interface returns the value of a parameter (`<xsl:param>`) from the stylesheet imported in the processor.

Syntax
------

```js
getParameter(namespaceURI, localName)
```

### Parameters

`namespaceURI`

The namespace associated with the parameter name. A "null" value is treated the same as the empty string (`""`).

`localName`

The name of the parameter in the associated namespace.

### Return value

An object that is the value associated with the parameter. It can be of any type.

**Note:** Firefox supports any kind of parameter. Chrome, Edge and Safari only support string parameters.

Examples
--------

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-xsltprocessor-getparameter |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `XSLTProcessor.setParameter()`
* `XSLTProcessor.removeParameter()`
* `XSLTProcessor.clearParameters()`
* `XSLTProcessor.reset()`


XSLT Basic Example - Web APIs

XSLT Basic Example
==================

 This first example demonstrates the basics of setting up an XSLT transformation in a browser.
 The example takes an XML document that contains information about an article (title, list of authors and body text) and presents it in a human-readable form.

The XML document (**example.xml**) is shown below.

```xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="example.xsl"?>
<Article>
  <Title>My Article</Title>
  <Authors>
    <Author>Mr. Foo</Author>
    <Author>Mr. Bar</Author>
  </Authors>
  <Body>This is my article text.</Body>
</Article>
```

The `?xml-stylesheet` processing instruction in the XML file specifies the XSLT stylesheet to apply in its `href` attribute.

This XSL stylesheet file (**example.xsl**) is shown below:

```xml
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="text"/>

  <xsl:template match="/">
    Article - <xsl:value-of select="/Article/Title"/>
    Authors: <xsl:apply-templates select="/Article/Authors/Author"/>
  </xsl:template>

  <xsl:template match="Author">
    - <xsl:value-of select="." />
  </xsl:template>

</xsl:stylesheet>
```

 An XSLT stylesheet starts with the `xsl:stylesheet` element, which contains all the *templates* used to create the final output.
 The example above has two templates - one that matches the root node and one that matches `Author` nodes.
 The template that matches the root node outputs the article's title and then says to process all templates (via `apply-templates`) that match `Author` nodes which are children of the `Authors` node.

To try out the example:

1. Create a directory in your file system and inside it create the files `example.xml` and `example.xsl` listed above
2. Start a local server in the directory containing the files.
 This allows you to browse the files in the directory as though they were hosted on the internet.

**Warning:** Opening the XML file directly from the file system will not work, because loading the stylesheet from the file system is a cross-origin request, and will be disallowed by default.
 Hosting the XML and stylesheet on the same local server ensures that they have the same origin.
3. Open **example.xml** from the browser.
4. The browser output is then as shown below:
```

Browser Output :

    Article - My Article
    Authors:
    - Mr. Foo
    - Mr. Bar
```


XSLTProcessor: transformToFragment() method - Web APIs

XSLTProcessor: transformToFragment() method
===========================================

The `transformToFragment()` method of the `XSLTProcessor` interface transforms a provided `Node` source to a `DocumentFragment` using the XSLT stylesheet associated with the `XSLTProcessor`.

Syntax
------

```js
transformToFragment(source, document)
```

### Parameters

`source`

The `Node` source to apply the XSLT stylesheet to.

`document`

The `Document` the document fragment will be associated with. (Any document fragment is associated with a document it can be added to).

### Return value

A `DocumentFragment`.

Examples
--------

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-xsltprocessor-transformtofragment |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `XSLTProcessor.transformToDocument()`


XSLTProcessor: XSLTProcessor() constructor - Web APIs

XSLTProcessor: XSLTProcessor() constructor
==========================================

The **`XSLTProcessor()`** constructor creates a new `XSLTProcessor` object instance.

Syntax
------

```js
new XSLTProcessor()
```

### Parameters

None.

### Return value

A new `XSLTProcessor` object instance.

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-xsltprocessor-xsltprocessor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


XSLTProcessor: importStylesheet() method - Web APIs

XSLTProcessor: importStylesheet() method
========================================

The `importStylesheet()` method of the `XSLTProcessor` interface imports an XSLT stylesheet for the processor.

Syntax
------

```js
importStylesheet(style)
```

### Parameters

`style`

The `Node` to import. It can be an XML document (that is a `Document` with `doctype``.``name` of `"xml"`) containing an XSLT stylesheet or a literal result element transform, or an `Element` representing an `<xsl:stylesheet>` or `<xsl:transform>`.

### Return value

None (`undefined`).

Examples
--------

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-xsltprocessor-importstylesheet |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


XSLTProcessor: transformToDocument() method - Web APIs

XSLTProcessor: transformToDocument() method
===========================================

The `transformToDocument()` method of the `XSLTProcessor` interface transforms the provided `Node` source to a `Document` using the XSLT stylesheet associated with `XSLTProcessor`.

Syntax
------

```js
transformToDocument(source)
```

### Parameters

`source`

The `Node` source to apply the XSLT stylesheet to.

### Return value

A `Document`. The actual interface depends on the output method of the stylesheet:

| Output method | Result interface |
| --- | --- |
| `html` | `HTMLDocument` |
| `xml` | `XMLDocument` |
| `text` | `XMLDocument` with a single root element `<transformiix:result>` with the text as a child |

Examples
--------

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-xsltprocessor-transformtodocument |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `XSLTProcessor.transformToDocument()`


XSLTProcessor: removeParameter() method - Web APIs

XSLTProcessor: removeParameter() method
=======================================

The `removeParameter()` method of the `XSLTProcessor` interface removes the parameter (`<xsl:param>`) and its value from the stylesheet imported in the processor.

Syntax
------

```js
removeParameter(namespaceURI, localName)
```

### Parameters

`namespaceURI`

The namespace associated with the parameter name. A "null" value is treated the same as the empty string (`""`).

`localName`

The name of the parameter in the associated namespace.

### Return value

None (`undefined`).

Examples
--------

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-xsltprocessor-removeparameter |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `XSLTProcessor.getParameter()`
* `XSLTProcessor.setParameter()`
* `XSLTProcessor.clearParameters()`
* `XSLTProcessor.reset()`


Introduction - Web APIs

Introduction
============

One noticeable trend in W3C standards has been the effort to separate content from style. This would allow the same style to be reused for multiple content, as well as simplify maintenance and allow a quick (only modify one file) way to change the look of content.

CSS (Cascade Style Sheets) was one of the first ways proposed by the W3C. CSS is a simple way to apply style rules to a web document. These style rules define how the document (the content) should be laid out. However, it has several limitations, such as lack of programming structures and ability to create complex layout models. CSS also has limited support for changing the position of an element.

XSL (Extensible Stylesheet Language) Transformations are composed of two parts: XSL elements, which allow the transformation of an XML tree into another markup tree and XPath, a selection language for trees. XSLT takes an XML document (the content) and creates a brand new document based on the rules in the XSL stylesheet. This allows XSLT to add, remove and reorganize elements from the original XML document and thus allows more fine-grain control of the resulting document's structure.

Transformations in XSLT are based on rules that consist of templates. Each template matches (using XPath) a certain fragment of the input XML document and then applies the substitution part on that fragment to create the new resulting document.


XSLTProcessor: setParameter() method - Web APIs

XSLTProcessor: setParameter() method
====================================

The `setParameter()` method of the `XSLTProcessor` interface sets the value of a parameter (`<xsl:param>`) in the stylesheet imported in the processor.

Syntax
------

```js
setParameter(namespaceURI, localName, value)
```

### Parameters

`namespaceURI`

The namespace associated with the parameter name. A "null" value is treated the same as the empty string (`""`).

`localName`

The name of the parameter in the associated namespace.

`value`

The value of the parameter.

**Note:** Firefox supports any kind of parameter. Chrome, Edge and Safari only support string parameters.

### Return value

None (`undefined`).

Examples
--------

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-xsltprocessor-setparameter |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `XSLTProcessor.getParameter()`
* `XSLTProcessor.removeParameter()`
* `XSLTProcessor.clearParameters()`
* `XSLTProcessor.reset()`


XSLTProcessor: clearParameters() method - Web APIs

XSLTProcessor: clearParameters() method
=======================================

The `clearParameters()` method of the `XSLTProcessor` interface removes all parameters (`<xsl:param>`) and their values from the stylesheet imported in the processor. The `XSLTProcessor` will then use the default values specified in the XSLT stylesheet.

Syntax
------

```js
clearParameters()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-xsltprocessor-clearparameters |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `XSLTProcessor.getParameter()`
* `XSLTProcessor.setParameter()`
* `XSLTProcessor.removeParameter()`
* `XSLTProcessor.reset()`


Generating HTML - Web APIs

Generating HTML
===============

One common application of XSLT in the browser is transforming XML into HTML on the client. This example will transform the input document (example2.xml), which contains information about an article, into an HTML document.

The `<body>` element of the article now contains HTML elements (a `<b>` and `<u>` tag). The XML document contains both HTML elements and XML elements, but only one namespace is needed, namely for the XML elements. Since there is no HTML namespace, and using the XHTML namespace would force the XSL to create an XML document that would not behave like an HTML document, the `xsl:output` in the XSL Stylesheet will make sure the resulting document will be handled as HTML. For the XML elements, our own namespace is needed, `http://devedge.netscape.com/2002/de`, and it is given the prefix myNS `(xmlns:myNS="http://devedge.netscape.com/2002/de")`.

XML file
--------

```xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="example2.xsl"?>
  <myNS:Article xmlns:myNS="http://devedge.netscape.com/2002/de">
    <myNS:Title>My Article</myNS:Title>
    <myNS:Authors>
      <myNS:Author company="Foopy Corp.">Mr. Foo</myNS:Author>
      <myNS:Author>Mr. Bar</myNS:Author>
    </myNS:Authors>
    <myNS:Body>
      The <b>rain</b> in <u>Spain</u> stays mainly in the plains.
    </myNS:Body>
  </myNS:Article>
```

The XSL Stylesheet used will need to have two namespaces - one for the XSLT elements and one for our own XML elements used in the XML document. The output of the XSL Stylesheet is set to `HTML` by using the `xsl:output` element. By setting the output to be HTML and not having a namespace on the resulting elements (colored in blue), those elements will be treated as HTML elements.

XSL stylesheet with 2 namespaces
--------------------------------

```xml
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:myNS="http://devedge.netscape.com/2002/de">

  <xsl:output method="html"/>
  …
</xsl:stylesheet version="1.0">
```

A template matching the root node of the XML document is created and used to create the basic structure of the HTML page.

Creating the basic HTML document
--------------------------------

```xml
…
<xsl:template match="/">
<html>

  <head>

    <title>
      <xsl:value-of select="/myNS:Article/myNS:Title"/>
    </title>

    <style>
      .myBox {margin:10px 155px 0 50px; border: 1px dotted #639ACE; padding:0 5px 0 5px;}
    </style>

  </head>

  <body>
    <p class="myBox">
      <span class="title">
        <xsl:value-of select="/myNS:Article/myNS:Title"/>
      </span> </br>

      Authors:   <br />
        <xsl:apply-templates select="/myNS:Article/myNS:Authors/myNS:Author"/>
    </p>

    <p class="myBox">
      <xsl:apply-templates select="//myNS:Body"/>
    </p>

  </body>

</html>
</xsl:template>
…
```

Three more `xsl:template`'s are needed to complete the example. The first `xsl:template` is used for the author nodes, while the second one processes the body node. The third template has a general matching rule which will match any node and any attribute. It is needed in order to preserve the HTML elements in the XML document, since it matches all of them and copies them out into the HTML document the transformation creates.

Final 3 templates
-----------------

```xml
…
<xsl:template match="myNS:Author">
    --   <xsl:value-of select="." />

  <xsl:if test="@company">
    ::   <b>  <xsl:value-of select="@company" />  </b>
  </xsl:if>

  <br />
</xsl:template>
```

```xml
<xsl:template match="myNS:Body">
  <xsl:copy>
    <xsl:apply-templates select="@\*|node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="@\*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@\*|node()"/>
  </xsl:copy>
</xsl:template>
…
```

The final XSLT stylesheet looks as follows:

Final XSLT stylesheet
---------------------

```xml
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:myNS="http://devedge.netscape.com/2002/de">

  <xsl:output method="html" />

  <xsl:template match="/">
    <html>

      <head>

        <title>
          <xsl:value-of select="/myNS:Article/myNS:Title"/>
        </title>

        <style>
          .myBox {margin:10px 155px 0 50px; border: 1px dotted #639ACE; padding:0 5px 0 5px;}
        </style>

      </head>

      <body>
        <p class="myBox">
          <span class="title">
            <xsl:value-of select="/myNS:Article/myNS:Title"/>
          </span> <br />

          Authors:   <br />
            <xsl:apply-templates select="/myNS:Article/myNS:Authors/myNS:Author"/>
          </p>

        <p class="myBox">
          <xsl:apply-templates select="//myNS:Body"/>
        </p>

      </body>

    </html>
  </xsl:template>

  <xsl:template match="myNS:Author">
      --   <xsl:value-of select="." />

    <xsl:if test="@company">
      ::   <b>  <xsl:value-of select="@company" />  </b>
    </xsl:if>

    <br />
  </xsl:template>

  <xsl:template match="myNS:Body">
    <xsl:copy>
      <xsl:apply-templates select="@\*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="@\*|node()">
      <xsl:copy>
        <xsl:apply-templates select="@\*|node()"/>
      </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
```


XRSubImage: viewport property - Web APIs

XRSubImage: viewport property
=============================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The read-only **`viewport`** property of the `XRSubImage` interface represents the `XRViewport` that is used when rendering the sub image.

Value
-----

An `XRViewport`.

Specifications
--------------

| Specification |
| --- |
| WebXR Layers API Level 1 # dom-xrsubimage-viewport |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `XRViewport`


GPUCommandEncoder: beginComputePass() method - Web APIs

GPUCommandEncoder: beginComputePass() method
============================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`beginComputePass()`** method of the
 `GPUCommandEncoder` interface starts encoding a compute pass, returning a `GPUComputePassEncoder` that can be used to control computation.

Syntax
------

```js
beginComputePass()
beginComputePass(descriptor)
```

### Parameters

`descriptor` Optional

An object containing the following properties:

`label` Optional

A string providing a label that can be used to identify the object, for example in `GPUError` messages or console warnings.

`timestampWrites` Optional

An array of objects defining where and when timestamp query values will be written for this pass. These objects have the following properties:

* `location`: An enumerated value specifying when the timestamp will be executed. Available values are:
    + `"beginning"`: The timestamp is executed along with the other encoded commands in the compute pass once the corresponding `GPUCommandBuffer` is submitted.
    + `"end"`: The timestamp is executed as part of a separate list of timestamp attachments once the pass ends.
* `queryIndex`: A number specifying the index position in the `querySet` that the timestamp will be written to.
* `querySet`: The `GPUQuerySet` that the timestamp will be written to.

**Note:** To use timestamp queries, the `timestamp-query` feature must be enabled in the `GPUDevice`.

### Return value

A `GPUComputePassEncoder` object instance.

### Validation

The following criteria must be met when calling **`beginComputePass()`**, otherwise a `GPUValidationError` is generated and an invalid `GPUComputePassEncoder` is returned:

* The `timestamp-query` feature is enabled in the `GPUDevice`.
* No two `timestampWrites` objects have the same `location`. In effect, this means that you can only run two timestamp queries per render pass.
* For each timestamp query, the `querySet` `GPUQuerySet.type` is `"timestamp"`, and the `queryIndex` value is less than the `GPUQuerySet.count`.
Examples
--------

In our basic compute demo, several commands are recorded via a `GPUCommandEncoder`. Most of these commands originate from the `GPUComputePassEncoder` created via `beginComputePass()`.

```js
// ...

// Create GPUCommandEncoder to encode commands to issue to the GPU
const commandEncoder = device.createCommandEncoder();

// Initiate render pass
const passEncoder = commandEncoder.beginComputePass();

// Issue commands
passEncoder.setPipeline(computePipeline);
passEncoder.setBindGroup(0, bindGroup);
passEncoder.dispatchWorkgroups(Math.ceil(BUFFER\_SIZE / 64));

// End the render pass
passEncoder.end();

// Copy output buffer to staging buffer
commandEncoder.copyBufferToBuffer(
  output,
  0, // Source offset
  stagingBuffer,
  0, // Destination offset
  BUFFER\_SIZE,
);

// End frame by passing array of command buffers to command queue for execution
device.queue.submit([commandEncoder.finish()]);

// ...
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # dom-gpucommandencoder-begincomputepass |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API


GPUCommandEncoder: popDebugGroup() method - Web APIs

GPUCommandEncoder: popDebugGroup() method
=========================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`popDebugGroup()`** method of the
 `GPUCommandEncoder` interface ends a debug group, which is begun with a `pushDebugGroup()` call.

This could be used for telemetry, or may be utilized in `GPUError` messages, browser dev tools, or other services in the future to help with debugging.

Syntax
------

```js
popDebugGroup()
```

### Parameters

None.

### Return value

None (`Undefined`).

### Validation

The following criteria must be met when calling **`popDebugGroup()`**, otherwise a `GPUValidationError` is generated and the `GPUCommandEncoder` becomes invalid:

* The command encoder's debug stack is not empty (i.e. at least one debug group was previously started with `pushDebugGroup()`).
Examples
--------

```js
// ...

commandEncoder.pushDebugGroup("mygroupmarker"); // Start labeled debug group

const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);

passEncoder.end();

commandEncoder.popDebugGroup(); // End labeled debug group

// ...
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # dom-gpudebugcommandsmixin-popdebuggroup |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API


GPUCommandEncoder: copyBufferToTexture() method - Web APIs

GPUCommandEncoder: copyBufferToTexture() method
===============================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`copyBufferToTexture()`** method of the
 `GPUCommandEncoder` interface encodes a command that copies data from a `GPUBuffer` to a `GPUTexture`.

Syntax
------

```js
copyBufferToTexture(source, destination, copySize)
```

### Parameters

`source`

An object that defines the buffer to copy from, plus the layout of the data in the buffer to be copied to the texture. Combined with `copySize`, it defines the region of the source buffer. `source` can take the following properties:

`buffer`

The `GPUBuffer` to copy from.

`offset` Optional

The offset, in bytes, from the beginning of `data` to the start of the image data to be copied. If omitted, `offset` defaults to 0.

`bytesPerRow` Optional

A number representing the stride, in bytes, between the start of each block row (i.e. a row of complete texel blocks) and the subsequent block row. This is required if there are multiple block rows (i.e. the copy height or depth is more than one block).

`rowsPerImage` Optional

The number of block rows per single image inside the data. `bytesPerRow` × `rowsPerImage` will give you the stride, in bytes, between the start of each complete image. This is required if there are multiple images to copy.

`destination`

An object defining the texture to write the data to. Combined with `copySize`, defines the region of the destination texture subresource. `destination` can take the following properties:

`aspect` Optional

An enumerated value defining which aspects of the texture to write the data to. Possible values are:

`"all"`

All available aspects of the texture format will be written to, which can mean all or any of color, depth, and stencil, depending on what kind of format you are dealing with.

`"depth-only"`

Only the depth aspect of a depth-or-stencil format will be written to.

`"stencil-only"`

Only the stencil aspect of a depth-or-stencil format will be written to.

If omitted, `aspect` takes a value of `"all"`.

`mipLevel` Optional

A number representing the mip-map level of the texture to write the data to. If omitted, `mipLevel` defaults to 0.

`origin` Optional

An object or array specifying the origin of the copy — the minimum corner of the texture region to write the data to. Together with `size`, this defines the full extent of the region to copy to. The `x`, `y`, and `z` values default to 0 if any of all of `origin` is omitted.

What follows is a sample array:

```js
[0, 0, 0];
```

The object equivalent would look like this:

```js
{
  x: 0,
  y: 0,
  z: 0
}
```

`texture`

A `GPUTexture` object representing the texture to write the data to.

`copySize`

An object or array specifying the width, height, and depth/array layer count of the copied data. The width value must always be specified, while the height and depth/array layer count values are optional and will default to 1 if omitted.

What follows is a sample `copySize` array:

```js
[16, 16, 2];
```

The object equivalent would look like this:

```js
{
  width: 16,
  height: 16,
  depthOrArrayLayers: 2
}
```

### Return value

None (`Undefined`).

### Validation

The following criteria must be met when calling **`copyBufferToTexture()`**, otherwise a `GPUValidationError` is generated and the `GPUCommandEncoder` becomes invalid.

For the `source`:

* `source.bytesPerRow` is a multiple of 256.
* The `source.buffer`'s `GPUBuffer.usage` includes the `GPUBufferUsage.COPY_SRC` flag.

For the `destination`:

* `mipLevel` is less than the `GPUTexture.mipLevelCount`.
* `origin.x` is a multiple of the texel block width of the `GPUTexture.format`.
* `origin.y` is a multiple of the texel block height of the `GPUTexture.format`.
* If the `GPUTexture.format` is a depth-or-stencil format or `GPUTexture.sampleCount` is more than 1, the subresource size is equal to `size`.
* The `destination`'s `GPUTexture.usage` includes the `GPUTextureUsage.COPY_DST` flag.
* The `destination`'s `GPUTexture.sampleCount` is 1.
* `destination.aspect` refers to a single aspect of the `GPUTexture.format`.
* That aspect is a valid image copy destination according to depth-or-stencil formats.
* The `destination` is compatible with the `copySize`.
Examples
--------

```js
commandEncoder.copyBufferToTexture(
  {
    buffer: sourceBuffer,
  },
  {
    texture: destinationTexture,
  },
  {
    width: 16,
    height: 16,
    depthOrArrayLayers: 2,
  },
);
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # dom-gpucommandencoder-copybuffertotexture |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API


GPUCommandEncoder: copyBufferToBuffer() method - Web APIs

GPUCommandEncoder: copyBufferToBuffer() method
==============================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`copyBufferToBuffer()`** method of the
 `GPUCommandEncoder` interface encodes a command that copies data from one `GPUBuffer` to another.

Syntax
------

```js
copyBufferToBuffer(source, sourceOffset, destination, destinationOffset, size)
```

### Parameters

`source`

The `GPUBuffer` to copy from.

`sourceOffset`

The offset, in bytes, into the `source` to begin copying from.

`destination`

The `GPUBuffer` to copy to.

`destinationOffset`

The offset, in bytes, into the `destination` to begin copying to.

`size`

The number of bytes to copy.

### Return value

None (`Undefined`).

### Validation

The following criteria must be met when calling **`copyBufferToBuffer()`**, otherwise a `GPUValidationError` is generated and the `GPUCommandEncoder` becomes invalid:

* The `source`'s `GPUBuffer.usage` includes the `GPUBufferUsage.COPY_SRC` flag.
* The `destination`'s `GPUBuffer.usage` includes the `GPUBufferUsage.COPY_DST` flag.
* `size`, `sourceOffset`, and `destinationOffset` are all multiples of 4.
* The `source`'s `GPUBuffer.size` is greater than or equal to `sourceOffset` + `size`.
* The `destination`'s `GPUBuffer.size` is greater than or equal to `destinationOffset` + `size`.
* `source` and `destination` are different `GPUBuffer`s (you can't copy from and to the same buffer).
Examples
--------

In our basic compute demo, we use `copyBufferToBuffer()` to copy the contents of our `output` buffer to the `stagingBuffer`.

```js
// ...

// Create an output buffer to read GPU calculations to, and a staging buffer to be mapped for JavaScript access

const output = device.createBuffer({
  size: BUFFER\_SIZE,
  usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY\_SRC,
});

const stagingBuffer = device.createBuffer({
  size: BUFFER\_SIZE,
  usage: GPUBufferUsage.MAP\_READ | GPUBufferUsage.COPY\_DST,
});

// ...

// Create GPUCommandEncoder to encode commands to issue to the GPU
const commandEncoder = device.createCommandEncoder();

// ...

// Copy output buffer to staging buffer
commandEncoder.copyBufferToBuffer(
  output,
  0, // Source offset
  stagingBuffer,
  0, // Destination offset
  BUFFER\_SIZE,
);

// ...
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # dom-gpucommandencoder-copybuffertobuffer |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API


GPUCommandEncoder: beginRenderPass() method - Web APIs

GPUCommandEncoder: beginRenderPass() method
===========================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`beginRenderPass()`** method of the
 `GPUCommandEncoder` interface starts encoding a render pass, returning a `GPURenderPassEncoder` that can be used to control rendering.

Syntax
------

```js
beginRenderPass(descriptor)
```

### Parameters

`descriptor`

An object containing the following properties:

`colorAttachments`

An array of objects (see Color attachment object structure) defining the color attachments that will be output to when executing this render pass.

`depthStencilAttachment` Optional

An object (see Depth/stencil attachment object structure) defining the depth/stencil attachment that will be output to and tested against when executing this render pass.

`label` Optional

A string providing a label that can be used to identify the object, for example in `GPUError` messages or console warnings.

`maxDrawCount` Optional

A number indicating the maximum number of draw calls that will be done in the render pass. This is used by some implementations to size work injected before the render pass. You should keep the default value — 50000000 — unless you know that more draw calls will be done.

`occlusionQuerySet` Optional

The `GPUQuerySet` that will store the occlusion query results for this pass.

`timestampWrites` Optional

An array of objects defining where and when timestamp query values will be written for this pass. These objects have the following properties:

* `location`: An enumerated value specifying when the timestamp will be executed. Available values are:
    + `"beginning"`: The timestamp is executed along with the other encoded commands in the compute pass once the corresponding `GPUCommandBuffer` is submitted.
    + `"end"`: The timestamp is executed as part of a separate list of timestamp attachments once the pass ends.
* `queryIndex`: A number specifying the index position in the `querySet` that the timestamp will be written to.
* `querySet`: The `GPUQuerySet` that the timestamp will be written to.

**Note:** To use timestamp queries, the `timestamp-query` feature must be enabled in the `GPUDevice`.

### Color attachment object structure

Color attachment objects can have the following properties:

`clearValue` Optional

A color value to clear the `view` texture to, prior to executing the render pass. This value is ignored if `loadOp` is not set to `"clear"`. `clearValue` takes an array or object representing the four color components `r`, `g`, `b`, and `a` as decimals.

What follows is a sample array:

```js
clearValue: [0.0, 0.5, 1.0, 1.0];
```

The object equivalent would look like this:

```js
clearValue: {
  r: 0.0,
  g: 0.5,
  b: 1.0,
  a: 1.0
}
```

If `clearValue` is omitted, it defaults to `{r: 0, g: 0, b: 0, a: 0}`.

`loadOp`

An enumerated value indicating the load operation to perform on `view` prior to executing the render pass. Possible values are:

* `"clear"`: Loads the `clearValue` for this attachment into the render pass.
* `"load"`: Loads the existing value for this attachment into the render pass.

**Note:** It is recommended to always use `"clear"` in cases where the initial value doesn't matter, as it will give better performance on some devices such as mobiles.

`storeOp`

An enumerated value indicating the store operation to perform on `view` after executing the render pass. Possible values are:

* `"discard"`: Discards the resulting value of the render pass for this attachment.
* `"store"`: Stores the resulting value of the render pass for this attachment.

`resolveTarget` Optional

A `GPUTextureView` object representing the texture subresource that will receive the resolved output for this color attachment if `view` is multisampled.

`view`

A `GPUTextureView` object representing the texture subresource that will be output to for this color attachment.

**Note:** Each color or depth/stencil attachment must be a unique texture subresource, and texture subresources used as attachments cannot be used inside the render pass.

### Depth/stencil attachment object structure

The `depthStencilAttachment` object can have the following properties:

`depthClearValue` Optional

A number indicating the value to clear `view`'s depth component prior to executing the render pass. This is ignored if `depthLoadOp` is not set to `"clear"`.

The value must be between 0.0 and 1.0, inclusive.

`depthLoadOp` Optional

An enumerated value indicating the load operation to perform on `view`'s depth component prior to executing the render pass. Possible values are:

* `"clear"`: Loads the `clearValue` for this attachment into the render pass.
* `"load"`: Loads the existing value for this attachment into the render pass.

**Note:** It is recommended to always use `"clear"` in cases where the initial value doesn't matter, as it will give better performance on some devices such as mobiles.

`depthReadOnly` Optional

A boolean. Setting the value to `true` causes the depth component of `view` to be read-only. If `depthReadOnly` is omitted, it defaults to `false`.

`depthStoreOp` Optional

An enumerated value indicating the store operation to perform on `view`'s depth component after executing the render pass. Possible values are:

* `"discard"`: Discards the resulting value of the render pass for this attachment.
* `"store"`: Stores the resulting value of the render pass for this attachment.

`stencilClearValue` Optional

A number indicating the value to clear `view`'s stencil component to prior to executing the render pass. This is ignored if `stencilLoadOp` is not set to `"clear"`.

If `stencilClearValue` is omitted, it defaults to 0.

`stencilLoadOp` Optional

An enumerated value indicating the load operation to perform on `view`'s stencil component prior to executing the render pass. Possible values are:

* `"clear"`: Loads the `clearValue` for this attachment into the render pass.
* `"load"`: Loads the existing value for this attachment into the render pass.

**Note:** It is recommended to always use `"clear"` in cases where the initial value doesn't matter, as it will give better performance on some devices such as mobiles.

`stencilReadOnly` Optional

A boolean. Setting the value to `true` causes the stencil component of `view` to be read-only. If `stencilReadOnly` is omitted, it defaults to `false`.

`stencilStoreOp` Optional

An enumerated value indicating the store operation to perform on `view`'s stencil component after executing the render pass. Possible values are:

* `"discard"`: Discards the resulting value of the render pass for this attachment.
* `"store"`: Stores the resulting value of the render pass for this attachment.

`view`

A `GPUTextureView` object representing the texture subresource that will be output to and read from for this depth/stencil attachment.

### Return value

A `GPURenderPassEncoder` object instance.

### Validation

The following criteria must be met when calling **`beginRenderPass()`**, otherwise a `GPUValidationError` is generated and an invalid `GPURenderPassEncoder` is returned.

General:

* `colorAttachments.length` is less than or equal to the `GPUDevice`'s `maxColorAttachments` limit.
* If `colorAttachments` contains only `null` values, `depthStencilAttachment` is provided.
* All `view`s in `colorAttachments` and `depthStencilAttachment` have equal `GPUTexture.sampleCount` values and render extents (`GPUTexture.height`, `GPUTexture.width`, and `GPUTexture.depthOrArrayLayers`).
* If `occlusionQuerySet` is set, the referenced `GPUQuerySet` has a `type` of `"occlusion"`.

For color attachment objects

* The `view` is renderable, and the `view`'s format (i.e. specified in the descriptor of the originating `GPUTexture.createView()` call) is a color renderable format.
* If `resolveTarget` is provided:
    + The `view`'s originating `GPUTexture`'s `sampleCount` is greater than 1.
    + The `resolveTarget`'s originating `GPUTexture`'s `sampleCount` is 1.
    + `resolveTarget` is renderable.
    + The sizes of the subresources that `view` and `resolveTarget` provide a view of match.
    + `view`'s and `resolveTarget`'s formats match.
* Color attachments bytes per sample is less than or equal to the `GPUDevice`'s `maxColorAttachmentBytesPerSample` limit.

For depth/stencil attachment objects:

* The `view` is renderable, and its format is a depth-or-stencil format.
* If `depthLoadOp` is set to `"clear"`, a valid `depthClearValue` is provided.
* If `view`'s format is a combined depth-or-stencil format, `depthReadOnly` matches `stencilReadOnly`.
* If `view`'s format has a depth aspect, and `depthReadOnly` is `false`, `depthLoadOp` and `depthStoreOp` are provided.
* If `view`'s format has a depth aspect, and `depthReadOnly` is `true`, `depthLoadOp` and `depthStoreOp` are not provided.
* If `view`'s format has a stencil aspect, and `stencilReadOnly` is `false`, `stencilLoadOp` and `stencilStoreOp` are provided.
* If `view`'s format has a stencil aspect, and `stencilReadOnly` is `true`, `stencilLoadOp` and `stencilStoreOp` are not provided.

For timestamp queries:

* The `timestamp-query` feature is enabled in the `GPUDevice`.
* No two `timestampWrites` objects have the same `location`. In effect, this means that you can only run two timestamp queries per render pass.
* For each timestamp query, the `querySet` `GPUQuerySet.type` is `"timestamp"`, and the `queryIndex` value is less than the `GPUQuerySet.count`.
* No two `timestampWrites` objects have the same `queryIndex` and `querySet` pair.
Examples
--------

In our basic render demo, a number of commands are recorded via a `GPUCommandEncoder`. These commands originate from the `GPURenderPassEncoder` created via `beginRenderPass()` :

```js
// ...

// Create GPUCommandEncoder
const commandEncoder = device.createCommandEncoder();

// Create GPURenderPassDescriptor to tell WebGPU which texture to draw into, then initiate render pass

const renderPassDescriptor = {
  colorAttachments: [
    {
      clearValue: clearColor,
      loadOp: "clear",
      storeOp: "store",
      view: context.getCurrentTexture().createView(),
    },
  ],
};

const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

// Draw a triangle

passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);

// End the render pass

passEncoder.end();

device.queue.submit([commandEncoder.finish()]);

// ...
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # dom-gpucommandencoder-beginrenderpass |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API


GPUCommandEncoder: copyTextureToTexture() method - Web APIs

GPUCommandEncoder: copyTextureToTexture() method
================================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`copyTextureToTexture()`** method of the
 `GPUCommandEncoder` interface encodes a command that copies data from one `GPUTexture` to another.

Syntax
------

```js
copyTextureToTexture(source, destination, copySize)
```

### Parameters

`source`

An object (see Copy texture object structure) defining the texture to copy the data from. Combined with `copySize`, this defines the region of the source texture subresource.

`destination`

An object (see Copy texture object structure) defining the texture to write the data to. Combined with `copySize`, this defines the region of the destination texture subresource.

`copySize`

An object or array specifying the width, height, and depth/array layer count of the copied data. The width value must always be specified, while the height and depth/array layer count values are optional and will default to 1 if omitted.

What follows is a sample `copySize` array:

```js
[16, 16, 2];
```

The object equivalent would look like this:

```js
{
  width: 16,
  height: 16,
  depthOrArrayLayers: 2
}
```

### Copy texture object structure

A copy texture object has the following structure:

`aspect` Optional

An enumerated value defining which aspects of the texture to copy the data from/to. Possible values are:

`"all"`

All available aspects of the texture format will be copied from/to, which can mean all or any of color, depth, and stencil, depending on what kind of format you are dealing with.

`"depth-only"`

Only the depth aspect of a depth-or-stencil format will be copied from/to.

`"stencil-only"`

Only the stencil aspect of a depth-or-stencil format will be copied from/to.

If omitted, `aspect` takes a value of `"all"`.

`mipLevel` Optional

A number representing the mip-map level of the texture to copy the data from/to. If omitted, `mipLevel` defaults to 0.

`origin` Optional

An object or array specifying the origin of the copy/destination — the minimum corner of the texture region to copy the data from/to. Together with `size`, this defines the full extent of the region to copy from/to. The `x`, `y`, and `z` values default to 0 if any of all of `origin` is omitted.

What follows is a sample array:

```js
[0, 0, 0];
```

The object equivalent would look like this:

```js
{
  x: 0,
  y: 0,
  z: 0
}
```

`texture`

A `GPUTexture` object representing the texture to copy the data from/to.

### Return value

None (`Undefined`).

### Validation

The following criteria must be met when calling **`copyTextureToTexture()`**, otherwise a `GPUValidationError` is generated and the `GPUCommandEncoder` becomes invalid.

For the `source`:

* The `source`'s `GPUTexture.usage` includes the `GPUTextureUsage.COPY_SRC` flag.

For the `destination`:

* The `source`'s `GPUTexture.usage` includes the `GPUTextureUsage.COPY_DST` flag.

For `source` and `destination`:

* `mipLevel` is less than the `GPUTexture.mipLevelCount`.
* `origin.x` is a multiple of the texel block width of the `GPUTexture.format`.
* `origin.y` is a multiple of the texel block height of the `GPUTexture.format`.
* The source and destination `texture` `GPUTexture.format`s are copy-compatible.
* The source and destination `texture` `GPUTexture.sampleCount`s are equal.
* If the `GPUTexture.format` is a depth-or-stencil format or `GPUTexture.sampleCount` is more than 1, the subresource size is equal to `size`.
* The `texture`'s `GPUTexture.sampleCount` is 1.
* `aspect` refers to a single aspect of the `GPUTexture.format`.
* That aspect is a valid image copy source/destination according to depth-or-stencil formats.
* The `texture` is compatible with the `copySize`.
Examples
--------

```js
commandEncoder.copyTextureToTexture(
  {
    texture: sourceTexture,
  },
  {
    texture: destinationTexture,
  },
  {
    width: 16,
    height: 16,
    depthOrArrayLayers: 2,
  },
);
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # dom-gpucommandencoder-copytexturetotexture |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API


GPUCommandEncoder: finish() method - Web APIs

GPUCommandEncoder: finish() method
==================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`finish()`** method of the
 `GPUCommandEncoder` interface completes recording of the command sequence encoded on this `GPUCommandEncoder`, returning a corresponding `GPUCommandBuffer`.

Syntax
------

```js
finish()
finish(descriptor)
```

### Parameters

`descriptor` Optional

An object that can contain the following properties:

`label` Optional

A string providing a label for the returned `GPUCommandBuffer` that can be used to identify it, for example in `GPUError` messages or console warnings.

### Return value

A `GPUCommandBuffer` object instance.

### Validation

The following criteria must be met when calling **`finish()`**, otherwise a `GPUValidationError` is generated and the `GPUCommandEncoder` becomes invalid:

* There are no active debug groups (i.e. started via `pushDebugGroup()`).
* The `GPUCommandEncoder` is in an open state — this means that:
    + There are no child `GPUComputePassEncoder` or `GPURenderPassEncoder`s active that have not been `end()`ed.
    + The `GPUCommandEncoder` has not already had `finish()` called on it (in which case it cannot be used to encode any more commands).
Examples
--------

```js
// ...

const commandBuffer = commandEncoder.finish();
device.queue.submit([commandBuffer]);

// ...
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # dom-gpucommandencoder-finish |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API


GPUCommandEncoder: pushDebugGroup() method - Web APIs

GPUCommandEncoder: pushDebugGroup() method
==========================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`pushDebugGroup()`** method of the
 `GPUCommandEncoder` interface begins a debug group, which is marked with a specified label, and will contain all subsequent encoded commands up until a `popDebugGroup()` method is invoked.

This could be used for telemetry, or may be utilized in `GPUError` messages, browser dev tools, or other services in the future to help with debugging.

Syntax
------

```js
pushDebugGroup(groupLabel)
```

### Parameters

`groupLabel`

A string representing the label for the debug group.

### Return value

None (`Undefined`).

Examples
--------

```js
// ...

commandEncoder.pushDebugGroup("mygroupmarker"); // Start labeled debug group

const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);

passEncoder.end();

commandEncoder.popDebugGroup(); // End labeled debug group

// ...
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # dom-gpudebugcommandsmixin-pushdebuggroup |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API


GPUCommandEncoder: copyTextureToBuffer() method - Web APIs

GPUCommandEncoder: copyTextureToBuffer() method
===============================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`copyTextureToBuffer()`** method of the
 `GPUCommandEncoder` interface encodes a command that copies data from a `GPUTexture` to a `GPUBuffer`.

Syntax
------

```js
copyTextureToBuffer(source, destination, copySize)
```

### Parameters

`source`

An object defining the texture to copy the data from. Combined with `copySize`, defines the region of the source texture subresource. `source` can take the following properties:

`aspect` Optional

An enumerated value defining which aspects of the texture to copy the data from. Possible values are:

`"all"`

All available aspects of the texture format will be copied from, which can mean all or any of color, depth, and stencil, depending on what kind of format you are dealing with.

`"depth-only"`

Only the depth aspect of a depth-or-stencil format will be copied from.

`"stencil-only"`

Only the stencil aspect of a depth-or-stencil format will be copied from.

If omitted, `aspect` takes a value of `"all"`.

`mipLevel` Optional

A number representing the mip-map level of the texture to copy the data from. If omitted, `mipLevel` defaults to 0.

`origin` Optional

An object or array specifying the origin of the copy — the minimum corner of the texture region to copy the data from. Together with `size`, this defines the full extent of the region to copy from. The `x`, `y`, and `z` values default to 0 if any of all of `origin` is omitted.

What follows is a sample array:

```js
[0, 0, 0];
```

The object equivalent would look like this:

```js
{
  x: 0,
  y: 0,
  z: 0
}
```

`texture`

A `GPUTexture` object representing the texture to copy the data from.

`destination`

An object that defines the buffer to write to, plus the layout of the data to write to the buffer. Combined with `copySize`, it defines the region of the destination buffer. `source` can take the following properties:

`buffer`

The `GPUBuffer` to write to.

`offset` Optional

The offset, in bytes, from the beginning of `data` to the start position to write the copied data to. If omitted, `offset` defaults to 0.

`bytesPerRow` Optional

A number representing the stride, in bytes, between the start of each block row (i.e. a row of complete texel blocks) and the subsequent block row. This is required if there are multiple block rows (i.e. the copy height or depth is more than one block).

`rowsPerImage` Optional

The number of block rows per single image inside the data. `bytesPerRow` × `rowsPerImage` will give you the stride, in bytes, between the start of each complete image. This is required if there are multiple images to copy.

`copySize`

An object or array specifying the width, height, and depth/array layer count of the copied data. The width value must always be specified, while the height and depth/array layer count values are optional and will default to 1 if omitted.

What follows is a sample `copySize` array:

```js
[16, 16, 2];
```

The object equivalent would look like this:

```js
{
  width: 16,
  height: 16,
  depthOrArrayLayers: 2
}
```

### Return value

None (`Undefined`).

### Validation

The following criteria must be met when calling **`copyTextureToBuffer()`**, otherwise a `GPUValidationError` is generated and the `GPUCommandEncoder` becomes invalid.

For the `source`:

* `mipLevel` is less than the `GPUTexture.mipLevelCount`.
* `origin.x` is a multiple of the texel block width of the `GPUTexture.format`.
* `origin.y` is a multiple of the texel block height of the `GPUTexture.format`.
* If the `GPUTexture.format` is a depth-or-stencil format or `GPUTexture.sampleCount` is more than 1, the subresource size is equal to `size`.
* The `source`'s `GPUTexture.usage` includes the `GPUTextureUsage.COPY_SRC` flag.
* The `source`'s `GPUTexture.sampleCount` is 1.
* `source.aspect` refers to a single aspect of the `GPUTexture.format`.
* That aspect is a valid image copy source according to depth-or-stencil formats.
* The `source` is compatible with the `copySize`.

For the `destination`:

* `destination.bytesPerRow` is a multiple of 256.
* The `destination.buffer`'s `GPUBuffer.usage` includes the `GPUBufferUsage.COPY_DST` flag.
Examples
--------

```js
commandEncoder.copyTextureToBuffer(
  {
    texture: sourceTexture,
  },
  {
    buffer: destinationBuffer,
  },
  {
    width: 16,
    height: 16,
    depthOrArrayLayers: 2,
  },
);
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # dom-gpucommandencoder-copytexturetobuffer |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API


GPUCommandEncoder: insertDebugMarker() method - Web APIs

GPUCommandEncoder: insertDebugMarker() method
=============================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`insertDebugMarker()`** method of the
 `GPUCommandEncoder` interface marks a specific point in a series of encoded commands with a label.

This could be used for telemetry, or may be utilized in `GPUError` messages, browser dev tools, or other services in the future to help with debugging.

Syntax
------

```js
insertDebugMarker(markerLabel)
```

### Parameters

`markerLabel`

A string representing the label to insert.

### Return value

None (`Undefined`).

Examples
--------

```js
// ...

commandEncoder.insertDebugMarker("mymarker");

// ...
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # dom-gpudebugcommandsmixin-insertdebugmarker |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API


GPUCommandEncoder: writeTimestamp() method - Web APIs

GPUCommandEncoder: writeTimestamp() method
==========================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`writeTimestamp()`** method of the
 `GPUCommandEncoder` interface encodes a command that writes a timestamp into a `GPUQuerySet` once the previous commands recorded into the same queued `GPUCommandBuffer` have been executed by the GPU.

**Note:** To use timestamp queries, the `timestamp-query` feature must be enabled in the `GPUDevice`.

Syntax
------

```js
writeTimestamp(querySet, queryIndex)
```

### Parameters

`querySet`

A `GPUQuerySet` object representing the query set that will store the timestamp values.

`queryIndex`

A number representing the index of the query in the query set.

### Return value

None (`Undefined`).

### Validation

The following criteria must be met when calling **`writeTimestamp()`**, otherwise a `GPUValidationError` is generated and the `GPUCommandEncoder` becomes invalid:

* The `timestamp-query` feature is enabled in the `GPUDevice`.
* The `querySet` `GPUQuerySet.type` is `"timestamp"`
* The `queryIndex` value is less than the `GPUQuerySet.count`.
Examples
--------

```js
// ...

const querySet = device.createQuerySet({
  type: "timestamp",
  count: 32,
});

// ...

commandEncoder.writeTimestamp(querySet, 0);

// ...
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # dom-gpucommandencoder-writetimestamp |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API


GPUCommandEncoder: label property - Web APIs

GPUCommandEncoder: label property
=================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`label`** read-only property of the
 `GPUCommandEncoder` interface is a string providing a label that can be used to identify the object, for example in `GPUError` messages or console warnings.

This can be set by providing a `label` property in the descriptor object passed into the originating `GPUDevice.createCommandEncoder()` call, or you can get and set it directly on the `GPUCommandEncoder` object.

Value
-----

A string. If no label value has previously been set, getting the label returns an empty string.

Examples
--------

Setting and getting a label via `GPUCommandEncoder.label`:

```js
const commandEncoder = device.createCommandEncoder();
commandEncoder.label = "mycommandencoder";
console.log(commandEncoder.label); // "mycommandencoder";
```

Setting a label via the originating `GPUDevice.createCommandEncoder()` call, and then getting it via `GPUCommandEncoder.label`:

```js
const commandEncoder = device.createCommandEncoder({
  label: "mycommandencoder",
});

console.log(commandEncoder.label); // "mycommandencoder";
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # dom-gpuobjectbase-label |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API


GPUCommandEncoder: clearBuffer() method - Web APIs

GPUCommandEncoder: clearBuffer() method
=======================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`clearBuffer()`** method of the
 `GPUCommandEncoder` interface encodes a command that fills a region of a `GPUBuffer` with zeroes.

Syntax
------

```js
clearBuffer(buffer)
clearBuffer(buffer, offset)
clearBuffer(buffer, offset, size)
```

### Parameters

`buffer`

A `GPUBuffer` object representing the buffer to clear.

`offset` Optional

A number representing the offset, in bytes, from the start of the `buffer` to the sub-region to clear. If omitted, `offset` defaults to 0.

`size` Optional

A number representing the size, in bytes, of the sub-region to clear. If omitted, `size` defaults to the `buffer` size - `offset`.

### Return value

None (`Undefined`).

### Validation

The following criteria must be met when calling **`clearBuffer()`**, otherwise a `GPUValidationError` is generated and the `GPUCommandEncoder` becomes invalid:

* The `buffer`'s `GPUBuffer.usage` includes the `GPUBufferUsage.COPY_DST` flag.
* `offset` and `size` are both multiples of 4.
* The `buffer`'s `GPUBuffer.size` is greater than or equal to `offset` + `size`.
Examples
--------

```js
// ...

const buffer = device.createBuffer({
  size: 1000,
  usage: GPUBufferUsage.MAP\_READ | GPUBufferUsage.COPY\_DST,
});

// Later on

const commandBuffer = device.createCommandEncoder();
commandEncoder.clearBuffer(buffer);

// ...
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # dom-gpucommandencoder-clearbuffer |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API


GPUCommandEncoder: resolveQuerySet() method - Web APIs

GPUCommandEncoder: resolveQuerySet() method
===========================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`resolveQuerySet()`** method of the
 `GPUCommandEncoder` interface encodes a command that resolves a `GPUQuerySet`, copying the results into a specified `GPUBuffer`.

Syntax
------

```js
resolveQuerySet(querySet, firstQuery, queryCount, destination, destinationOffset)
```

### Parameters

`querySet`

A `GPUQuerySet` object representing the query set to be resolved.

`firstQuery`

The index number of the first query value to be copied over to the buffer.

`queryCount`

The number of queries to be copied over to the buffer, starting from `firstQuery`.

`destination`

A `GPUBuffer` representing the buffer to copy the query values to.

`destinationOffset`

A number representing the offset, in bytes, from the start of the buffer to start writing the query values at.

### Return value

None (`Undefined`).

### Validation

The following criteria must be met when calling **`resolveQuerySet()`**, otherwise a `GPUValidationError` is generated and the `GPUCommandEncoder` becomes invalid:

* The `destination.buffer`'s `GPUBuffer.usage` includes the `GPUBufferUsage.QUERY_RESOLVE` flag.
* `firstQuery` is smaller than the number of queries in `querySet`.
* `firstQuery` + `queryCount` is smaller than or equal to the number of queries in `querySet`.
* `destinationOffset` is a multiple of 256.
* `destinationOffset` + 8 × `queryCount` is less than or equal to `destination.size`.
Examples
--------

```js
// ...

const queryBuffer = device.createBuffer({
  size: 1024,
  usage: GPUBufferUsage.QUERY\_RESOLVE,
});

const querySet = device.createQuerySet({
  type: "timestamp",
  count: 32,
});

// ...

const commandEncoder = device.createCommandEncoder();

// Write timestamps to querySet
commandEncoder.writeTimestamp(querySet, 0);
// ...
commandEncoder.writeTimestamp(querySet, 1);
// etc.

// ...

commandEncoder.resolveQuerySet(
  querySet,
  0, // First query to write
  16, // Number of queries to count
  queryBuffer,
  0, // Buffer offset
);

// ...
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # dom-gpucommandencoder-resolvequeryset |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API


CacheStorage: delete() method - Web APIs

CacheStorage: delete() method
=============================

 The **`delete()`** method of the `CacheStorage` interface finds the `Cache` object matching the `cacheName`, and if found, deletes the `Cache` object and returns a `Promise` that resolves to `true`.
 If no `Cache` object is found, it resolves to `false`.

You can access `CacheStorage` through the global `caches` property.

Syntax
------

```js
delete(cacheName)
```

### Parameters

`cacheName`

The name of the cache you want to delete.

### Return value

 a `Promise` that resolves to `true` if the `Cache`
 object is found and deleted, and `false` otherwise.

Examples
--------

 In this code snippet we wait for an activate event, and then run a
 `waitUntil()` block that clears up any old,
 unused caches before a new service worker is activated. Here we have an array of cache
 names we want to keep (`cachesToKeep`). We return the keys of the caches in
 the `CacheStorage` object using `CacheStorage.keys`, then
 check each key to see if it is in the array. If not, we delete it using
 `delete()`.

```js
this.addEventListener("activate", (event) => {
  const cachesToKeep = ["v2"];

  event.waitUntil(
    caches.keys().then((keyList) =>
      Promise.all(
        keyList.map((key) => {
          if (!cachesToKeep.includes(key)) {
            return caches.delete(key);
          }
        }),
      ),
    ),
  );
});
```

Specifications
--------------

| Specification |
| --- |
| Service Workers # cache-storage-delete |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using Service Workers
* `Cache`
* `caches`


CacheStorage: open() method - Web APIs

CacheStorage: open() method
===========================

 The **`open()`** method of the
 `CacheStorage` interface returns a `Promise` that resolves to
 the `Cache` object matching the `cacheName`.

 You can access `CacheStorage` through the global
 `caches` property.

**Note:** If the specified `Cache` does not exist, a new
 cache is created with that `cacheName` and a `Promise` that
 resolves to this new `Cache` object is returned.

Syntax
------

```js
open(cacheName)
```

### Parameters

`cacheName`

The name of the cache you want to open.

### Return value

A `Promise` that resolves to the requested `Cache` object.

Examples
--------

 This example is from the MDN simple service worker example (see simple service worker running live).
 Here we wait for an `InstallEvent` to fire, then runs
 `waitUntil()` to handle the install process for
 the app. This consists of calling `CacheStorage.open()` to create a new
 cache, then using `Cache.addAll()` to add a series of assets to it.

```js
self.addEventListener("install", (event) => {
  event.waitUntil(
    caches
      .open("v1")
      .then((cache) =>
        cache.addAll([
          "/",
          "/index.html",
          "/style.css",
          "/app.js",
          "/image-list.js",
          "/star-wars-logo.jpg",
          "/gallery/bountyHunters.jpg",
          "/gallery/myLittleVader.jpg",
          "/gallery/snowTroopers.jpg",
        ]),
      ),
  );
});
```

Specifications
--------------

| Specification |
| --- |
| Service Workers # cache-storage-open |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using Service Workers
* `Cache`
* `caches`


CacheStorage: has() method - Web APIs

CacheStorage: has() method
==========================

 The **`has()`** method of the `CacheStorage`
 interface returns a `Promise` that resolves to `true` if a
 `Cache` object matches the `cacheName`.

You can access `CacheStorage` through the global `caches` property.

Syntax
------

```js
has(cacheName)
```

### Parameters

`cacheName`

A string representing the name of the `Cache` object you are looking for in the `CacheStorage`.

### Return value

 a `Promise` that resolves to `true` if the cache exists or
 `false` if not.

Examples
--------

 The following example first checks whether a cache called 'v1' exists. If so, we add a
 list of assets to it. If not then we run some kind of cache set-up function.

```js
caches
  .has("v1")
  .then((hasCache) => {
    if (!hasCache) {
      someCacheSetupFunction();
    } else {
      caches.open("v1").then((cache) => cache.addAll(myAssets));
    }
  })
  .catch(() => {
    // Handle exception here.
  });
```

Specifications
--------------

| Specification |
| --- |
| Service Workers # cache-storage-has |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using Service Workers
* `Cache`
* `caches`


CacheStorage: keys() method - Web APIs

CacheStorage: keys() method
===========================

 The **`keys()`** method of the `CacheStorage` interface returns a `Promise` that will resolve with an array containing strings corresponding to all of the named `Cache` objects tracked by the `CacheStorage` object in the order they were created.
 Use this method to iterate over a list of all `Cache` objects.

You can access `CacheStorage` through the global `caches` property.

Syntax
------

```js
keys()
```

### Parameters

None.

### Return value

a `Promise` that resolves with an array of the `Cache` names inside the `CacheStorage` object.

Examples
--------

 In this code snippet we wait for an `activate` event, and then run a `waitUntil()` block that clears up any old, unused caches before a new service worker is activated.
 Here we have an allowlist containing the names of the caches we want to keep (`cacheAllowlist`).
 We return the keys of the caches in the `CacheStorage` object using `keys()`, then check each key to see if it is in the allowlist.
 If not, we delete it using `CacheStorage.delete()`.

```js
this.addEventListener("activate", (event) => {
  const cacheAllowlist = ["v2"];

  event.waitUntil(
    caches.keys().then((keyList) =>
      Promise.all(
        keyList.map((key) => {
          if (!cacheAllowlist.includes(key)) {
            return caches.delete(key);
          }
        }),
      ),
    ),
  );
});
```

Specifications
--------------

| Specification |
| --- |
| Service Workers # cache-storage-keys |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using Service Workers
* `Cache`
* `caches`


CacheStorage: match() method - Web APIs

CacheStorage: match() method
============================

 The **`match()`** method of the `CacheStorage` interface checks if a given `Request` or URL string is a key for a stored `Response`.
 This method returns a `Promise` for a `Response`, or a `Promise` which resolves to `undefined` if no match is found.

 You can access `CacheStorage` through the global
 `caches` property.

`Cache` objects are searched in creation order.

**Note:** `caches.match()` is a convenience method.
 Equivalent functionality is to call `cache.match()` on each cache (in the order returned by `caches.keys()`) until a `Response` is returned.

Syntax
------

```js
match(request)
match(request, options)
```

### Parameters

`request`

 The `Request` you want to match. This can be a `Request`
 object or a URL string.

`options` Optional

 An object whose properties control how matching is done in the `match`
 operation. The available options are:

`ignoreSearch`

 A boolean value that specifies whether the
 matching process should ignore the query string in the URL. For example, if set
 to `true`, the `?value=bar` part of
 `http://foo.com/?value=bar` would be ignored when performing a match.
 It defaults to `false`.

`ignoreMethod`

 A boolean value that, when set to
 `true`, prevents matching operations from validating the
 `Request` `http` method (normally only `GET`
 and `HEAD` are allowed.) It defaults to `false`.

`ignoreVary`

 A boolean value that, when set to
 `true,` tells the matching operation not to perform `VARY`
 header matching. In other words, if the URL matches you will get a match
 regardless of whether the `Response` object has a `VARY`
 header or not. It defaults to `false`.

`cacheName`

 A string that represents a specific
 cache to search within.

### Return value

 a `Promise` that resolves to the matching `Response`. If
 no matching response to the specified request is found, the promise resolves
 with `undefined`.

Examples
--------

 This example is from the MDN simple service worker example (see simple service worker running live).
 Here we wait for a `FetchEvent` to fire. We construct a custom response
 like so:

1. Check whether a match for the request is found in the `CacheStorage`
 using `CacheStorage.match()`. If so, serve that.
2. If not, open the `v1` cache using `open()`, put the default
 network request in the cache using `Cache.put()` and return a
 clone of the default network request using `return response.clone()`. The
 last is necessary because `put()` consumes the response body.
3. If this fails (e.g., because the network is down), return a fallback response.

```js
self.addEventListener("fetch", (event) => {
  event.respondWith(
    caches.match(event.request).then((response) => {
      // caches.match() always resolves
      // but in case of success response will have value
      if (response !== undefined) {
        return response;
      } else {
        return fetch(event.request)
          .then((response) => {
            // response may be used only once
            // we need to save clone to put one copy in cache
            // and serve second one
            let responseClone = response.clone();

            caches.open("v1").then((cache) => {
              cache.put(event.request, responseClone);
            });
            return response;
          })
          .catch(() => caches.match("/gallery/myLittleVader.jpg"));
      }
    }),
  );
});
```

Specifications
--------------

| Specification |
| --- |
| Service Workers # cache-storage-match |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using Service Workers
* `Cache`
* `caches`