USBIsochronousOutTransferPacket - Web APIs

USBIsochronousOutTransferPacket
===============================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

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

The `USBIsochronousOutTransferPacket` interface of the WebUSB API is part of the response from a call to the `isochronousTransferOut()` method of the `USBDevice` interface. It represents the status of an individual packet from a request to transfer data from the USB host to the USB device over an isochronous endpoint.

Constructor
-----------

`USBIsochronousOutTransferPacket()`
Experimental

Creates a new `USBIsochronousOutTransferPacket` object with the provided `status` and `bytesWritten` fields.

Instance properties
-------------------

`USBIsochronousOutTransferPacket.bytesWritten` Read only
Experimental

Returns the number of bytes from the packet that were sent to the device.

`USBIsochronousOutTransferPacket.status` Read only
Experimental

Returns the status of the transfer request, one of:

* `"ok"` - The transfer was successful.
* `"stall"` - The device indicated an error by generating a stall condition on the endpoint. A stall on an isochronous endpoint does not need to be cleared.

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

| Specification |
| --- |
| WebUSB API # usbisochronousouttransferpacket |

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

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


CSSRuleList - Web APIs

CSSRuleList
===========

A `CSSRuleList` represents an ordered collection of read-only `CSSRule` objects.

While the `CSSRuleList` object is read-only, and cannot be directly modified, it is considered a `live` object, as the content can change over time.

To edit the underlying rules returned by `CSSRule` objects, use `CSSStyleSheet.insertRule()` and `CSSStyleSheet.deleteRule()`, which are methods of `CSSStyleSheet`.

The interface has no constructor. An instance of `CSSRuleList` is returned by `CSSStyleSheet.cssRules` and `CSSKeyframesRule.cssRules`.

**Note:** This interface was an attempt to create an unmodifiable list and only continues to be supported to not break code that's already using it. Modern APIs use types that wrap around ECMAScript array types instead, so you can treat them like ECMAScript arrays, and at the same time impose additional semantics on their usage (such as making their items read-only).

Instance properties
-------------------

`CSSRuleList.length` Read only

Returns an integer representing the number of `CSSRule` objects in the collection.

Instance methods
----------------

`CSSRuleList.item()`

Gets a single `CSSRule`.

Examples
--------

In the following example there is a stylesheet with three rules. Using `CSSStyleSheet.cssRules` returns a `CSSRuleList`, which is printed to the console.

The number of rules in the list is printed to the console using `CSSRuleList.length`. The first `CSSRule` can be returned by using `0` as the parameter for `CSSRuleList.item`, in the example this will return the rules set for the `body` selector.

### CSS

```css
body {
  font-family:
    system-ui,
    -apple-system,
    sans-serif;
  margin: 2em;
}

.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, 200px);
}

.container > \* {
  background-color: #3740ff;
  color: #fff;
}
```

### JavaScript

```js
let myRules = document.styleSheets[0].cssRules;
console.log(myRules);
console.log(myRules.length);
console.log(myRules[0]);
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # the-cssrulelist-interface |

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

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

See also
--------

* `CSSRule`


LayoutShift - Web APIs

LayoutShift
===========

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

The `LayoutShift` interface of the Performance API provides insights into the layout stability of web pages based on movements of the elements on the page.

Description
-----------

A layout shift happens when any element that is visible in the viewport changes its position between two frames. These elements are described as being **unstable**, indicating a lack of visual stability.

The Layout Instability API provides a way to measure and report on these layout shifts. All tools for debugging layout shifts, including those in the browser's developer tools, use this API. The API can also be used to observe and debug layout shifts by logging the information to the console, to send the data to a server endpoint, or to web page analytics.

Popular performance tools, use this API to calculate a Cumulative Layout Shift (CLS) score.

PerformanceEntry

LayoutShiftInstance properties
-------------------

This interface extends the following `PerformanceEntry` properties by qualifying them as follows:

`PerformanceEntry.duration` Read only
Experimental

Always returns `0` (the concept of duration does not apply to layout shifts).

`PerformanceEntry.entryType` Read only
Experimental

Always returns `"layout-shift"`.

`PerformanceEntry.name` Read only
Experimental

Always returns `"layout-shift"`.

`PerformanceEntry.startTime` Read only
Experimental

Returns a `DOMHighResTimeStamp` representing the time when the layout shift started.

This interface also supports the following properties:

`LayoutShift.value`
Experimental

Returns the layout shift score calculated as the impact fraction (fraction of the viewport that was shifted) multiplied by the distance fraction (distance moved as a fraction of viewport).

`LayoutShift.hadRecentInput`
Experimental

Returns `true` if `lastInputTime` is less than 500 milliseconds in the past.

`LayoutShift.lastInputTime`
Experimental

Returns the time of the most recent excluding input (user input that would exclude this entry as a contributor to the CLS score) or `0` if no excluding input has occurred.

`LayoutShift.sources`
Experimental

Returns an array of `LayoutShiftAttribution` objects with information on the elements that were shifted.

Instance methods
----------------

`LayoutShift.toJSON()`
Experimental

Converts the properties to JSON.

Examples
--------

### Logging layout shift values

The following example shows how to capture layout shifts and log them to the console.

```js
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    // Count layout shifts without recent user input only
    if (!entry.hadRecentInput) {
      console.log("LayoutShift value:", entry.value);
      if (entry.sources) {
        for (const { node, currentRect, previousRect } of entry.sources)
          console.log("LayoutShift source:", node, {
            currentRect,
            previousRect,
          });
      }
    }
  }
});

observer.observe({ type: "layout-shift", buffered: true });
```

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

| Specification |
| --- |
| Layout Instability # sec-layout-shift |

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

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

See also
--------

* `LayoutShiftAttribution`
* Cumulative Layout Shift (CLS)


CSS Typed Object Model API - Web APIs

CSS Typed Object Model API
==========================

The CSS Typed Object Model API simplifies CSS property manipulation by exposing CSS values as typed JavaScript objects rather than strings. This not only simplifies CSS manipulation, but also lessens the negative impact on performance as compared to `HTMLElement.style`.

Generally, CSS values can be read and written in JavaScript as strings, which can be slow and cumbersome. CSS Typed Object Model API provides interfaces to interact with underlying values, by representing them with specialized JS objects that can be manipulated and understood more easily and more reliably than string parsing and concatenation. This is easier for authors (for example, numeric values are reflected with actual JS numbers, and have unit-aware mathematical operations defined for them). It is also generally faster, as values can be directly manipulated and then cheaply translated back into underlying values without having to both build and parse strings of CSS.

CSS Typed OM both allows for the performant manipulation of values assigned to CSS properties while enabling maintainable code that is both more understandable and easier to write.

Interfaces
----------

### `CSSStyleValue`

The `CSSStyleValue` interface of the CSS Typed Object Model API is the base class of all CSS values accessible through the Typed OM API. An instance of this class may be used anywhere a string is expected.

`CSSStyleValue.parse()`

The parse() method of the CSSStyleValue interface allows a CSSNumericValue to be constructed from a CSS string. It sets a specific CSS property to the specified values and returns the first value as a CSSStyleValue object.

`CSSStyleValue.parseAll()`

The parseAll() method of the CSSStyleValue interface sets all occurrences of a specific CSS property to the specified value and returns an array of CSSStyleValue objects, each containing one of the supplied values.

### `StylePropertyMap`

The `StylePropertyMap` interface of the CSS Typed Object Model API provides a representation of a CSS declaration block that is an alternative to CSSStyleDeclaration.

`StylePropertyMap.set()`

Method of StylePropertyMap interface that changes the CSS declaration with the given property to the value given.

`StylePropertyMap.append()`

Method that adds a new CSS declaration to the StylePropertyMap with the given property and value.

`StylePropertyMap.delete()`

Method that removes the CSS declaration with the given property from the StylePropertyMap.

`StylePropertyMap.clear()`

Method that removes all declarations in the StylePropertyMap.

### `CSSUnparsedValue`

The `CSSUnparsedValue` interface of the CSS Typed Object Model API represents property values that reference custom properties. It consists of a list of string fragments and variable references.

`CSSUnparsedValue()` constructor

Creates a new CSSUnparsedValue object which represents property values that reference custom properties.

`CSSUnparsedValue.entries()`

Method returning an array of a given object's own enumerable property [key, value] pairs in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

`CSSUnparsedValue.forEach()`

Method executing a provided function once for each element of the CSSUnparsedValue.

`CSSUnparsedValue.keys()`

Method returning a new *array iterator* object that contains the keys for each index in the array.

### `CSSKeywordValue` Serialization

The `CSSKeywordValue` interface of the CSS Typed Object Model API creates an object to represent CSS keywords and other identifiers.

`CSSKeywordValue()` constructor

Constructor creates a new `CSSKeywordValue()` object which represents CSS keywords and other identifiers.

`CSSKeywordValue.value()`

Property of the CSSKeywordValue interface returning or setting the value of the CSSKeywordValue.

CSSStyleValue Interfaces
------------------------

CSSStyleValue is the base class through which all CSS values are expressed. Subclasses include:

`CSSImageValue` objects

An interface representing values for properties that take an image, for example `background-image`, `list-style-image`, or `border-image-source`.

`CSSKeywordValue`

An interface which creates an object to represent CSS keywords and other identifiers. When used where a string is expected, it will return the value of CSSKeyword.value.

`CSSMathValue`

A tree of subclasses representing numeric values that are more complicated than a single value and unit, including:

* `CSSMathInvert` - represents a CSS `calc()` value used as `calc(1 / <value>)`.
* `CSSMathMax` - represents the CSS `max()` function.
* `CSSMathMin` - represents the CSS `min()` function.
* `CSSMathNegate` - negates the value passed into it.
* `CSSMathProduct` - represents the result obtained by calling `add()`, `sub()`, or `toSum()` on `CSSNumericValue`.
* `CSSMathSum` - represents the result obtained by calling `add()`, `sub()`, or `toSum()` on `CSSNumericValue`.

`CSSNumericValue`

An interface representing operations that all numeric values can perform, including:

* `CSSNumericValue.add` - Adds supplied numbers to the `CSSNumericValue`.
* `CSSNumericValue.sub` - Subtracts supplied numbers to the `CSSNumericValue`.
* `CSSNumericValue.mul` - Multiplies supplied numbers to the `CSSNumericValue`.
* `CSSNumericValue.div` - Divides a supplied number by other numbers, throwing an error if 0.
* `CSSNumericValue.min` - Returns the minimum value passed
* `CSSNumericValue.max` - Returns the maximum value passed
* `CSSNumericValue.equals` - Returns true if all the values are the exact same type and value, in the same order. Otherwise, false
* `CSSNumericValue.to` - Converts `value` into another one with the specified *unit.*
* `CSSNumericValue.toSum`
* `CSSNumericValue.type`
* `CSSNumericValue.parse` - Returns a number parsed from a CSS string

`CSSPositionValue`

Represents values for properties that take a position, for example object-position.

`CSSTransformValue`

An interface representing a list of `transform` list values. They "contain" one or more `CSSTransformComponent`s, which represent individual `transform` function values.

`CSSUnitValue`

An interface representing numeric values that can be represented as a single unit, or a named number and percentage.

`CSSUnparsedValue`

Represents property values that reference custom properties. It consists of a list of string fragments and variable references.

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

| Specification |
| --- |
| CSS Typed OM Level 1 # stylevalue-objects |
| CSS Typed OM Level 1 # the-stylepropertymap |
| CSS Typed OM Level 1 # cssunparsedvalue |
| CSS Typed OM Level 1 # keywordvalue-objects |

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

### api.CSSStyleValue

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

### api.StylePropertyMap

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

### api.CSSUnparsedValue

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

### api.CSSKeywordValue

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

See also
--------

* CSS Painting API
* Using the CSS Typed Object Model
* CSS Houdini


GamepadHapticActuator - Web APIs

GamepadHapticActuator
=====================

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

The **`GamepadHapticActuator`** interface of the Gamepad API represents hardware in the controller designed to provide haptic feedback to the user (if available), most commonly vibration hardware.

This interface is accessible through the `Gamepad.hapticActuators` property.

Instance properties
-------------------

`GamepadHapticActuator.type` Read only

Returns an enum representing the type of the haptic hardware.

Instance methods
----------------

`GamepadHapticActuator.pulse()` Read only

Makes the hardware pulse at a certain intensity for a specified duration.

`GamepadHapticActuator.playEffect()` Read only
Non-standard

Makes the hardware play a specific vibration pattern.

Examples
--------

```js
const gamepad = navigator.getGamepads()[0];

gamepad.hapticActuators[0].pulse(1.0, 200);

gamepad.vibrationActuator.playEffect("dual-rumble", {
  startDelay: 0,
  duration: 200,
  weakMagnitude: 1.0,
  strongMagnitude: 1.0,
});
```

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

| Specification |
| --- |
| Gamepad Extensions # gamepadhapticactuator-interface |

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

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

See also
--------

* Gamepad API


HTMLFormElement - Web APIs

HTMLFormElement
===============

The **`HTMLFormElement`** interface represents a `<form>` element in the DOM. It allows access to—and, in some cases, modification of—aspects of the form, as well as access to its component elements.

EventTarget

Node

Element

HTMLElement

HTMLFormElementInstance properties
-------------------

*This interface also inherits properties from its parent, `HTMLElement`.*

`HTMLFormElement.elements` Read only

A `HTMLFormControlsCollection` holding all form controls belonging to this form element.

`HTMLFormElement.length` Read only

A `long` reflecting the number of controls in the form.

`HTMLFormElement.name`

A string reflecting the value of the form's `name` HTML attribute, containing the name of the form.

`HTMLFormElement.method`

A string reflecting the value of the form's `method` HTML attribute, indicating the HTTP method used to submit the form. Only specified values can be set.

`HTMLFormElement.target`

A string reflecting the value of the form's `target` HTML attribute, indicating where to display the results received from submitting the form.

`HTMLFormElement.action`

A string reflecting the value of the form's `action` HTML attribute, containing the URI of a program that processes the information submitted by the form.

`HTMLFormElement.encoding` or `HTMLFormElement.enctype`

A string reflecting the value of the form's `enctype` HTML attribute, indicating the type of content that is used to transmit the form to the server. Only specified values can be set. The two properties are synonyms.

`HTMLFormElement.acceptCharset`

A string reflecting the value of the form's `accept-charset` HTML attribute, representing the character encoding that the server accepts.

`HTMLFormElement.autocomplete`

A string reflecting the value of the form's `autocomplete` HTML attribute, indicating whether the controls in this form can have their values automatically populated by the browser.

`HTMLFormElement.noValidate`

A boolean value reflecting the value of the form's `novalidate` HTML attribute, indicating whether the form should not be validated.

Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (e.g. a form with an input named `action` will have its `action` property return that input instead of the form's `action` HTML attribute).

Instance methods
----------------

*This interface also inherits methods from its parent, `HTMLElement`.*

`checkValidity()`

Returns `true` if the element's child controls are subject to constraint validation and satisfy those constraints; returns `false` if some controls do not satisfy their constraints. Fires an event named `invalid` at any control that does not satisfy its constraints; such controls are considered invalid if the event is not canceled. It is up to the programmer to decide how to respond to `false`.

`reportValidity()`

Returns `true` if the element's child controls satisfy their validation constraints. When `false` is returned, cancelable `invalid` events are fired for each invalid child and validation problems are reported to the user.

`requestSubmit()`

Requests that the form be submitted using the specified submit button and its corresponding configuration.

`reset()`

Resets the form to its initial state.

`submit()`

Submits the form to the server.

### Deprecated methods

`HTMLFormElement.requestAutocomplete()`
Deprecated

Triggers a native browser interface to assist the user in completing the fields which have an autofill field name value that is not `off` or `on`. The form will receive an event once the user has finished with the interface, the event will either be `autocomplete` when the fields have been filled or `autocompleteerror` when there was a problem.

Events
------

Listen to these events using `addEventListener()`, or by assigning an event listener to the `oneventname` property of this interface.

`formdata`

The `formdata` event fires after the entry list representing the form's data is constructed.

`reset`

The `reset` event fires when a form is reset.

`submit`

The `submit` event fires when a form is submitted.

Usage notes
-----------

### Obtaining a form element object

To obtain an `HTMLFormElement` object, you can use a CSS selector with `querySelector()`, or you can get a list of all of the forms in the document using its `forms` property.

`Document.forms` returns an array of `HTMLFormElement` objects listing each of the forms on the page. You can then use any of the following syntaxes to get an individual form:

`document.forms[index]`

Returns the form at the specified `index` into the array of forms.

`document.forms[id]`

Returns the form whose ID is `id`.

`document.forms[name]`

Returns the form whose `name` attribute's value is `name`.

### Accessing the form's elements

You can access the list of the form's data-containing elements by examining the form's `elements` property. This returns an `HTMLFormControlsCollection` listing all of the form's user data entry elements, both those which are descendants of the `<form>` and those which are made members of the form using their `form` attributes.

You can also get the form's element by using its `name` attribute as a key of the `form`, but using `elements` is a better approach—it contains *only* the form's elements, and it cannot be mixed with other attributes of the `form`.

### Issues with Naming Elements

Some names will interfere with JavaScript access to the form's properties and elements.

For example:

* `<input name="id">` will take precedence over `<form id="…">`. This means that `form.id` will not refer to the form's id, but to the element whose name is "`id`". This will be the case with any other form properties, such as `<input name="action">` or `<input name="post">`.
* `<input name="elements">` will render the form's `elements` collection inaccessible. The reference `form.elements` will now refer to the individual element.

To avoid such problems with element names:

* *Always* use the `elements` collection to avoid ambiguity between an element name and a form property.
* *Never* use "`elements`" as an element name.

If you are not using JavaScript, this will not cause a problem.

### Elements that are considered form controls

The elements included by `HTMLFormElement.elements` and `HTMLFormElement.length` are the following:

* `<button>`
* `<fieldset>`
* `<input>` (with the exception that any whose `type` is `"image"` are omitted for historical reasons)
* `<object>`
* `<output>`
* `<select>`
* `<textarea>`

No other elements are included in the list returned by `elements`, which makes it an excellent way to get at the elements most important when processing forms.

Examples
--------

Creating a new form element, modifying its attributes, then submitting it:

```js
const f = document.createElement("form"); // Create a form
document.body.appendChild(f); // Add it to the document body
f.action = "/cgi-bin/some.cgi"; // Add action and method attributes
f.method = "POST";
f.submit(); // Call the form's submit() method
```

Extract information from a `<form>` element and set some of its attributes:

```html
<form name="formA" action="/cgi-bin/test" method="post">
  <p>Press "Info" for form details, or "Set" to change those details.</p>
  <p>
    <button type="button" onclick="getFormInfo();">Info</button>
    <button type="button" onclick="setFormInfo(this.form);">Set</button>
    <button type="reset">Reset</button>
  </p>

  <textarea id="form-info" rows="15" cols="20"></textarea>
</form>

<script>
 function getFormInfo() {
 // Get a reference to the form via its name
 const f = document.forms["formA"];
 // The form properties we're interested in
 const properties = [
 "elements",
 "length",
 "name",
 "charset",
 "action",
 "acceptCharset",
 "action",
 "enctype",
 "method",
 "target",
 ];
 // Iterate over the properties, turning them into a string that we can display to the user
 const info = properties
 .map((property) => `${property}: ${f[property]}`)
 .join("\n");

 // Set the form's <textarea> to display the form's properties
 document.forms["formA"].elements["form-info"].value = info; // document.forms["formA"]['form-info'].value would also work
 }

 function setFormInfo(f) {
 // Argument should be a form element reference.
 f.action = "a-different-url.cgi";
 f.name = "a-different-name";
 }
</script>
```

Submit a `<form>` into a new window:

```html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <title>Example new-window form submission</title>
  </head>
  <body>
    <form action="test.php" target="\_blank">
      <p>
        <label>First name: <input type="text" name="firstname" /></label>
      </p>
      <p>
        <label>Last name: <input type="text" name="lastname" /></label>
      </p>
      <p>
        <label><input type="password" name="pwd" /></label>
      </p>

      <fieldset>
        <legend>Pet preference</legend>

        <p>
          <label><input type="radio" name="pet" value="cat" /> Cat</label>
        </p>
        <p>
          <label><input type="radio" name="pet" value="dog" /> Dog</label>
        </p>
      </fieldset>

      <fieldset>
        <legend>Owned vehicles</legend>

        <p>
          <label
 ><input type="checkbox" name="vehicle" value="Bike" />I have a
            bike</label
 >
        </p>
        <p>
          <label
 ><input type="checkbox" name="vehicle" value="Car" />I have a
            car</label
 >
        </p>
      </fieldset>

      <p><button>Submit</button></p>
    </form>
  </body>
</html>
```

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

| Specification |
| --- |
| HTML Standard # htmlformelement |

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

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

See also
--------

* The HTML element implementing this interface: `<form>`.


PerformanceResourceTiming - Web APIs

PerformanceResourceTiming
=========================

**Note:** This feature is available in Web Workers

The **`PerformanceResourceTiming`** interface enables retrieval and analysis of detailed network timing data regarding the loading of an application's resources. An application can use the timing metrics to determine, for example, the length of time it takes to fetch a specific resource, such as an `XMLHttpRequest`, `<SVG>`, image, or script.

Description
-----------

The interface's properties create a resource loading timeline with high-resolution timestamps for network events such as redirect start and end times, fetch start, DNS lookup start and end times, response start and end times, and more. Additionally, the interface extends `PerformanceEntry` with other properties which provide data about the size of the fetched resource as well as the type of resource that initiated the fetch.

PerformanceEntry

PerformanceResourceTiming### Typical resource timing metrics

The properties of this interface allow you to calculate certain resource timing metrics. Common use cases include:

* Measuring TCP handshake time (`connectEnd` - `connectStart`)
* Measuring DNS lookup time (`domainLookupEnd` - `domainLookupStart`)
* Measuring redirection time (`redirectEnd` - `redirectStart`)
* Measuring interim request time (`firstInterimResponseStart` - `requestStart`)
* Measuring request time (`responseStart` - `requestStart`)
* Measuring TLS negotiation time (`requestStart` - `secureConnectionStart`)
* Measuring time to fetch (without redirects) (`responseEnd` - `fetchStart`)
* Measuring ServiceWorker processing time (`fetchStart` - `workerStart`)
* Checking if content was compressed (`decodedBodySize` should not be `encodedBodySize`)
* Checking if local caches were hit (`transferSize` should be `0`)
* Checking if modern and fast protocols are used (`nextHopProtocol` should be HTTP/2 or HTTP/3)
* Checking if the correct resources are render-blocking (`renderBlockingStatus`)
Instance properties
-------------------

### Inherited from `PerformanceEntry`

This interface extends the following `PerformanceEntry` properties for resource performance entry types by qualifying and constraining them as follows:

`PerformanceEntry.duration` Read only

Returns a `timestamp` that is the difference between the `responseEnd` and the `startTime` properties.

`PerformanceEntry.entryType` Read only

Returns `"resource"`.

`PerformanceEntry.name` Read only

Returns the resource's URL.

`PerformanceEntry.startTime` Read only

Returns the `timestamp` for the time a resource fetch started. This value is equivalent to `PerformanceResourceTiming.fetchStart`.

### Timestamps

The interface supports the following timestamp properties which you can see in the diagram and are listed in the order in which they are recorded for the fetching of a resource. An alphabetical listing is shown in the navigation, at left.

![Timestamp diagram listing timestamps in the order in which they are recorded for the fetching of a resource](/en-US/docs/Web/API/PerformanceResourceTiming/timestamp-diagram.svg)

`PerformanceResourceTiming.redirectStart` Read only

A `DOMHighResTimeStamp` that represents the start time of the fetch which initiates the redirect.

`PerformanceResourceTiming.redirectEnd` Read only

A `DOMHighResTimeStamp` immediately after receiving the last byte of the response of the last redirect.

`PerformanceResourceTiming.workerStart` Read only

Returns a `DOMHighResTimeStamp` immediately before dispatching the `FetchEvent` if a Service Worker thread is already running, or immediately before starting the Service Worker thread if it is not already running. If the resource is not intercepted by a Service Worker the property will always return 0.

`PerformanceResourceTiming.fetchStart` Read only

A `DOMHighResTimeStamp` immediately before the browser starts to fetch the resource.

`PerformanceResourceTiming.domainLookupStart` Read only

A `DOMHighResTimeStamp` immediately before the browser starts the domain name lookup for the resource.

`PerformanceResourceTiming.domainLookupEnd` Read only

A `DOMHighResTimeStamp` representing the time immediately after the browser finishes the domain name lookup for the resource.

`PerformanceResourceTiming.connectStart` Read only

A `DOMHighResTimeStamp` immediately before the browser starts to establish the connection to the server to retrieve the resource.

`PerformanceResourceTiming.secureConnectionStart` Read only

A `DOMHighResTimeStamp` immediately before the browser starts the handshake process to secure the current connection.

`PerformanceResourceTiming.connectEnd` Read only

A `DOMHighResTimeStamp` immediately after the browser finishes establishing the connection to the server to retrieve the resource.

`PerformanceResourceTiming.requestStart` Read only

A `DOMHighResTimeStamp` immediately before the browser starts requesting the resource from the server.

`PerformanceResourceTiming.firstInterimResponseStart`
Experimental
 Read only

A `DOMHighResTimeStamp` that represents the interim response time (for example, 100 Continue or 103 Early Hints).

`PerformanceResourceTiming.responseStart` Read only

A `DOMHighResTimeStamp` immediately after the browser receives the first byte of the response from the server.

`PerformanceResourceTiming.responseEnd` Read only

A `DOMHighResTimeStamp` immediately after the browser receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first.

### Additional resource information

Additionally, this interface exposes the following properties containing more information about a resource:

`PerformanceResourceTiming.decodedBodySize` Read only

A number that is the size (in octets) received from the fetch (HTTP or cache) of the message body, after removing any applied content encoding.

`PerformanceResourceTiming.encodedBodySize` Read only

A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload body, before removing any applied content encodings.

`PerformanceResourceTiming.initiatorType` Read only

A string representing the web platform feature that initiated the performance entry.

`PerformanceResourceTiming.nextHopProtocol` Read only

A string representing the network protocol used to fetch the resource, as identified by the ALPN Protocol ID (RFC7301).

`PerformanceResourceTiming.renderBlockingStatus` Read only

A string representing the render-blocking status. Either "`blocking`" or "`non-blocking`".

`PerformanceResourceTiming.responseStatus`
Experimental
 Read only

A number representing the HTTP response status code returned when fetching the resource.

`PerformanceResourceTiming.transferSize` Read only

A number representing the size (in octets) of the fetched resource. The size includes the response header fields plus the response payload body.

`PerformanceResourceTiming.serverTiming` Read only

An array of `PerformanceServerTiming` entries containing server timing metrics.

`PerformanceResourceTiming.deliveryType`
Experimental
 Read only

Indicates how the resource was delivered — for example from the cache or from a navigational prefetch.

Instance methods
----------------

`PerformanceResourceTiming.toJSON()`

Returns a JSON representation of the `PerformanceResourceTiming` object.

Examples
--------

### Logging resource timing information

Example using a `PerformanceObserver`, which notifies of new `resource` performance entries as they are recorded in the browser's performance timeline. Use the `buffered` option to access entries from before the observer creation.

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    console.log(entry);
  });
});

observer.observe({ type: "resource", buffered: true });
```

Example using `Performance.getEntriesByType()`, which only shows `resource` performance entries present in the browser's performance timeline at the time you call this method:

```js
const resources = performance.getEntriesByType("resource");
resources.forEach((entry) => {
  console.log(entry);
});
```

Security requirements
---------------------

### Cross-origin timing information

Many of the resource timing properties are restricted to return `0` or an empty string when the resource is a cross-origin request. To expose cross-origin timing information, the `Timing-Allow-Origin` HTTP response header needs to be set.

For example, to allow `https://developer.mozilla.org` to see resource timing information, the cross-origin resource should send:

```http
Timing-Allow-Origin: https://developer.mozilla.org
```

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

| Specification |
| --- |
| Resource Timing # resources-included-in-the-performanceresourcetiming-interface |

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

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

See also
--------

* Resource timing (Overview)


WEBGL_lose_context extension - Web APIs

WEBGL\_lose\_context extension
==============================

The **WEBGL\_lose\_context** extension is part of the WebGL API and exposes functions to simulate losing and restoring a `WebGLRenderingContext`.

WebGL extensions are available using the `WebGLRenderingContext.getExtension()` method. For more information, see also Using Extensions in the WebGL tutorial.

**Note:** This extension is available to both, WebGL1 and WebGL2 contexts.

Instance methods
----------------

`WEBGL_lose_context.loseContext()`

Simulates losing the context.

`WEBGL_lose_context.restoreContext()`

Simulates restoring the context.

Examples
--------

With this extension, you can simulate the `webglcontextlost` and `webglcontextrestored` events:

```js
const canvas = document.getElementById("canvas");
const gl = canvas.getContext("webgl");

canvas.addEventListener("webglcontextlost", (event) => {
  console.log(event);
});

gl.getExtension("WEBGL\_lose\_context").loseContext();

// WebGLContextEvent event with type "webglcontextlost" is logged.
```

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

| Specification |
| --- |
| WebGL WEBGL\_lose\_context Khronos Ratified Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.isContextLost()`
* Events: `webglcontextlost`, `webglcontextrestored`, `webglcontextcreationerror`


RTCTransformEvent - Web APIs

RTCTransformEvent
=================

The **`RTCTransformEvent`** of the WebRTC API represent an event that is fired in a dedicated worker when an encoded frame has been queued for processing by a WebRTC Encoded Transform.

 The interface has a `transformer` property that exposes a readable stream and a writable stream.
 A worker should read encoded frames from `transformer.readable`, modify them as needed, and write them to `transformer.writable` in the same order and without any duplication.

At time of writing there is just one event based on `RTCTransformEvent`: `rtctransform`.

Event

RTCTransformEventInstance properties
-------------------

*Since `RTCTransformEvent` is based on `Event`, its properties are also available.*

`RTCTransformEvent.transformer` Read only

Returns the `RTCRtpScriptTransformer` associated with the event.

Transform event types
---------------------

There is only one type of transform event.

### `rtctransform`

The `rtctransform` event is fired at the worker global scope on construction of an associated `RTCRtpScriptTransform`, and whenever a new encoded video or audio frame is enqueued for processing.

You can add a `rtctransform` event listener to be notified when the new frame is available using either `DedicatedWorkerGlobalScope.addEventListener()` or the `onrtctransform` event handler property.

Example
-------

This example creates an event listener for the `rtctransform` event.

 The example assumes we have a `TransformStream` with an `options` object passed from a `RTCRtpScriptTransform` constructor in the main-thread.
 The code at the end shows how the stream is piped through the transform stream from the `readable` to the `writable`.

```js
addEventListener("rtctransform", (event) => {
  let transform;
  // Select a transform based on passed options
  if (event.transformer.options.name == "senderTransform") {
    transform = createSenderTransform(); // A TransformStream (not shown)
  } else if (event.transformer.options.name == "receiverTransform") {
    transform = createReceiverTransform(); // A TransformStream (not shown)
  }
  // Pipe frames from the readable to writeable through TransformStream
  event.transformer.readable
    .pipeThrough(transform)
    .pipeTo(event.transformer.writable);
});
```

Note that this code is part of a more complete example provided in Using WebRTC Encoded Transforms.

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

| Specification |
| --- |
| WebRTC Encoded Transform # rtctransformevent |

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

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

* Using WebRTC Encoded Transforms
* `TransformStream`


CSSSkewY - Web APIs

CSSSkewY
========

The **`CSSSkewY`** interface of the CSS\_Object\_Model#css\_typed\_object\_model represents the `skewY()` value of the individual `transform` property in CSS. It inherits properties and methods from its parent `CSSTransformValue`.

CSSTransformComponent

CSSSkewYConstructor
-----------

`CSSSkewY()`

Creates a new `CSSSkewY` object.

Instance properties
-------------------

*Inherits properties from its ancestor* `CSSTransformValue`.

`ay`

Returns or sets the y-axis value.

Instance methods
----------------

*Inherits methods from its ancestor* `CSSTransformValue`.

Examples
--------

To Do

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

| Specification |
| --- |
| CSS Typed OM Level 1 # cssskewy |

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

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


User-Agent Client Hints API - Web APIs

User-Agent Client Hints API
===========================

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

The User-Agent Client Hints API extends Client Hints to provide a way of exposing browser and platform information via User-Agent response and request headers, and a JavaScript API.

Concepts and Usage
------------------

Parsing the User-Agent string has historically been the way to get information about the user's browser or device. A typical user agent string looks like the following example, identifying Chrome 92 on Windows:
```

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36
```

User agent Client Hints aims to provide this information in a more privacy-preserving way by enforcing a model where the server requests a set of information. The browser decides what to return. This approach means that a user-agent could provide settings that allow a user to hide some of the information that could fingerprint them from such requests.

In order to decide what to return, the information accessed via this API is split into two groups—**low entropy** and **high entropy** hints. Low entropy hints are those that do not give away much information, the API makes these easily accessible with every request. High entropy hints have the potential to give away more information and therefore are gated in such a way that the browser can make a decision as to whether to provide them. This decision could potentially be based on user preferences, or behind a permission request.

### Use cases for User-Agent Client Hints

Potential use cases include:

* Providing custom-tailored polyfills to users on identifying that their browser lacked some web platform feature.
* Working around browser bugs.
* Recording browser analytics.
* Adapting content based on user-agent information.
 This includes serving different content to mobile devices, in particular devices identified as low-powered.
 It might also include adapting the design to tailor the interfaces to the user's OS, or providing links to OS-specific ones.
* Providing a notification when a user logs in from a different browser or device, as a security feature.
* Providing the correct binary executable, on a site offering a download.
* Collecting information about the browser and device to identify application errors.
* Blocking spammers, bots, and crawlers.
Interfaces
----------

`NavigatorUAData`

Provides properties and methods to access data about the user's browser and operating system.

Examples
--------

### Getting the brands

The following example prints the value of `NavigatorUAData.brands` to the console.

```js
console.log(navigator.userAgentData.brands);
```

### Returning high entropy values

In the following example a number of hints are requested using the `NavigatorUAData.getHighEntropyValues()` method. When the promise resolves, this information is printed to the console.

```js
navigator.userAgentData
  .getHighEntropyValues([
    "architecture",
    "model",
    "platform",
    "platformVersion",
    "fullVersionList",
  ])
  .then((ua) => {
    console.log(ua);
  });
```

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

| Specification |
| --- |
| User-Agent Client Hints # navigatoruadata |

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

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

See also
--------

* Improving user privacy and developer experience with User-Agent Client Hints
* Migrate to User-Agent Client Hints


Storage Access API - Web APIs

Storage Access API
==================

The Storage Access API provides a way for cross-site content loaded in a third-party context (i.e., embedded in an `<iframe>`) to gain access to third-party cookies that it would typically only have access to in a first-party context (i.e., when loaded directly in a browser tab).

The Storage Access API is relevant to user agents that, by default, block access to third-party cookies to improve privacy (for example, to prevent tracking). There are legitimate uses for third-party cookies that we still want to enable, even with these default restrictions in place. Examples include single sign-on (SSO) with federated identity providers (IdPs), or persisting user details such as location data or viewing preferences across different sites.

The API provides methods that allow embedded resources to check whether they currently have access to third-party cookies and, if not, to request access from the user agent.

**Note:** The *Storage Access API* name may seem like somewhat of a misnomer, given that it only provides access to cookies, and not other client-side storage mechanisms such as Web Storage or IndexedDB. The name has been kept generic because it may provide access to other forms of client-side storage in the future.

Concepts and usage
------------------

Browsers implement several storage access features and policies restricting access to third-party cookies. These range from giving embedded resources under each top-level origin a unique cookie storage space (partitioned cookies) to outright blocking of cookie access when resources are loaded in a third-party context.

The semantics around third-party cookie-blocking features and policies differ from browser to browser, but the core functionality is similar. Cross-site resources embedded in a third-party context are not given access to the same cookies that they would have access to when loaded in a first-party context. This is done with good intent — browser vendors want to take steps to better protect their user's privacy and security. Examples include leaving them less open to having their activity tracked across different sites, and less vulnerable to exploits such as cross-site request forgery (CSRF).

However, there are legitimate uses for embedded cross-site content accessing third-party cookies, which the above features and policies are known to break. Let's say you've got a series of different sites that provide access to different products — `heads-example.com`, `shoulders-example.com`, `knees-example.com`, and `toes-example.com`.

Alternatively, you might separate your content or services into different country domains for localization purposes — `example.com`, `example.ua`, `example.br`, etc. — or in some other way.

You might have accompanying utility sites with components embedded in all the other sites, for example, to provide SSO (`sso-example.com`) or general personalization services (`services-example.com`). These utility sites will want to share their state with the sites they are embedded in via cookies. They cannot share first-party cookies because they are on different domains, and third-party cookies will no longer work in browsers that block them.

In such situations, site owners often encourage users to add their site as an exception or to disable third-party cookie-blocking policies entirely. Users who wish to continue interacting with their content must significantly relax their blocking policy for resources loaded from all embedded origins and possibly across all websites.

The Storage Access API is intended to solve this problem; embedded cross-site content can request unrestricted access to third-party cookies on a frame-by-frame basis via the `Document.requestStorageAccess()` method. It can also check whether it already has access via the `Document.hasStorageAccess()` method.

### Unpartitioned versus partitioned cookies

It is important to note that the Storage Access API is only needed to provide access to *unpartitioned* third-party cookies. This means cookies stored in the traditional way since the early web — all cookies set on the same site are stored in the same cookie jar. This is in contrast to *partitioned* cookies, where embedded resources under each top-level site are given a unique cookie storage space, thereby making tracking users across sites via these cookies impossible.

Browsers have various mechanisms to partition third-party cookie access, for example Firefox Total Cookie Protection and Cookies Having Independent Partitioned State (CHIPS).

When we talk about third-party cookies in the context of the Storage Access API, we implicitly mean *unpartitioned* third-party cookies.

### How it works

Embedded content that has a legitimate need for third party cookie access can request access using the Storage Access API as follows:

1. It can call the `Document.hasStorageAccess()` method to check whether it has the access it needs already.
2. If not, it can request access via the `Document.requestStorageAccess()` method.
3. Depending on the browser, the user will be asked whether to grant access to the requesting embed in slightly different ways.
    * Safari shows prompts for all embedded content that has not previously received storage access.
    * Firefox only prompts users after an origin has requested storage access on more than a threshold number of sites.
    * Chrome shows prompts for all embedded content that has not previously received storage access. It will however automatically grant access and skip prompts if the embedded content and embedding site are part of the same related website set.
4. Access is granted or denied based on whether the content meets all the security requirements — see Security measures for general requirements, and Browser-specific variations for some browser-specific security requirements. The `Promise`-based nature of `requestStorageAccess()` allows you to run code to handle success and failure cases.
    * Modern spec behavior dictates that access is granted *per-frame* — every separate content embed has its third-party cookie access blocked by default, and needs to call `requestStorageAccess()` to opt in to access. If a content embed has received access, and same-site embeds then call `requestStorageAccess()`, their promises will fulfill automatically. But they still need to opt in.
    * The only exception to the "blocked by default" behavior is when a content embed makes a successful `requestStorageAccess()`, but then performs a same-origin navigation (for example reloading itself). In such cases, the storage access is carried over from the previous navigation.
    * In older spec versions, the access was *per-page* (Safari is the only browser still using this model). When one embed received third-party cookie access via `requestStorageAccess()`, all other same-site embeds would automatically receive access. This was not desirable behavior from a security standpoint — for example, if `shop.example.com` embedded `locator.users.com` to allow users to use their location info while shopping, and `locator.users.com` called `requestStorageAccess()`, `shop.example.com` and any other sites it embeds would be able to access its cookies, but also access cookies from `private.users.com`, which is not intended to be embedded. Read more about the motivations behind this change.
5. Once access is granted, a permission key is stored in the browser with the structure `<top-level site, embedded site>`. For example, if the embedding site is `embedder.com`, and the embed is `locator.example.com`, the key would be `<embedder.com, example.com>`. Same-site embeds (`docs.example.com`, `profile.example.com`, etc.) would then be able to call `requestStorageAccess()` and the promise would fulfill automatically, as mentioned earlier.
    * Older spec versions used the more specific permission key structure `<top-level site, embedded origin>`, which meant that same-site, cross-origin embeds didn't match the permission key and had to go through the whole process separately.

**Note:** In cases where a top-level site has its cookies partitioned, the Storage Access API isn't required, as sharing the cookies by default has no privacy risk.

Security measures
-----------------

Several different security measures could cause a `Document.requestStorageAccess()` call to fail. Check the below list if you are having trouble getting a request to work:

1. The call must be associated with a user gesture (transient activation) such as a tap or click. This prevents embedded content on the page from spamming the browser or user with excessive access requests. Note that this isn't required if:
    * Permission to use the API has already been granted, for example by another same-site resource calling `requestStorageAccess()`.
    * The caller is a top-level document or same-site to the top-level document. In such cases, `requestStorageAccess()` probably doesn't need to be called at all.
2. The document and top-level document must not have a `null` origin.
3. Origins that have never been interacted with as a first party do not have a notion of first-party storage. From the user's perspective, they only have a third-party relationship with that origin. Access requests are automatically denied if the browser detects that the user hasn't interacted with the embedded content in a first-party context recently (in Firefox, "recently" means within 30 days).
4. The document's window must be a secure context.
5. Sandboxed `<iframe>`s cannot be granted storage access by default for security reasons. The API therefore also adds the `allow-storage-access-by-user-activation` sandbox token. The embedding website needs to add this to allow storage access requests to be successful, along with `allow-scripts` and `allow-same-origin` to allow it to execute a script to call the API and execute it in an origin that can have cookies:

```html
<iframe
 sandbox="allow-storage-access-by-user-activation
 allow-scripts
 allow-same-origin">
  …
</iframe>
```

6. Usage of this feature may be blocked by a `storage-access` Permissions Policy set on your server.

**Note:** The document may also be required to pass additional browser-specific checks. Examples: allowlists, blocklists, on-device classification, user settings, anti-clickjacking heuristics, or prompting the user for explicit permission.

Browser-specific variations
---------------------------

Although the API surface is the same, websites using the Storage Access API should expect differences in the level and extent of third-party cookie access they receive between different browsers, due to differences in their storage access policies.

### Chrome

* Cookies must have `SameSite=None` explicitly set on them, because the default value for Chrome is `SameSite=Lax` (`SameSite=None` is the default in Firefox and Safari).
* Cookies must have the `Secure` attribute set on them.
* The storage access grants are phased out after 30 days of browser usage passed without user interaction. Interaction with the embedded content extends this limit by another 30 days. This doesn't occur when `Document.requestStorageAccessFor()` is called because the user is already on the page.
### Firefox

* If the embedded origin `tracker.example` has already obtained third-party cookie access on the top-level origin `foo.example`, and the user visits a page from `foo.example` embedding a page from `tracker.example` again in less than 30 days, the embedded origin will have third-party cookie access immediately when loading.
* The storage access grants are phased out after 30 calendar days have passed.

Documentation for Firefox's new storage access policy for blocking tracking cookies includes a detailed description of the scope of storage access grants.

### Safari

* The storage access grants are phased out after 30 days of browser usage passed without user interaction. Successful use of the Storage Access API resets this counter.
Examples
--------

* See Using the Storage Access API for an implementation guide with code examples.
* See Storage Access API Demo for a live demo.
API methods
-----------

`Document.hasStorageAccess()`

Returns a `Promise` that resolves with a boolean value indicating whether the document has access to third-party cookies.

`Document.requestStorageAccess()`

Allows content loaded in a third-party context (i.e., embedded in an `<iframe>`) to request access to third-party cookies; returns a `Promise` that resolves if the access was granted, and rejects if access was denied.

`Document.requestStorageAccessFor()`
Experimental

A proposed extension to the Storage Access API that allows top-level sites to request third-party cookie access on behalf of embedded content originating from another site in the same related website set. Returns a `Promise` that resolves if the access was granted, and rejects if access was denied.

**Note:** User interaction propagates to the promise returned by these methods, allowing the callers to take actions requiring user interaction without requiring a second click. For example, a caller could open a pop-up window from the resolved promise without triggering Firefox's pop-up blocker.

### Additions to other APIs

`Permissions.query()`, the `"storage-access"` feature name

In supporting browsers, this can query whether third-party cookie access has been granted in general, that is, to another same-site embed. If so, you can call `requestStorageAccess()` without user interaction, and the promise will resolve automatically.

`Permissions.query()`, the `"top-level-storage-access"` feature name
Experimental

A separate feature name used to query whether permission to access third-party cookies has already been granted via `requestStorageAccessFor()`. If so, you don't need to call `requestStorageAccessFor()` again.

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

| Specification |
| --- |
| The Storage Access API  |

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

### api.Document.hasStorageAccess

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

### api.Document.requestStorageAccess

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

### api.Document.requestStorageAccessFor

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

### api.Permissions.permission\_storage-access

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

See also
--------

* Using the Storage Access API
* Introducing Storage Access API (WebKit blog)


GestureEvent - Web APIs

GestureEvent
============

**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 **`GestureEvent`** is a proprietary interface specific to WebKit which gives information regarding multi-touch gestures. Events using this interface include `gesturestart`, `gesturechange`, and `gestureend`.

Instance properties
-------------------

*This interface also inherits properties of its parents, `UIEvent` and `Event`.*

`GestureEvent.rotation` Read only
Non-standard

Change in rotation (in degrees) since the event's beginning. Positive values indicate clockwise rotation; negative values indicate counterclockwise rotation. Initial value: `0.0`.

`GestureEvent.scale` Read only
Non-standard

Distance between two digits since the event's beginning. Expressed as a floating-point multiple of the initial distance between the digits at the beginning of the gesture. Values below 1.0 indicate an inward pinch (zoom out). Values above 1.0 indicate an outward unpinch (zoom in). Initial value: `1.0`.

Instance methods
----------------

*This interface also inherits methods of its parents, `UIEvent` and `Event`.*

`GestureEvent.initGestureEvent()`
Non-standard

Initializes the value of an `GestureEvent`. If the event has already been dispatched, this method does nothing.

Gesture event types
-------------------

* `gesturestart`
* `gesturechange`
* `gestureend`
Specifications
--------------

*Not part of any specification.* Apple has a description at the Safari Developer Library.

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

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


Worker - Web APIs

Worker
======

The **`Worker`** interface of the Web Workers API represents a background task that can be created via script, which can send messages back to its creator.

Creating a worker is done by calling the `Worker("path/to/worker/script")` constructor.

Workers may themselves spawn new workers, as long as those workers are hosted at the same origin as the parent page.

Note that not all interfaces and functions are available to web workers. See Functions and classes available to Web Workers for details.

EventTarget

WorkerConstructors
------------

`Worker()`

Creates a dedicated web worker that executes the script at the specified URL. This also works for Blob URLs.

Instance properties
-------------------

*Inherits properties from its parent, `EventTarget`.*

Instance methods
----------------

*Inherits methods from its parent, `EventTarget`.*

`Worker.postMessage()`

Sends a message — consisting of any JavaScript object — to the worker's inner scope.

`Worker.terminate()`

Immediately terminates the worker. This does not let worker finish its operations; it is halted at once. `ServiceWorker` instances do not support this method.

Events
------

`error`

Fires when an error occurs in the worker.

`message`

Fires when the worker's parent receives a message from that worker.

`messageerror`

Fires when a `Worker` object receives a message that can't be deserialized.

Example
-------

The following code snippet creates a `Worker` object using the `Worker()` constructor, then uses the worker object:

```js
const myWorker = new Worker("/worker.js");
const first = document.querySelector("input#number1");
const second = document.querySelector("input#number2");

first.onchange = () => {
  myWorker.postMessage([first.value, second.value]);
  console.log("Message posted to worker");
};
```

For a full example, see our Basic dedicated worker example (run dedicated worker).

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

| Specification |
| --- |
| HTML Standard # dedicated-workers-and-the-worker-interface |

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

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

Support varies for different types of workers. See each worker type's page for specifics.

### Cross-origin worker error behavior

In early versions of the spec, loading a cross-origin worker script threw a `SecurityError`. Nowadays, an `error` event is thrown instead.

See also
--------

* Using Web Workers
* Functions and classes available to Web Workers
* Other kind of workers: `SharedWorker` and Service Worker.
* `OffscreenCanvas` interface


RTCRtpReceiver - Web APIs

RTCRtpReceiver
==============

The **`RTCRtpReceiver`** interface of the WebRTC API manages the reception and decoding of data for a `MediaStreamTrack` on an `RTCPeerConnection`.

Instance properties
-------------------

`RTCRtpReceiver.track` Read only

Returns the `MediaStreamTrack` associated with the current `RTCRtpReceiver` instance.

`RTCRtpReceiver.transport` Read only

Returns the `RTCDtlsTransport` instance over which the media for the receiver's track is received.

`RTCRtpReceiver.transform`

An `RTCRtpScriptTransform` is used to insert a transform stream (`TransformStream`) running in a worker thread into the receiver pipeline, allowing stream transforms to be applied to incoming encoded video and audio frames.

### Obsolete properties

`rtcpTransport`
Deprecated

This property has been removed; the RTP and RTCP transports have been combined into a single transport. Use the `transport` property instead.

Static methods
--------------

`RTCRtpReceiver.getCapabilities()`

Returns the most optimistic view of the capabilities of the system for receiving media of the given kind.

Instance methods
----------------

`RTCRtpReceiver.getContributingSources()`

Returns an array that contains an object for each unique CSRC (contributing source) identifier received by the current `RTCRtpReceiver` in the last ten seconds.

`RTCRtpReceiver.getParameters()`

Returns an object that contains information about how the RTC data is to be decoded.

`RTCRtpReceiver.getStats()`

Returns a `Promise` whose fulfillment handler receives a `RTCStatsReport` which contains statistics about the incoming streams and their dependencies.

`RTCRtpReceiver.getSynchronizationSources()`

Returns an array that contains an object for each unique SSRC (synchronization source) identifier received by the current `RTCRtpReceiver` in the last ten seconds.

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

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # rtcrtpreceiver-interface |

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

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

See also
--------

* WebRTC
* `RTCStatsReport`
* `RTCRtpSender`
* `RTCPeerConnection.getStats()`


SVGNumberList - Web APIs

SVGNumberList
=============

SVG number list interface
-------------------------

The `SVGNumberList` defines a list of `SVGNumber` objects.

An `SVGNumberList` object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown.

An `SVGNumberList` is indexable and can be accessed like an array.

### Interface overview

|  |  |
| --- | --- |
| Also implement | None |
| Methods | * `void clear()`
* `SVGNumber`
`initialize(in `SVGNumber`
newItem)`
* `SVGNumber`
`getItem(in unsigned long index)`
* `SVGNumber`
`insertItemBefore(in `SVGNumber`
newItem, in unsigned long index)`
* `SVGNumber`
`replaceItem(in `SVGNumber`
newItem, in unsigned long index)`
* `SVGNumber`
`removeItem(in unsigned long index)`
* `SVGNumber`
`appendItem(in `SVGNumber`
newItem)`
 |
| Properties | * readonly unsigned long `numberOfItems`
* readonly unsigned long
 `length`
Non-standard
 |
| Normative document | SVG 1.1 (2nd Edition) |

Instance properties
-------------------

| Name | Type | Description |
| --- | --- | --- |
| `numberOfItems` | unsigned long | The number of items in the list. |
| `length`
Non-standard
 | unsigned long | The number of items in the list. |

Instance methods
----------------

| Name & Arguments | Return | Description |
| --- | --- | --- |
| `**clear**()` | void |
 Clears all existing current items from the list, with the result being
 an empty list.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |
| `**initialize**(in `SVGNumber`
newItem)` | `SVGNumber` |
 Clears all existing current items from the list and re-initializes the
 list to hold the single item specified by
 `newItem`. If the inserted item is already in a list, it is removed from its
 previous list before it is inserted into this list. The inserted item
 is the item itself and not a copy. The return value is the item
 inserted into the list.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |
| `**getItem**(in unsigned long index)` | `SVGNumber` |
 Returns the specified item from the list. The returned item is the
 item itself and not a copy. Any changes made to the item are
 immediately reflected in the list. The first item is
 number `0`.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |
| `**insertItemBefore**(in
`SVGNumber` newItem, in unsigned
long index)` | `SVGNumber` |
 Inserts a new item into the list at the specified position. The first
 item is number `0`.

 If `newItem` is already in a list, it is removed
 from its previous list before it is inserted into this list. The
 inserted item is the item itself and not a copy. If the item is
 already in this list, note that the index of the item to insert before
 is before the removal of the item.

 If the `index` is equal to `0`, then
 the new item is inserted at the front of the list. If the index is
 greater than or equal to `numberOfItems`, then the new item
 is appended to the end of the list.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |
| `**replaceItem**(in `SVGNumber`
newItem, in unsigned long index)` | `SVGNumber` |
 Replaces an existing item in the list with a new item. If
 `newItem` is already in a list, it is removed
 from its previous list before it is inserted into this list. The
 inserted item is the item itself and not a copy. If the item is
 already in this list, note that the index of the item to replace is
 before the removal of the item.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
* a `DOMException` with code
 `INDEX_SIZE_ERR` is raised if
 `index` is greater than or equal to `numberOfItems`.
 |
| `**removeItem**(in unsigned long index)` | `SVGNumber` | Removes an existing item from the list.
**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
* a `DOMException` with code
 `INDEX_SIZE_ERR` is raised if
 `index` is greater than or equal to `numberOfItems`.
 |
| `**appendItem**(in `SVGNumber`
newItem)` | `SVGNumber` |
 Inserts a new item at the end of the list. If
 `newItem` is already in a list, it is removed
 from its previous list before it is inserted into this list. The
 inserted item is the item itself and not a copy.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |

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

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


GPUBindGroup - Web APIs

GPUBindGroup
============

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

The **`GPUBindGroup`** interface of the WebGPU API is based on a `GPUBindGroupLayout` and defines a set of resources to be bound together in a group and how those resources are used in shader stages.

A `GPUBindGroup` object instance is created using the `GPUDevice.createBindGroup()` method.

Instance properties
-------------------

`label`
Experimental

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

Examples
--------

**Note:** The WebGPU samples feature many more examples.

### Basic example

Our basic compute demo shows an example of creating a bind group layout and then using that as a template when creating a bind group.

```js
// ...

const bindGroupLayout = device.createBindGroupLayout({
  entries: [
    {
      binding: 0,
      visibility: GPUShaderStage.COMPUTE,
      buffer: {
        type: "storage",
      },
    },
  ],
});

const bindGroup = device.createBindGroup({
  layout: bindGroupLayout,
  entries: [
    {
      binding: 0,
      resource: {
        buffer: output,
      },
    },
  ],
});

// ...
```

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

| Specification |
| --- |
| WebGPU # gpubindgroup |

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

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

See also
--------

* The WebGPU API


FileSystemEntry - Web APIs

FileSystemEntry
===============

The **`FileSystemEntry`** interface of the File and Directory Entries API represents a single entry in a file system. The entry can be a file or a directory (directories are represented by the `FileSystemDirectoryEntry` interface). It includes methods for working with files—including copying, moving, removing, and reading files—as well as information about a file it points to—including the file name and its path from the root to the entry.

Basic concepts
--------------

You don't create `FileSystemEntry` objects directly. Instead, you will receive an object based on this interface through other APIs. This interface serves as a base class for the `FileSystemFileEntry` and `FileSystemDirectoryEntry` interfaces, which provide features specific to file system entries representing files and directories, respectively.

The `FileSystemEntry` interface includes methods that you would expect for manipulating files and directories, but it also includes a convenient method for obtaining the URL of the entry: `toURL()`. It also introduces a new URL scheme: `filesystem:`.

You can use the `filesystem:` scheme on Google Chrome to see all the files and folders that are stored in the origin of your app. Just use `filesystem:` scheme for the root directory of the origin of the app. For example, if your app is in `http://www.example.com`, open `filesystem:http://www.example.com/temporary/` in a tab. Chrome shows a read-only list of all the files and folders stored the origin of your app.

### Example

To see an example of how `toURL()` works, see the method description. The snippet below shows you how you can remove a file by name.

```js
// Taking care of the browser-specific prefixes.
window.requestFileSystem =
  window.requestFileSystem || window.webkitRequestFileSystem;

// …

// Opening a file system with temporary storage
window.requestFileSystem(
  TEMPORARY,
  1024 \* 1024 /\*1MB\*/,
  (fs) => {
    fs.root.getFile(
      "log.txt",
      {},
      (fileEntry) => {
        fileEntry.remove(() => {
          console.log("File removed.");
        }, onError);
      },
      onError,
    );
  },
  onError,
);
```

Instance properties
-------------------

*This interface provides the following properties.*

`filesystem` Read only

A `FileSystem` object representing the file system in which the entry is located.

`fullPath` Read only

A string object which provides the full, absolute path from the file system's root to the entry; it can also be thought of as a path which is relative to the root directory, prepended with a "/" character.

`isDirectory` Read only

A boolean value which is `true` if the entry represents a directory; otherwise, it's `false`.

`isFile` Read only

A Boolean which is `true` if the entry represents a file. If it's not a file, this value is `false`.

`name` Read only

A string containing the name of the entry (the final part of the path, after the last "/" character).

Instance methods
----------------

*This interface defines the following methods.*

`copyTo()`
Deprecated

Non-standard

Copies the file or directory to a new location on the file system.

`getMetadata()`
Deprecated

Non-standard

Obtains metadata about the file, such as its modification date and size.

`getParent()`

Returns a `FileSystemDirectoryEntry` representing the entry's parent directory.

`moveTo()`
Deprecated

Non-standard

Moves the file or directory to a new location on the file system, or renames the file or directory.

`remove()`
Deprecated

Non-standard

Removes the specified file or directory. You can only remove directories which are empty.

`toURL()`
Deprecated

Non-standard

Creates and returns a URL which identifies the entry. This URL uses the URL scheme `"filesystem:"`.

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

| Specification |
| --- |
| File and Directory Entries API # api-entry |

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

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

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API
* `FileSystemFileEntry` and `FileSystemDirectoryEntry` are based on `FileSystemEntry`.


CSS Custom Highlight API - Web APIs

CSS Custom Highlight API
========================

The CSS Custom Highlight API provides a mechanism for styling arbitrary text ranges on a document by using JavaScript to create the ranges, and CSS to style them.

Concepts and usage
------------------

Styling text ranges on a webpage can be very useful. For example, text editing web apps highlight spelling or grammar errors, and code editors highlight syntax errors.

The CSS Custom Highlight API extends the concept of other highlight pseudo-elements such as `::selection`, `::spelling-error`, `::grammar-error`, and `::target-text` by providing a way to create and style arbitrary `Range` objects, rather than being limited to browser-defined ranges.

Using the CSS Custom Highlight API, you can programmatically create text ranges and highlight them without affecting the DOM structure in the page.

There are four steps to style text ranges on a webpage using the CSS Custom Highlight API:

1. Creating `Range` objects.
2. Creating `Highlight` objects for these ranges.
3. Registering the highlights using the `HighlightRegistry`.
4. Styling the highlights using the `::highlight()` pseudo-element.
### Create ranges

The first step is to define the text ranges that you want to style by creating `Range` objects in JavaScript. For example:

```js
const parentNode = document.getElementById("foo");

const range1 = new Range();
range1.setStart(parentNode, 10);
range1.setEnd(parentNode, 20);

const range2 = new Range();
range2.setStart(parentNode, 40);
range2.setEnd(parentNode, 60);
```

### Create highlights

The second step is to instantiate `Highlight` objects for your text ranges.

Multiple ranges can be associated to one highlight. If you want to highlight multiple pieces of text the same way, you need to create a single highlight and initialize it with the corresponding ranges.

```js
const highlight = new Highlight(range1, range2);
```

But you can also create as many highlights as you need. For example, if you are building a collaborative text editor where each user gets a different text color, then you can create one highlight per user, as seen in the code snippet below:

```js
const user1Highlight = new Highlight(user1Range1, user1Range2);
const user2Highlight = new Highlight(user2Range1, user2Range2, user2Range3);
```

Each highlight can be styled differently.

### Register highlights

Once highlights have been created, register them by using the `HighlightRegistry` available as `CSS.highlights`.

The registry is a `Map`-like object used to register highlights by names, as seen below:

```js
CSS.highlights.set("user-1-highlight", user1Highlight);
CSS.highlights.set("user-2-highlight", user2Highlight);
```

In the above code snippet, the `user-1-highlight` and `user-2-highlight` strings are custom identifiers that can be used in CSS to apply styles to the registered highlights.

You can register as many highlights as you need in the registry, as well as remove highlights and clear the entire registry.

```js
// Remove a single highlight from the registry.
CSS.highlights.delete("user-1-highlight");

// Clear the registry.
CSS.highlights.clear();
```

### Style highlights

The final step is to style the registered highlights. This is done by using the `::highlight()` pseudo-element. For example, to style the `user-1-highlight` highlight registered in the previous step:

```css
::highlight(user-1-highlight) {
  background-color: yellow;
  color: black;
}
```

Interfaces
----------

`Highlight`

This interface is used to represent a collection of ranges to be styled on a document.

`HighlightRegistry`

Accessible via `CSS.highlights`, this `Map`-like object is used to register highlights with custom identifiers.

Examples
--------

### Highlighting search results

This example shows how to use the CSS Custom Highlight API to highlight search results.

#### HTML

The HTML code snippet below defines a search field and an article with a few paragraphs of text:

```html
<label>Search within text <input id="query" type="text" /></label>
<article>
  <p>
    Maxime debitis hic, delectus perspiciatis laborum molestiae labore,
    deleniti, quam consequatur iure veniam alias voluptas nisi quo. Dolorem
    eaque alias, quo vel quas repudiandae architecto deserunt quidem, sapiente
    laudantium nulla.
  </p>
  <p>
    Maiores odit molestias, necessitatibus doloremque dolor illum reprehenderit
    provident nostrum laboriosam iste, tempore perferendis! Ab porro neque esse
    voluptas libero necessitatibus fugiat, ex, minus atque deserunt veniam
    molestiae tempora? Vitae.
  </p>
  <p>
    Dolorum facilis voluptate eaque eius similique ducimus dignissimos assumenda
    quos architecto. Doloremque deleniti non exercitationem rerum quam alias
    harum, nisi obcaecati corporis temporibus vero sapiente voluptatum est
    quibusdam id ipsa.
  </p>
</article>
```

#### JavaScript

JavaScript is used to listen to the `input` event on the search field. When the event is fired, the code locates matches for the input text in the article text. It then creates ranges for the matches, and uses the CSS Custom Highlight API to create and register a `search-results` highlight object:

```js
const query = document.getElementById("query");
const article = document.querySelector("article");

// Find all text nodes in the article. We'll search within
// these text nodes.
const treeWalker = document.createTreeWalker(article, NodeFilter.SHOW\_TEXT);
const allTextNodes = [];
let currentNode = treeWalker.nextNode();
while (currentNode) {
  allTextNodes.push(currentNode);
  currentNode = treeWalker.nextNode();
}

// Listen to the input event to run the search.
query.addEventListener("input", () => {
  // If the CSS Custom Highlight API is not supported,
  // display a message and bail-out.
  if (!CSS.highlights) {
    article.textContent = "CSS Custom Highlight API not supported.";
    return;
  }

  // Clear the HighlightRegistry to remove the
  // previous search results.
  CSS.highlights.clear();

  // Clean-up the search query and bail-out if
  // if it's empty.
  const str = query.value.trim().toLowerCase();
  if (!str) {
    return;
  }

  // Iterate over all text nodes and find matches.
  const ranges = allTextNodes
    .map((el) => {
      return { el, text: el.textContent.toLowerCase() };
    })
    .map(({ text, el }) => {
      const indices = [];
      let startPos = 0;
      while (startPos < text.length) {
        const index = text.indexOf(str, startPos);
        if (index === -1) break;
        indices.push(index);
        startPos = index + str.length;
      }

      // Create a range object for each instance of
      // str we found in the text node.
      return indices.map((index) => {
        const range = new Range();
        range.setStart(el, index);
        range.setEnd(el, index + str.length);
        return range;
      });
    });

  // Create a Highlight object for the ranges.
  const searchResultsHighlight = new Highlight(...ranges.flat());

  // Register the Highlight object in the registry.
  CSS.highlights.set("search-results", searchResultsHighlight);
});
```

#### CSS

Finally, the `::highlight()` pseudo-element is used in CSS to style the highlights:

```css
::highlight(search-results) {
  background-color: #f06;
  color: white;
}
```

#### Result

The result is shown below. Type text within the search field to highlight matches in the article:

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

| Specification |
| --- |
| CSS Custom Highlight API Module Level 1  |

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

### api.Highlight

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

### api.HighlightRegistry

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

### css.selectors.highlight

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

See also
--------

* CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web


CSSStartingStyleRule - Web APIs

CSSStartingStyleRule
====================

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

The **`CSSStartingStyleRule`** interface of the CSS Object Model represents a CSS `@starting-style` at-rule.

CSSRule

CSSGroupingRule

CSSStartingStyleRuleInstance properties
-------------------

*This interface inherits properties from its parent, `CSSGroupingRule`.*

Instance methods
----------------

*This interface inherits methods from its parent, `CSSGroupingRule`.*

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

| Specification |
| --- |
| CSS Transitions Level 2 # the-cssstartingstylerule-interface |

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

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

See also
--------

* `@starting-style`
* CSS transitions module
* Using dynamic styling information


Streams API - Web APIs

Streams API
===========

The Streams API allows JavaScript to programmatically access streams of data received over the network and process them as desired by the developer.

**Note:** This feature is available in Web Workers

Concepts and usage
------------------

Streaming involves breaking a resource that you want to receive over a network down into small chunks, then processing it bit by bit. Browsers already do this when receiving media assets — videos buffer and play as more of the content downloads, and sometimes you'll see images display gradually as more is loaded too.

But this capability has never been available to JavaScript before. Previously, if we wanted to process a resource of some kind (video, text file, etc.), we'd have to download the entire file, wait for it to be deserialized into a suitable format, then process all the data.

With the Streams API, you can start processing raw data with JavaScript bit by bit, as soon as it is available, without needing to generate a buffer, string, or blob.

![The basic concept of the stream API is data is fetched from the network in several data packets. The data is processed, and then sent to the browser in a stream of data packets.](/en-US/docs/Web/API/Streams_API/concept.png)

There are more advantages too — you can detect when streams start or end, chain streams together, handle errors and cancel streams as required, and react to the speed at which the stream is being read.

The usage of Streams hinges on making responses available as streams. For example, the response body returned by a successful fetch request is a `ReadableStream` that can be read by a reader created with `ReadableStream.getReader()`.

More complicated uses involve creating your own stream using the `ReadableStream()` constructor, for example to process data inside a service worker.

You can also write data to streams using `WritableStream`.

**Note:** You can find a lot more details about the theory and practice of streams in our articles — Streams API concepts, Using readable streams, Using readable byte streams, and Using writable streams.

Stream interfaces
-----------------

### Readable streams

`ReadableStream`

Represents a readable stream of data. It can be used to handle response streams of the Fetch API, or developer-defined streams (e.g. a custom `ReadableStream()` constructor).

`ReadableStreamDefaultReader`

Represents a default reader that can be used to read stream data supplied from a network (e.g. a fetch request).

`ReadableStreamDefaultController`

Represents a controller allowing control of a `ReadableStream`'s state and internal queue. Default controllers are for streams that are not byte streams.

### Writable streams

`WritableStream`

Provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing.

`WritableStreamDefaultWriter`

Represents a default writable stream writer that can be used to write chunks of data to a writable stream.

`WritableStreamDefaultController`

Represents a controller allowing control of a `WritableStream`'s state. When constructing a `WritableStream`, the underlying sink is given a corresponding `WritableStreamDefaultController` instance to manipulate.

### Transform Streams

`TransformStream`

Represents an abstraction for a stream object that transforms data as it passes through a pipe chain of stream objects.

`TransformStreamDefaultController`

Provides methods to manipulate the `ReadableStream` and `WritableStream` associated with a transform stream.

### Related stream APIs and operations

`ByteLengthQueuingStrategy`

Provides a built-in byte length queuing strategy that can be used when constructing streams.

`CountQueuingStrategy`

Provides a built-in chunk counting queuing strategy that can be used when constructing streams.

### Extensions to other APIs

`Request`

When a new `Request` object is constructed, you can pass it a `ReadableStream` in the `body` property of its `RequestInit` dictionary. This `Request` could then be passed to a `fetch()` to commence fetching the stream.

`Response.body`

The response body returned by a successful fetch request is exposed by default as a `ReadableStream`, and can have a reader attached to it, etc.

### ByteStream-related interfaces

`ReadableStreamBYOBReader`

Represents a BYOB ("bring your own buffer") reader that can be used to read stream data supplied by the developer (e.g. a custom `ReadableStream()` constructor).

`ReadableByteStreamController`

Represents a controller allowing control of a `ReadableStream`'s state and internal queue. Byte stream controllers are for byte streams.

`ReadableStreamBYOBRequest`

Represents a pull into request in a `ReadableByteStreamController`.

Examples
--------

We have created a directory of examples to go along with the Streams API documentation — see mdn/dom-examples/streams. The examples are as follows:

* Simple stream pump: This example shows how to consume a ReadableStream and pass its data to another.
* Grayscale a PNG: This example shows how a ReadableStream of a PNG can be turned into grayscale.
* Simple random stream: This example shows how to use a custom stream to generate random strings, enqueue them as chunks, and then read them back out again.
* Simple tee example: This example extends the Simple random stream example, showing how a stream can be teed and both resulting streams can be read independently.
* Simple writer: This example shows how to write to a writable stream, then decode the stream and write the contents to the UI.
* Unpack chunks of a PNG: This example shows how `pipeThrough()` can be used to transform a ReadableStream into a stream of other data types by transforming a data of a PNG file into a stream of PNG chunks.

Examples from other developers:

* Progress Indicators with Streams, Service Workers, & Fetch.
Specifications
--------------

| Specification |
| --- |
| Streams Standard # rs-class |
| Streams Standard # ws-class |

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

### api.ReadableStream

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

### api.WritableStream

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

See also
--------

* Streams API concepts
* Using readable streams
* Using readable byte streams
* Using writable streams


InputEvent - Web APIs

InputEvent
==========

Baseline 2023
-------------

Newly availableSince March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Learn more
* See full compatibility
* Report feedback
The **`InputEvent`** interface represents an event notifying the user of editable content changes.

Event

UIEvent

InputEventConstructor
-----------

`InputEvent()`

Creates an `InputEvent` object.

Instance properties
-------------------

*This interface inherits properties from its parents, `UIEvent` and `Event`.*

`InputEvent.data` Read only

Returns a string with the inserted characters. This may be an empty string if the change doesn't insert text (for example, when deleting characters).

`InputEvent.dataTransfer` Read only

Returns a `DataTransfer` object containing information about richtext or plaintext data being added to or removed from editable content.

`InputEvent.inputType` Read only

Returns the type of change for editable content such as, for example, inserting, deleting, or formatting text.

`InputEvent.isComposing` Read only

Returns a `Boolean` value indicating if the event is fired after `compositionstart` and before `compositionend`.

Instance methods
----------------

*This interface inherits methods from its parents, `UIEvent` and `Event`.*

`InputEvent.getTargetRanges()`

Returns an array of static ranges that will be affected by a change to the DOM if the input event is not canceled.

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

| Specification |
| --- |
| Input Events Level 2 # interface-InputEvent |
| UI Events # interface-inputevent |

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

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

See also
--------

* `beforeinput` event
* `input` event


TrustedTypePolicyFactory - Web APIs

TrustedTypePolicyFactory
========================

The **`TrustedTypePolicyFactory`** interface of the `Trusted Types API` creates policies and allows the verification of Trusted Type objects against created policies.

Instance properties
-------------------

`TrustedTypePolicyFactory.emptyHTML` Read only

Returns a `TrustedHTML` object containing an empty string.

`TrustedTypePolicyFactory.emptyScript` Read only

Returns a `TrustedScript` object containing an empty string.

`TrustedTypePolicyFactory.defaultPolicy` Read only

Returns the default `TrustedTypePolicy` or null if this is empty.

Instance methods
----------------

`TrustedTypePolicyFactory.createPolicy()`

Creates a `TrustedTypePolicy` object that implements the rules passed as `policyOptions`.

`TrustedTypePolicyFactory.isHTML()`

When passed a value checks that it is a valid `TrustedHTML` object.

`TrustedTypePolicyFactory.isScript()`

When passed a value checks that it is a valid `TrustedScript` object.

`TrustedTypePolicyFactory.isScriptURL()`

When passed a value checks that it is a valid `TrustedScriptURL` object.

`TrustedTypePolicyFactory.getAttributeType()`

Allows web developers to check whether a Trusted Type is required for an element and attribute, and if so which one.

`TrustedTypePolicyFactory.getPropertyType()`

Allows web developers to check whether a Trusted Type is required for a property, and if so which one.

Examples
--------

The below code creates a policy with the name `"myEscapePolicy"` with a function defined for `createHTML()` which sanitizes HTML.

We then use the policy to sanitize a string, creating a `TrustedHTML` object, `escaped`. This object can be tested with `isHTML()` to ensure that it was created by one of our policies.

```js
const escapeHTMLPolicy = trustedTypes.createPolicy("myEscapePolicy", {
  createHTML: (string) => string.replace(/>/g, "<"),
});

const escaped = escapeHTMLPolicy.createHTML("<img src=x onerror=alert(1)>");

console.log(trustedTypes.isHTML(escaped)); // true;
```

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

| Specification |
| --- |
| Trusted Types # trusted-type-policy-factory |

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

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


SharedStorage - Web APIs

SharedStorage
=============

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

The **`SharedStorage`** interface of the Shared Storage API represents the shared storage for a particular origin, defining methods to write data to the shared storage.

`SharedStorage` is the base class for:

* `WindowSharedStorage`, accessed via `Window.sharedStorage`.
* `WorkletSharedStorage`, accessed via `SharedStorageWorkletGlobalScope.sharedStorage`.
Instance methods
----------------

`append()`
Experimental

Appends a string to the value of an existing key-value pair in the current origin's shared storage.

`clear()`
Experimental

Clears the current origin's shared storage, removing all data from it.

`delete()`
Experimental

Deletes an existing key-value pair from the current origin's shared storage.

`set()`
Experimental

Stores a new key-value pair in the current origin's shared storage or updates an existing one.

Examples
--------

```js
window.sharedStorage
  .set("ab-testing-group", "0")
  .then(console.log("Value saved to shared storage"));
```

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

| Specification |
| --- |
| Shared Storage API # sharedstorage |

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

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

See also
--------

* `WindowSharedStorage`
* Shared Storage API


WebGLObject - Web APIs

WebGLObject
===========

The **`WebGLObject`** is part of the WebGL API and is the parent interface for all WebGL objects.

This object has no public properties or methods on its own.

If the WebGL context is lost, the internal *invalidated* flag of all `WebGLObject` instances is set to `true`.

Objects inheriting from `WebGLObject`
-------------------------------------

WebGL 1:

* `WebGLBuffer`
* `WebGLFramebuffer`
* `WebGLProgram`
* `WebGLRenderbuffer`
* `WebGLShader`
* `WebGLTexture`

WebGL 2:

* `WebGLQuery` (and `WebGLTimerQueryEXT`)
* `WebGLSampler`
* `WebGLSync`
* `WebGLTransformFeedback`
* `WebGLVertexArrayObject` (and `WebGLVertexArrayObjectOES`)
See also
--------

* `WebGLRenderingContext.isContextLost()`
* `WEBGL_lose_context`
* `webglcontextlost` event