FontData: family property - Web APIs

FontData: family property
=========================

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

The **`family`** read-only property of the `FontData` interface returns the family of the font face.

This is the name used when referring to the font family from code, for example, in the `font-family` property or in places within the `@font-face` at-rule such as the `local()` function.

Examples include:

* Apple SD Gothic Neo
* Arial Black
* Avenir Next
* Katari
* YuMincho +36p Kana
Value
-----

A string.

Examples
--------

The following snippet will query for all available fonts, and log metadata. This could be used, for example, to populate a font-picker control.

```js
async function logFontData() {
  try {
    const availableFonts = await window.queryLocalFonts();
    for (const fontData of availableFonts) {
      console.log(fontData.postscriptName);
      console.log(fontData.fullName);
      console.log(fontData.family);
      console.log(fontData.style);
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}
```

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

| Specification |
| --- |
| Local Font Access # ref-for-dom-fontdata-family |

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

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

See also
--------

* Use advanced typography with local fonts
* `@font-face`


InterventionReportBody: lineNumber property - Web APIs

InterventionReportBody: lineNumber property
===========================================

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

The **`lineNumber`** read-only property of the `InterventionReportBody` interface returns the line in the source file in which the intervention occurred.

**Note:** This property is most useful alongside `InterventionReportBody.sourceFile` as it enables the location of the line in that file where the feature is used.

Value
-----

An integer, or `null` if the line is not known.

Examples
--------

In this example we create a new `ReportingObserver` to observe intervention reports, then print the value of `lineNumber` to the console.

```js
const options = {
  types: ["intervention"],
  buffered: true,
};

const observer = new ReportingObserver((reports, observer) => {
  const firstReport = reports[0];
  console.log(firstReport.type); // intervention
  console.log(firstReport.body.sourceFile); // the source file
  console.log(firstReport.body.lineNumber); // the line in that file
}, options);
```

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

| Specification |
| --- |
| Intervention Reporting # dom-interventionreportbody-linenumber |

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

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


InterventionReportBody: columnNumber property - Web APIs

InterventionReportBody: columnNumber property
=============================================

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

The **`columnNumber`** read-only property of the `InterventionReportBody` interface returns the line in the source file in which the intervention occurred.

**Note:** This property is most useful alongside `InterventionReportBody.sourceFile` and `InterventionReportBody.lineNumber` as it enables the location of the column in that file and line where the feature is used.

Value
-----

An integer, or `null` if the column is not known.

Examples
--------

In this example we create a new `ReportingObserver` to observe intervention reports, then print the value of `columnNumber` to the console.

```js
const options = {
  types: ["intervention"],
  buffered: true,
};

const observer = new ReportingObserver((reports, observer) => {
  const firstReport = reports[0];
  console.log(firstReport.type); // intervention
  console.log(firstReport.body.sourceFile); // the source file
  console.log(firstReport.body.lineNumber); // the line in that file
  console.log(firstReport.body.columnNumber); // the column in that file.
}, options);
```

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

| Specification |
| --- |
| Intervention Reporting # dom-interventionreportbody-columnnumber |

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

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


InterventionReportBody: id property - Web APIs

InterventionReportBody: id property
===================================

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

The **`id`** read-only property of the `InterventionReportBody` interface returns a string identifying the intervention that generated the report. This can be used to group reports.

Value
-----

A string.

Examples
--------

In this example we create a new `ReportingObserver` to observe intervention reports, then print the value of `id` to the console.

```js
const options = {
  types: ["intervention"],
  buffered: true,
};

const observer = new ReportingObserver((reports, observer) => {
  const firstReport = reports[0];
  console.log(firstReport.type); // intervention
  console.log(firstReport.body.id);
}, options);
```

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

| Specification |
| --- |
| Intervention Reporting # dom-interventionreportbody-id |

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

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


InterventionReportBody: toJSON() method - Web APIs

InterventionReportBody: toJSON() method
=======================================

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

The **`toJSON()`** method of the `InterventionReportBody` interface is a *serializer*, and returns a JSON representation of the `InterventionReportBody` object.

Syntax
------

```js
toJSON()
```

### Parameters

None.

### Return value

A JSON object that is the serialization of the `InterventionReportBody` object.

Examples
--------

In this example we create a new `ReportingObserver` to observe intervention reports, then return a JSON representation of the first entry.

```js
const options = {
  types: ["intervention"],
  buffered: true,
};

const observer = new ReportingObserver((reports, observer) => {
  const firstReport = reports[0];
  console.log(firstReport.toJSON());
}, options);
```

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

| Specification |
| --- |
| Intervention Reporting # dom-interventionreportbody-tojson |

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

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


InterventionReportBody: sourceFile property - Web APIs

InterventionReportBody: sourceFile property
===========================================

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

The **`sourceFile`** read-only property of the `InterventionReportBody` interface returns the path to the source file where the intervention occurred.

**Note:** This property can be used with `InterventionReportBody.lineNumber` and `InterventionReportBody.columnNumber` to locate the column and line in the file where the feature is used.

Value
-----

A string, or `null` if the path is not known.

Examples
--------

In this example we create a new `ReportingObserver` to observe intervention reports, then print the value of `sourceFile` to the console.

```js
const options = {
  types: ["intervention"],
  buffered: true,
};

const observer = new ReportingObserver((reports, observer) => {
  const firstReport = reports[0];
  console.log(firstReport.type); // intervention
  console.log(firstReport.body.sourceFile);
}, options);
```

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

| Specification |
| --- |
| Intervention Reporting # dom-interventionreportbody-sourcefile |

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

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


InterventionReportBody: message property - Web APIs

InterventionReportBody: message property
========================================

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

The **`message`** read-only property of the `InterventionReportBody` interface returns a human-readable description of the intervention, including information such as how the intervention could be avoided. This typically matches the message a browser will display in its DevTools console when an intervention is imposed, if one is available.

Value
-----

A string.

Examples
--------

In this example we create a new `ReportingObserver` to observe intervention reports, then print the value of `message` to the console.

```js
const options = {
  types: ["intervention"],
  buffered: true,
};

const observer = new ReportingObserver((reports, observer) => {
  const firstReport = reports[0];
  console.log(firstReport.type); // intervention
  console.log(firstReport.body.message);
}, options);
```

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

| Specification |
| --- |
| Intervention Reporting # dom-interventionreportbody-message |

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

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


GPUCanvasContext: configure() method - Web APIs

GPUCanvasContext: configure() method
====================================

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

 The **`configure()`** method of the
 `GPUCanvasContext` interface configures the context to use for rendering with a given `GPUDevice`. When called the canvas will initially be cleared to transparent black.

Syntax
------

```js
configure(configuration)
```

### Parameters

`configuration`

An object containing the following properties:

`alphaMode` Optional

An enumerated value that specifies the effect that alpha values will have on the content of textures returned by `getCurrentTexture()` when read, displayed, or used as an image source. Possible values are:

* `opaque`: Alpha values are ignored — if a texture is not already opaque, the alpha channel is cleared to 1.0 when it is used as an image source or displayed to the screen. This is the default value.
* `premultiplied`: Color values are premultiplied by their alpha value. For example, 100% red at 50% alpha is `[0.5, 0, 0, 0.5]`.

`colorSpace` Optional

The color space that values written into textures returned by `getCurrentTexture()` should be displayed with. Possible values are `srgb` (the default) and `display-p3`.

`device`

The `GPUDevice` that the rendering information for the context will come from.

`format`

The format that textures returned by `getCurrentTexture()` will have. This can be `bgra8unorm`, `rgba8unorm`, or `rgba16float`. The optimal canvas texture format for the current system can be returned by `GPU.getPreferredCanvasFormat()`. Using this is recommended — if you don't use the preferred format when configuring the canvas context, you may incur additional overhead, such as additional texture copies, depending on the platform.

`usage` Optional

Bitwise flags specifying the allowed usage for textures returned by `getCurrentTexture()`. Possible values are:

* `GPUTextureUsage.COPY_SRC`: The texture can be used as the source of a copy operation, for example the source argument of a `GPUCommandEncoder.copyTextureToBuffer()` call.
* `GPUTextureUsage.COPY_DST`: The texture can be used as the destination of a copy/write operation, for example the destination argument of a `GPUCommandEncoder.copyTextureToTexture()` call.
* `GPUTextureUsage.RENDER_ATTACHMENT`: The texture can be used as a color attachment in a render pass, for example in a color attachment view in a `GPUCommandEncoder.beginRenderPass()` call. `GPUTextureUsage.RENDER_ATTACHMENT` is the default `usage`, but note that it is not automatically included if a different value is explicitly set; in such cases you need to include it in addition.
* `GPUTextureUsage.TEXTURE_BINDING`: The texture can be bound for use as a sampled texture in a shader, for example in a bind group entry in a `GPUDevice.createBindGroup()` call.
* `GPUTextureUsage.STORAGE_BINDING`: The texture can be bound for use as a storage texture in a shader, for example in a bind group entry in a `GPUDevice.createBindGroup()` call.

Note that multiple possible usages can be specified using the bitwise OR operator. For example, `usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.RENDER_ATTACHMENT`.

`viewFormats` Optional

An array of formats that views created from textures returned by `getCurrentTexture()` may use. See Texture Formats for all the possible values.

### Return value

None (`undefined`).

Examples
--------

```js
const canvas = document.querySelector("#gpuCanvas");
const context = canvas.getContext("webgpu");

context.configure({
  device: device,
  format: navigator.gpu.getPreferredCanvasFormat(),
  alphaMode: "premultiplied",
});
```

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

| Specification |
| --- |
| WebGPU # dom-gpucanvascontext-configure |

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

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

See also
--------

* The WebGPU API


GPUCanvasContext: canvas property - Web APIs

GPUCanvasContext: canvas property
=================================

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

 The **`canvas`** read-only property of the
 `GPUCanvasContext` interface returns a reference to the canvas that the context was created from.

Value
-----

An `HTMLCanvasElement` or `OffscreenCanvas` object instance.

Examples
--------

```js
const canvas = document.querySelector("#gpuCanvas");
const context = canvas.getContext("webgpu");

// returns an HTMLCanvasElement reference
context.canvas;
```

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

| Specification |
| --- |
| WebGPU # dom-gpucanvascontext-canvas |

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

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

See also
--------

* The WebGPU API


GPUCanvasContext: getCurrentTexture() method - Web APIs

GPUCanvasContext: getCurrentTexture() method
============================================

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

 The **`getCurrentTexture()`** method of the
 `GPUCanvasContext` interface returns the next `GPUTexture` to be composited to the document by the canvas context.

Syntax
------

```js
getCurrentTexture()
```

### Parameters

None.

### Return value

A `GPUTexture` object instance.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if `getCurrentTexture()` is called on the canvas context before it is configured (i.e. before `GPUCanvasContext.configure()` has been called).

Examples
--------

```js
const canvas = document.querySelector("#gpuCanvas");
const context = canvas.getContext("webgpu");

context.configure({
  device: device,
  format: navigator.gpu.getPreferredCanvasFormat(),
  alphaMode: "premultiplied",
});

//...
// Later on
const commandEncoder = device.createCommandEncoder();

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

const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
```

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

| Specification |
| --- |
| WebGPU # dom-gpucanvascontext-getcurrenttexture |

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

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

See also
--------

* The WebGPU API


GPUCanvasContext: unconfigure() method - Web APIs

GPUCanvasContext: unconfigure() method
======================================

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

 The **`unconfigure()`** method of the
 `GPUCanvasContext` interface removes any previously-set context configuration, and destroys any textures returned via `getCurrentTexture()` while the canvas context was configured.

Syntax
------

```js
unconfigure()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
const canvas = document.querySelector("#gpuCanvas");
const context = canvas.getContext("webgpu");

context.configure({
  device: device,
  format: navigator.gpu.getPreferredCanvasFormat(),
  alphaMode: "premultiplied",
});

// Later on
context.unconfigure();
```

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

| Specification |
| --- |
| WebGPU # dom-gpucanvascontext-unconfigure |

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

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

See also
--------

* The WebGPU API


AmbientLightSensor: illuminance property - Web APIs

AmbientLightSensor: illuminance property
========================================

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

The **`illuminance`** property of the `AmbientLightSensor` interface returns the current light level in lux of the ambient light level around the hosting device.

Value
-----

A `Number` indicating the current light level in lux.

Examples
--------

```js
if ("AmbientLightSensor" in window) {
  const sensor = new AmbientLightSensor();
  sensor.addEventListener("reading", (event) => {
    console.log("Current light level:", sensor.illuminance);
  });
  sensor.addEventListener("error", (event) => {
    console.log(event.error.name, event.error.message);
  });
  sensor.start();
}
```

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

| Specification |
| --- |
| Ambient Light Sensor # ambient-light-sensor-reading-attribute |

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

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


AmbientLightSensor: AmbientLightSensor() constructor - Web APIs

AmbientLightSensor: AmbientLightSensor() constructor
====================================================

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

The **`AmbientLightSensor()`** constructor creates a new `AmbientLightSensor` object, which returns the current light level or illuminance of the ambient light around the hosting device.

Syntax
------

```js
new AmbientLightSensor()
new AmbientLightSensor(options)
```

### Parameters

`options` Optional

Currently only one option is supported:

`frequency`

The desired number of times per second a sample should be taken, meaning the number of times per second that `reading` event will be called. A whole number or decimal may be used, the latter for frequencies less than a second. The actual reading frequency depends on the device hardware and consequently may be less than requested.

### Exceptions

`SecurityError` `DOMException`

Use of this feature was blocked by a Permissions Policy.

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

| Specification |
| --- |
| Ambient Light Sensor # dom-ambientlightsensor-ambientlightsensor |

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

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

See also
--------

* `reading` event


GainNode: GainNode() constructor - Web APIs

GainNode: GainNode() constructor
================================

 The **`GainNode()`** constructor of the Web Audio API creates a new
 `GainNode` object which is an `AudioNode` that represents a
 change in volume.

Syntax
------

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

### Parameters

`context`

A reference to a `BaseAudioContext`, e.g. an `AudioContext`.

`options` Optional

Options are as follows:

`gain`

 The amount of gain to apply. This parameter is a- `rate`
 and it's nominal range is (-∞,+∞). The default is `1`.

`channelCount`

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

`channelCountMode`

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

`channelInterpretation`

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

### Return value

A new `GainNode` object instance.

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

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

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

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


GainNode: gain property - Web APIs

GainNode: gain property
=======================

The `gain` property of the `GainNode` interface is an a-rate `AudioParam` representing the amount of gain to apply.

Value
-----

An `AudioParam`.

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

Examples
--------

See `BaseAudioContext.createGain()` for example code showing how to use an `AudioContext` to create a `GainNode`, which is then used to mute and unmute the audio by changing the gain property value.

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

| Specification |
| --- |
| Web Audio API # dom-gainnode-gain |

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

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

See also
--------

* Using the Web Audio API


AudioWorkletGlobalScope: currentFrame property - Web APIs

AudioWorkletGlobalScope: currentFrame property
==============================================

The read-only **`currentFrame`** property of the `AudioWorkletGlobalScope` interface returns an integer that represents the ever-increasing current sample-frame of the audio block being processed. It is incremented by 128 (the size of a render quantum) after the processing of each audio block.

Value
-----

An integer number.

Examples
--------

The `AudioWorkletProcessor` has access to the specific `AudioWorkletGlobalScope` properties:

```js
// AudioWorkletProcessor defined in : test-processor.js
class TestProcessor extends AudioWorkletProcessor {
  constructor() {
    super();

    // Logs the current sample-frame and time at the moment of instantiation.
    // They are accessible from the AudioWorkletGlobalScope.
    console.log(currentFrame);
    console.log(currentTime);
  }

  // The process method is required - output silence,
  // which the outputs are already filled with.
  process(inputs, outputs, parameters) {
    return true;
  }
}

// Logs the sample rate, that is not going to change ever,
// because it's a read-only property of a BaseAudioContext
// and is set only during its instantiation.
console.log(sampleRate);

// You can declare any variables and use them in your processors
// for example it may be an ArrayBuffer with a wavetable.
const usefulVariable = 42;
console.log(usefulVariable);

registerProcessor("test-processor", TestProcessor);
```

The main script loads the processor, creates an instance of `AudioWorkletNode`, passes the name of the processor to it, and connects the node to an audio graph. We should see the output of `console.log()` calls in the console:

```js
const audioContext = new AudioContext();
await audioContext.audioWorklet.addModule("test-processor.js");
const testNode = new AudioWorkletNode(audioContext, "test-processor");
testNode.connect(audioContext.destination);
```

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

| Specification |
| --- |
| Web Audio API # dom-audioworkletglobalscope-currentframe |

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

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

See also
--------

* Web Audio API
* Using the Web Audio API


AudioWorkletGlobalScope: sampleRate property - Web APIs

AudioWorkletGlobalScope: sampleRate property
============================================

The read-only **`sampleRate`** property of the `AudioWorkletGlobalScope` interface returns a float that represents the sample rate of the associated `BaseAudioContext` the worklet belongs to.

Value
-----

A floating-point number representing the associated sample rate.

Examples
--------

The `AudioWorkletProcessor` has access to the specific `AudioWorkletGlobalScope` properties:

```js
// AudioWorkletProcessor defined in : test-processor.js
class TestProcessor extends AudioWorkletProcessor {
  constructor() {
    super();

    // Logs the current sample-frame and time at the moment of instantiation.
    // They are accessible from the AudioWorkletGlobalScope.
    console.log(currentFrame);
    console.log(currentTime);
  }

  // The process method is required - output silence,
  // which the outputs are already filled with.
  process(inputs, outputs, parameters) {
    return true;
  }
}

// Logs the sample rate, that is not going to change ever,
// because it's a read-only property of a BaseAudioContext
// and is set only during its instantiation.
console.log(sampleRate);

// You can declare any variables and use them in your processors
// for example it may be an ArrayBuffer with a wavetable.
const usefulVariable = 42;
console.log(usefulVariable);

registerProcessor("test-processor", TestProcessor);
```

The main script loads the processor, creates an instance of `AudioWorkletNode`, passes the name of the processor to it, and connects the node to an audio graph. We should see the output of `console.log()` calls in the console:

```js
const audioContext = new AudioContext();
await audioContext.audioWorklet.addModule("test-processor.js");
const testNode = new AudioWorkletNode(audioContext, "test-processor");
testNode.connect(audioContext.destination);
```

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

| Specification |
| --- |
| Web Audio API # dom-audioworkletglobalscope-samplerate |

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

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

See also
--------

* Web Audio API
* Using the Web Audio API


AudioWorkletGlobalScope: registerProcessor() method - Web APIs

AudioWorkletGlobalScope: registerProcessor() method
===================================================

 The **`registerProcessor`** method of the
 `AudioWorkletGlobalScope` interface registers a class constructor derived
 from `AudioWorkletProcessor` interface under a specified *name*.

Syntax
------

```js
registerProcessor(name, processorCtor)
```

### Parameters

`name`

A string representing the name under which the processor will be registered.

`processorCtor`

The constructor of a class derived from `AudioWorkletProcessor`.

**Note:** A key-value pair `{ name: constructor }`
 is saved internally in the `AudioWorkletGlobalScope` once the processor
 is registered. The *name* is to be referred to when creating an
 `AudioWorkletNode` based on the registered processor. A new processor by
 the given name is internally created and associated with the new node.

### Return value

None (`undefined`).

### Exceptions

`NotSupportedError` `DOMException`

Thrown under the following conditions:

* The *name* is an empty string.
* A constructor under the given *name* is already registered. Registering
 the same name twice is not allowed.

`TypeError`

Thrown under the following conditions:

* The *processorCtor* is not a callable constructor.
* The `parameterDescriptors` property of the constructor exists and doesn't return an
 array of `AudioParamDescriptor`-based objects.

Examples
--------

In this example we create a custom `AudioWorkletNode` that outputs silence.

 First, we need to define a custom `AudioWorkletProcessor` and register it.
 Note that this should be done in a separate file.

```js
// test-processor.js
class TestProcessor extends AudioWorkletProcessor {
  process(inputs, outputs, parameters) {
    return true;
  }
}

registerProcessor("test-processor", TestProcessor);
```

 Next, in our main script file we'll load the processor, create an instance of
 `AudioWorkletNode` — passing it the processor name that we used when calling
 `registerProcessor` — and connect it to an audio graph.

```js
const audioContext = new AudioContext();
await audioContext.audioWorklet.addModule("test-processor.js");
const node = new AudioWorkletNode(audioContext, "test-processor");
node.connect(audioContext.destination);
```

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

| Specification |
| --- |
| Web Audio API # dom-audioworkletglobalscope-registerprocessor |

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

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

See also
--------

* Using the Web Audio API


AudioWorkletGlobalScope: currentTime property - Web APIs

AudioWorkletGlobalScope: currentTime property
=============================================

The read-only **`currentTime`** property of the `AudioWorkletGlobalScope` interface returns a double that represents the ever-increasing context time of the audio block being processed. It is equal to the `currentTime` property of the `BaseAudioContext` the worklet belongs to.

Value
-----

A floating-point number representing the time.

Examples
--------

The `AudioWorkletProcessor` has access to the specific `AudioWorkletGlobalScope` properties:

```js
// AudioWorkletProcessor defined in : test-processor.js
class TestProcessor extends AudioWorkletProcessor {
  constructor() {
    super();

    // Logs the current sample-frame and time at the moment of instantiation.
    // They are accessible from the AudioWorkletGlobalScope.
    console.log(currentFrame);
    console.log(currentTime);
  }

  // The process method is required - output silence,
  // which the outputs are already filled with.
  process(inputs, outputs, parameters) {
    return true;
  }
}

// Logs the sample rate, that is not going to change ever,
// because it's a read-only property of a BaseAudioContext
// and is set only during its instantiation.
console.log(sampleRate);

// You can declare any variables and use them in your processors
// for example it may be an ArrayBuffer with a wavetable.
const usefulVariable = 42;
console.log(usefulVariable);

registerProcessor("test-processor", TestProcessor);
```

The main script loads the processor, creates an instance of `AudioWorkletNode`, passes the name of the processor to it, and connects the node to an audio graph. We should see the output of `console.log()` calls in the console:

```js
const audioContext = new AudioContext();
await audioContext.audioWorklet.addModule("test-processor.js");
const testNode = new AudioWorkletNode(audioContext, "test-processor");
testNode.connect(audioContext.destination);
```

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

| Specification |
| --- |
| Web Audio API # dom-audioworkletglobalscope-currenttime |

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

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

See also
--------

* Web Audio API
* Using the Web Audio API


AbortSignal: aborted property - Web APIs

AbortSignal: aborted property
=============================

The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (`true`) or not (`false`).

Value
-----

`true` (aborted) or `false`

Examples
--------

 In the following snippet, we create a new `AbortController` object, and get its `AbortSignal` (available using the `signal` property).
 Later on, using the `aborted` property, we check whether or not the signal has been aborted, and send an appropriate log to the console.

```js
const controller = new AbortController();
const signal = controller.signal;

// …

if (signal.aborted) {
  console.log("Request has been aborted");
} else {
  console.log("Request not aborted");
}
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-abortsignal-aborted① |

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

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

See also
--------

* Fetch API


AbortSignal: reason property - Web APIs

AbortSignal: reason property
============================

The **`reason`** read-only property returns a JavaScript value that indicates the abort reason.

 The property is `undefined` when the signal has not been aborted.
 It can be set to a specific value when the signal is aborted, using `AbortController.abort()` or `AbortSignal.abort()`.
 If not explicitly set in those methods, it defaults to "AbortError" `DOMException`.

Value
-----

A JavaScript value that indicates the abort reason, or `undefined`, if not aborted.

Examples
--------

 In the following snippet, we create a new `AbortController` object, and get its `AbortSignal` (available using the `signal` property).
 Later on, using the `aborted` property, we check whether or not the signal has been aborted, and log the abort status and reason to the console.

```js
const controller = new AbortController();
const signal = controller.signal;

// …

if (signal.aborted) {
  if (signal.reason) {
    console.log(`Request aborted with reason: ${signal.reason}`);
  } else {
    console.log("Request aborted but no reason was given.");
  }
} else {
  console.log("Request not aborted");
}
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-abortsignal-reason① |

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

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

See also
--------

* Fetch API


AbortSignal: throwIfAborted() method - Web APIs

AbortSignal: throwIfAborted() method
====================================

The **`throwIfAborted()`** method throws the signal's abort `reason` if the signal has been aborted; otherwise it does nothing.

An API that needs to support aborting can accept an `AbortSignal` object and use `throwIfAborted()` to test and throw when the `abort` event is signalled.

This method can also be used to abort operations at particular points in code, rather than passing to functions that take a signal.

Syntax
------

```js
throwIfAborted()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

The examples below come from the specification.

### Aborting a polling operation

This example demonstrates how you can use `throwIfAborted()` to abort a polling operation.

 Consider an asynchronous `waitForCondition()` function that is called with another asynchronous function `func`, a target value `targetValue`, and an `AbortSignal`.
 The method compares the result of `func` with `targetValue` in a loop, returning when they match.

```js
async function waitForCondition(func, targetValue, { signal } = {}) {
  while (true) {
    signal?.throwIfAborted();

    const result = await func();
    if (result === targetValue) {
      return;
    }
  }
}
```

 On each iteration of the loop, we use `throwIfAborted()` to throw the signal's `reason` if the operation has been aborted (and otherwise do nothing).
 If the signal is aborted, this will cause the `waitForCondition()` promise to be rejected .

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-abortsignal-throwifaborted① |

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

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

See also
--------

* Fetch API


AbortSignal: any() static method - Web APIs

AbortSignal: any() static method
================================

The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an `AbortSignal`. The returned abort signal is aborted when any of the input iterable abort signals are aborted. The abort reason will be set to the reason of the first signal that is aborted. If any of the given abort signals are already aborted then so will be the returned `AbortSignal`.

Syntax
------

```js
AbortSignal.any(iterable)
```

### Parameters

`iterable`

An iterable (such as an `Array`) of abort signals.

### Return value

A `AbortSignal` that is:

* **Already aborted**, if any of the abort signals given is already aborted. The returned `AbortSignal`'s reason will be already set to the `reason` of the first abort signal that was already aborted.
* **Asynchronously aborted**, when any abort signal in `iterable` aborts. The `reason` will be set to the reason of the first abort signal that is aborted.
Examples
--------

### Using `AbortSignal.any()`

This example demonstrates combining both a signal from an `AbortController`, and a timeout signal from `AbortSignal.timeout`.

```js
const cancelDownloadButton = document.getElementById("cancelDownloadButton");

const userCancelController = new AbortController();

cancelDownloadButton.addEventListener("click", () => {
  userCancelController.abort();
});

// Timeout after 5 minutes
const timeoutSignal = AbortSignal.timeout(1\_000 \* 60 \* 5);

// This signal will abort when either the user clicks the cancel button or 5 minutes is up
// whichever is sooner
const combinedSignal = AbortSignal.any([
  userCancelController.signal,
  timeoutSignal,
]);

try {
  const res = await fetch(someUrlToDownload, {
    // Stop the fetch when any of the
    signal: combinedSignal,
  });
  const body = await res.blob();
  // Do something with downloaded content:
  // ...
} catch (e) {
  if (e.name === "AbortError") {
    // Cancelled by the user
  } else if (e.name === "TimeoutError") {
    // Show user that download timed out
  } else {
    // Other error, e.g. network error
  }
}
```

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

| Specification |
| --- |
| DOM Standard # dom-abortsignal-any |

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

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


AbortSignal: timeout() static method - Web APIs

AbortSignal: timeout() static method
====================================

The **`AbortSignal.timeout()`** static method returns an `AbortSignal` that will automatically abort after a specified time.

 The signal aborts with a `TimeoutError` `DOMException` on timeout, or with `AbortError` `DOMException` due to pressing a browser stop button (or some other inbuilt "stop" operation).
 This allows UIs to differentiate timeout errors, which typically require user notification, from user-triggered aborts that do not.

The timeout is based on active rather than elapsed time, and will effectively be paused if the code is running in a suspended worker, or while the document is in a back-forward cache ("bfcache").

To combine multiple signals, you can use `AbortSignal.any()`, for example, to directly abort a download using either a timeout signal or by calling `AbortController.abort()`.

Syntax
------

```js
AbortSignal.timeout(time)
```

### Parameters

`time`

The "active" time in milliseconds before the returned `AbortSignal` will abort.

### Return value

An `AbortSignal`.

The signal will abort with its `AbortSignal.reason` property set to a `TimeoutError` `DOMException` on timeout, or an `AbortError` `DOMException` if the operation was user-triggered.

Examples
--------

 Below is a simple example showing a fetch operation that will timeout if unsuccessful after 5 seconds.
 Note that this may also fail if the method is not supported, if a browser "stop" button is pressed, or for another reason.

```js
const url = "https://path\_to\_large\_file.mp4";

try {
  const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
  const result = await res.blob();
  // …
} catch (err) {
  if (err.name === "TimeoutError") {
    console.error("Timeout: It took more than 5 seconds to get the result!");
  } else if (err.name === "AbortError") {
    console.error(
      "Fetch aborted by user action (browser stop button, closing tab, etc.",
    );
  } else if (err.name === "TypeError") {
    console.error("AbortSignal.timeout() method is not supported");
  } else {
    // A network error, or some other problem.
    console.error(`Error: type: ${err.name}, message: ${err.message}`);
  }
}
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-abortsignal-timeout① |

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

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


AbortSignal: abort event - Web APIs

AbortSignal: abort event
========================

The **`abort`** event of the `AbortSignal` is fired when the associated request is aborted, i.e. using `AbortController.abort()`.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener('abort', (event) => { })

onabort = (event) => { }
```

Event type
----------

A generic `Event` with no added properties.

Examples
--------

In the following snippets, we create a new `AbortController` object, and get its `AbortSignal` (available using the `signal` property). Later on we check whether or not the signal has been aborted using an event handler property,

You can detect the `abort` event using an `addEventListener` method:

```js
const controller = new AbortController();
const signal = controller.signal;

signal.addEventListener("abort", () => {
  console.log("Request aborted");
});
```

Or use the `onabort` event handler property:

```js
const controller = new AbortController();
const signal = controller.signal;

signal.onabort = () => {
  console.log("Request aborted");
};
```

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

| Specification |
| --- |
| DOM Standard # eventdef-abortsignal-abort |
| DOM Standard # abortsignal-onabort |

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

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


AbortSignal: abort() static method - Web APIs

AbortSignal: abort() static method
==================================

The **`AbortSignal.abort()`** static method returns an `AbortSignal` that is already set as aborted (and which does not trigger an `abort` event).

This is shorthand for the following code:

```js
const controller = new AbortController();
controller.abort();
return controller.signal;
```

This could, for example, be passed to a fetch method in order to run its abort logic (i.e. it may be that code is organized such that the abort logic should be run even if the intended fetch operation has not been started).

**Note:** The method is similar in purpose to `Promise.reject`.

Syntax
------

```js
AbortSignal.abort()
AbortSignal.abort(reason)
```

### Parameters

`reason`

 The reason why the operation was aborted, which can be any JavaScript value.
 If not specified, the reason is set to "AbortError" `DOMException`.

### Return value

An `AbortSignal` instance with the `AbortSignal.aborted` property set to `true`, and `AbortSignal.reason` set to the specified or default reason value.

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-abortsignal-abort① |

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

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


ShadowRoot: adoptedStyleSheets property - Web APIs

ShadowRoot: adoptedStyleSheets property
=======================================

The **`adoptedStyleSheets`** property of the `ShadowRoot` interface sets an array of constructed stylesheets to be used by the shadow DOM subtree.

**Note:** A constructed stylesheet is a stylesheet created programmatically using the `CSSStyleSheet()` constructor (as compared to one created by a user-agent when importing a stylesheet from a script, imported using `<style>` and `@import`, or linked to via `<link>`).

 The same constructed stylesheet can be adopted by multiple `ShadowRoot` instances, and by the parent document (using the `Document.adoptedStyleSheets` property).
 Changing an adopted stylesheet will affect all the adopting objects.

 Stylesheets in the `adoptedStyleSheets` property are considered along with the shadow DOM's other stylesheets.
 For the purpose of determining the final computed CSS of any element, they are considered to have been added *after* the other stylesheets in the shadow DOM (`ShadowRoot.styleSheets`).

Only stylesheets created using the `CSSStyleSheet()` constructor, and from within the same parent `Document` as the shadow root, may be adopted.

Value
-----

The value is an array of `CSSStyleSheet` instances that must have been created using the `CSSStyleSheet()` constructor within the context of the shadow root's parent `Document`.

If the array needs to be modified, use in-place mutations like `push()`. The `CSSStyleSheet` instances themselves can also be modified, and these changes will apply wherever the stylesheet is adopted.

In an earlier version of the specification, the array was not modifiable, so the only way to add new stylesheets was to assign a new array to `adoptedStyleSheets`.

Examples
--------

### Adopting a stylesheet

The code below first shows a stylesheet being constructed, and then `CSSStyleSheet.replaceSync()` is called to add a rule to the sheet.

```js
// Create an empty "constructed" stylesheet
const sheet = new CSSStyleSheet();
// Apply a rule to the sheet
sheet.replaceSync("a { color: red; }");
```

We then create a `ShadowRoot` and pass the sheet object to `adoptedStyleSheets` inside an array.

```js
// Create an element in the document and then create a shadow root:
const node = document.createElement("div");
const shadow = node.attachShadow({ mode: "open" });

// Adopt the sheet into the shadow DOM
shadow.adoptedStyleSheets = [sheet];
```

 We can still modify the stylesheets after they have been added to the array.
 Below we append a new rule to the same sheet using `CSSStyleSheet.insertRule()`.

```js
sheet.insertRule("\* { background-color: blue; }");
// The document will now have blue background.
```

### Append a new stylesheet

New stylesheets can be *appended* to the document or shadow root by using `adoptedStyleSheets.push()`:

```js
const extraSheet = new CSSStyleSheet();
extraSheet.replaceSync("p { color: green; }");

// Concat the new sheet.
shadow.adoptedStyleSheets.push(extraSheet);
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-documentorshadowroot-adoptedstylesheets |

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

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

See also
--------

* Constructable Stylesheets (web.dev)
* Using the Shadow DOM
* `CSSStyleSheet()` constructor
* `CSSStyleSheet.replaceSync()`
* `CSSStyleSheet.replace()`
* `CSSStyleSheet.insertRule()`
* `CSSStyleSheet.deleteRule()`


ShadowRoot: activeElement property - Web APIs

ShadowRoot: activeElement property
==================================

 The **`activeElement`** read-only property of the
 `ShadowRoot` interface returns the element within the shadow tree that has focus.

Value
-----

The `Element` which currently has focus, or `null` if there is no focused element.

Examples
--------

```js
let customElem = document.querySelector("my-shadow-dom-element");
let shadow = customElem.shadowRoot;
let focusedElem = shadow.activeElement;
```

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

| Specification |
| --- |
| HTML Standard # dom-documentorshadowroot-activeelement-dev |

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

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

See also
--------

* `Document.activeElement`


ShadowRoot: slotAssignment property - Web APIs

ShadowRoot: slotAssignment property
===================================

The read-only **`slotAssignment`** property of the `ShadowRoot` interface returns the *slot assignment mode* for the shadow DOM tree. Nodes are either automatically assigned (`named`) or manually assigned (`manual`). The value of this property defined using the `slotAssignment` option when calling `Element.attachShadow()`.

Value
-----

A string that can be one of:

`named`

Elements are automatically assigned to `<slot>` elements within this shadow root. Any descendants of the host with a `slot` attribute which matches the `name` attribute of a `<slot>` within this shadow root will be assigned to that slot. Any top-level children of the host with no `slot` attribute will be assigned to a `<slot>` with no `name` attribute (the "default slot") if one is present.

`manual`

Elements are not automatically assigned to `<slot>` elements. Instead, they must be manually assigned with `HTMLSlotElement.assign()`.

Examples
--------

In the example below, the `assign()` method is used to display the correct tab in a tabbed application. The function is called and passed the panel to show, which is then assigned to the slot. We test if the `slotAssignment` is `named` to prevent an exception to be raised when `HTMLSlotElement.assign()` is called.

```js
function UpdateDisplayTab(elem, tabIdx) {
  const shadow = elem.shadowRoot;

  // This test is usually not needed, but can be useful when debugging
  if (shadow.slotAssignment === "named") {
    console.error(
      "Trying to manually assign a slot on an automatically-assigned (named) slot",
    );
  }
  const slot = shadow.querySelector("slot");
  const panels = elem.querySelectorAll("tab-panel");
  if (panels.length && tabIdx && tabIdx <= panels.length) {
    slot.assign(panels[tabIdx - 1]);
  } else {
    slot.assign();
  }
}
```

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

| Specification |
| --- |
| DOM Standard # dom-shadowroot-slotassignment |

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

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

See also
--------

* `Element.attachShadow()`
* `HTMLSlotElement.assign()`


ShadowRoot: innerHTML property - Web APIs

ShadowRoot: innerHTML property
==============================

 The **`innerHTML`** property of the `ShadowRoot`
 interface sets or returns a reference to the DOM tree inside the
 `ShadowRoot`.

Value
-----

A string.

Examples
--------

```js
let customElem = document.querySelector("my-shadow-dom-element");
let shadow = customElem.shadowRoot;

shadow.innerHTML = "<strong>This element should be more important!</strong>";
```

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

| Specification |
| --- |
| DOM Parsing and Serialization # ref-for-dom-innerhtml-innerhtml-2 |

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

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


ShadowRoot: delegatesFocus property - Web APIs

ShadowRoot: delegatesFocus property
===================================

The **`delegatesFocus`** read-only property of the `ShadowRoot` interface returns `true` if the shadow root delegates focus, and `false` otherwise.

If `true`, when a non-focusable part of the shadow DOM is clicked, or `.focus()` is called on the host element, the first focusable part is given focus, and the shadow host is given any available `:focus` styling.

Focus is of particular importance for keyboard users (including those using screen readers). `delegatesFocus` default behavior is to focus the first focusable element — which may be undesirable if that element is not meant to be part of the tabbing order (for example, an element with `tabindex="-1"`), or if a more 'important' focusable element should receive initial focus (for instance, the first text field rather than the 'close' button which precedes it). In such cases, the `autofocus` attribute can be specified on the element which should receive initial focus. Use the `autofocus` attribute with caution as it can introduce accessibility issues, such as bypassing important content which may go unnoticed due to focus being set to an element later in the DOM order.

The property value is set using the `delegatesFocus` property of the object passed to `Element.attachShadow()`).

Examples
--------

```js
let customElem = document.querySelector("my-shadow-dom-element");
let shadow = customElem.shadowRoot;

// ...

// Does it delegate focus?
let hostElem = shadow.delegatesFocus;
```

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

| Specification |
| --- |
| DOM Standard # shadowroot-delegates-focus |

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

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


ShadowRoot: styleSheets property - Web APIs

ShadowRoot: styleSheets property
================================

 The **`styleSheets`** read-only property of the `ShadowRoot` interface
 returns a `StyleSheetList` of `CSSStyleSheet` objects, for stylesheets explicitly linked into or embedded in a shadow tree.

Value
-----

A `StyleSheetList` of `CSSStyleSheet` objects.

Examples
--------

```js
let customElem = document.querySelector("my-shadow-dom-element");
let shadow = customElem.shadowRoot;
let styleSheets = shadow.styleSheets;
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-documentorshadowroot-stylesheets |

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

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


ShadowRoot: fullscreenElement property - Web APIs

ShadowRoot: fullscreenElement property
======================================

 The **`fullscreenElement`** read-only property of the
 `ShadowRoot` interface returns the element within the shadow tree that is currently displayed in full screen.

Value
-----

 The `Element` which is currently is displayed in full screen mode,
 or `null` if there is no full screen element.

Examples
--------

```js
let customElem = document.querySelector("my-shadow-dom-element");
let shadow = customElem.shadowRoot;
let fullscreenElem = shadow.fullscreenElement;
```

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

| Specification |
| --- |
| Fullscreen API Standard # ref-for-dom-document-fullscreenelement② |

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

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

See also
--------

* `Document.fullscreenElement`


ShadowRoot: getAnimations() method - Web APIs

ShadowRoot: getAnimations() method
==================================

 The **`getAnimations()`** method of the `ShadowRoot` interface
 returns an array of all `Animation` objects currently in effect whose
 target elements are descendants of the shadow tree. This array includes CSS Animations, CSS Transitions, and Web Animations.

Syntax
------

```js
getAnimations()
```

### Parameters

None.

### Return value

 An `Array` of `Animation` objects, each representing one
 animation currently associated with elements which are descendants of the
 `ShadowRoot` on which it's called.

Examples
--------

 The following code snippet will slow down all animations in a shadow tree by halving their
 `Animation.playbackRate`.

```js
let customElem = document.querySelector("my-shadow-dom-element");
let shadow = customElem.shadowRoot;
shadow.getAnimations().forEach((animation) => {
  animation.playbackRate \*= 0.5;
});
```

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

| Specification |
| --- |
| Web Animations # dom-documentorshadowroot-getanimations |

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

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

See also
--------

* Web Animations API
* CSS Animations
* CSS Transitions
* `Element.getAnimations()` - Fetch only the animations on a single
 `Element` and its descendants.
* `Animation`


ShadowRoot: pointerLockElement property - Web APIs

ShadowRoot: pointerLockElement property
=======================================

 The **`pointerLockElement`** read-only property of the `ShadowRoot` interface provides the element set as the target for mouse events while the pointer is locked.
 It is `null` if lock is pending, pointer is unlocked, or the target is in another tree.

Value
-----

An `Element` or `null`.

Examples
--------

```js
let customElem = document.querySelector("my-shadow-dom-element");
let shadow = customElem.shadowRoot;
let pleElem = shadow.pointerLockElement;
```

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

| Specification |
| --- |
| Pointer Lock 2.0 # dom-documentorshadowroot-pointerlockelement |

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

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

See also
--------

* `Document.exitPointerLock()`
* `Element.requestPointerLock()`
* Pointer Lock


ShadowRoot: host property - Web APIs

ShadowRoot: host property
=========================

Baseline Widely available
-------------------------

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

* Learn more
* See full compatibility
* Report feedback

 The **`host`** read-only property of
 the `ShadowRoot` returns a reference to the DOM element the
 `ShadowRoot` is attached to.

Value
-----

A DOM `Element`.

Examples
--------

```js
let customElem = document.querySelector("my-shadow-dom-element");
let shadow = customElem.shadowRoot;

// ...

// return the original host element some time later
let hostElem = shadow.host;
```

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

| Specification |
| --- |
| DOM Standard # dom-shadowroot-host |

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

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

See also
--------

* `part` and `exportparts` HTML attributes
* `<template>` and `<slot>` HTML elements
* `:host`, `:host()`, and `:host-context()` CSS pseudo-classes
* `::part` and `::slotted` CSS pseudo-elements


ShadowRoot: pictureInPictureElement property - Web APIs

ShadowRoot: pictureInPictureElement property
============================================

 The **`pictureInPictureElement`** read-only property of the
 `ShadowRoot` interface returns the `Element` that is currently being
 presented in picture-in-picture mode in this shadow tree, or `null` if
 picture-in-picture mode is not currently in use.

Value
-----

 A reference to the `Element` object that's currently in
 picture-in-picture mode, or, if picture-in-picture mode isn't currently in use by the
 shadow tree, the returned value is `null`.

Examples
--------

```js
let customElem = document.querySelector("my-shadow-dom-element");
let shadow = customElem.shadowRoot;
let pipElem = shadow.pictureInPictureElement;
```

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

| Specification |
| --- |
| Picture-in-Picture # ref-for-dom-documentorshadowroot-pictureinpictureelement①⑤ |

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

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

See also
--------

* `Document.pictureInPictureElement`


ShadowRoot: mode property - Web APIs

ShadowRoot: mode property
=========================

Baseline Widely available
-------------------------

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

* Learn more
* See full compatibility
* Report feedback

 The **`mode`** read-only property of the `ShadowRoot`
 specifies its mode — either `open` or `closed`. This defines
 whether or not the shadow root's internal features are accessible from JavaScript.

 When the `mode` of a shadow root is "`closed`", the shadow root's
 implementation internals are inaccessible and unchangeable from JavaScript—in the same
 way the implementation internals of, for example, the `<video>` element
 are inaccessible and unchangeable from JavaScript.

Value
-----

 A value defined in the
 `ShadowRootMode`
 enum — either `open` or `closed`.

Examples
--------

```js
// We create a closed shadow root, that is not accessible
let element = document.createElement("div");
element.attachShadow({ mode: "closed" });
element.shadowRoot; // null as the shadow root is closed

// We create an open shadow root, that is accessible
let element2 = document.createElement("div");
element2.attachShadow({ mode: "open" });
console.log(`The shadow is ${element2.shadowRoot.mode}`); // logs "The shadow is open"
element2.shadowRoot.textContent("Opened shadow"); // The shadow is open, we can access it from outside
```

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

| Specification |
| --- |
| DOM Standard # dom-shadowroot-mode |

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

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


GPUDeviceLostInfo: reason property - Web APIs

GPUDeviceLostInfo: reason property
==================================

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

 The **`reason`** read-only property of the
 `GPUDeviceLostInfo` interface defines the reason the device was lost in a machine-readable way.

Value
-----

An enumerated value. At the moment the only value defined in the spec is `"destroyed"`, which indicates that the device was destroyed by a call to `GPUDevice.destroy()`.

If the device was lost because of an unknown reason not covered in the available enumerated values, `reason` returns `undefined`.

Examples
--------

See the main `GPUDevice.lost` page for an example.

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

| Specification |
| --- |
| WebGPU # dom-gpudevicelostinfo-reason |

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

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

See also
--------

* The WebGPU API


GPUDeviceLostInfo: message property - Web APIs

GPUDeviceLostInfo: message property
===================================

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

 The **`message`** read-only property of the
 `GPUDeviceLostInfo` interface provides a human-readable message that explains why the device was lost.

Value
-----

A string.

Examples
--------

See the main `GPUDevice.lost` page for an example.

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

| Specification |
| --- |
| WebGPU # dom-gpudevicelostinfo-message |

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

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

See also
--------

* The WebGPU API


DataTransferItem: getAsFileSystemHandle() method - Web APIs

DataTransferItem: getAsFileSystemHandle() method
================================================

**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 **`getAsFileSystemHandle()`** method of the
 `DataTransferItem` interface returns a `FileSystemFileHandle`
 if the dragged item is a file, or a `FileSystemDirectoryHandle` if the
 dragged item is a directory.

Syntax
------

```js
getAsFileSystemHandle()
```

### Parameters

None.

### Return value

A `Promise`.

If the item's `kind` property is `"file"`, and this item is accessed in the `dragstart` or `drop` event handlers, then the returned promise is fulfilled with a `FileSystemFileHandle` if the dragged item is a file or a `FileSystemDirectoryHandle` if the dragged item is a directory.

Otherwise, the promise fulfills with `null`.

### Exceptions

None.

Examples
--------

 This example uses the `getAsFileSystemHandle` method to return
 `file handles` for dropped items.

```js
elem.addEventListener("dragover", (e) => {
  // Prevent navigation.
  e.preventDefault();
});
elem.addEventListener("drop", async (e) => {
  // Prevent navigation.
  e.preventDefault();

  // Process all of the items.
  for (const item of e.dataTransfer.items) {
    // kind will be 'file' for file/directory entries.
    if (item.kind === "file") {
      const entry = await item.getAsFileSystemHandle();
      if (entry.kind === "file") {
        // run code for if entry is a file
      } else if (entry.kind === "directory") {
        // run code for is entry is a directory
      }
    }
  }
});
```

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

| Specification |
| --- |
| File System Access # dom-datatransferitem-getasfilesystemhandle |

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

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

See also
--------

* File System API
* The File System Access API: simplifying access to local files


DataTransferItem: type property - Web APIs

DataTransferItem: type property
===============================

 The read-only **`DataTransferItem.type`** property returns the type (format) of the `DataTransferItem` object representing the drag data item.
 The `type` is a Unicode string generally given by a MIME type, although a MIME type is not required.

Some example types are: `text/plain` and `text/html`.

Value
-----

A string representing the drag data item's type.

Examples
--------

This example shows the use of the `type` property.

```js
function dropHandler(ev) {
  console.log("Drop");
  ev.preventDefault();
  const data = ev.dataTransfer.items;
  for (let i = 0; i < data.length; i += 1) {
    if (data[i].kind === "string" && data[i].type.match("^text/plain")) {
      // This item is the target node
      data[i].getAsString((s) => {
        ev.target.appendChild(document.getElementById(s));
      });
    } else if (data[i].kind === "string" && data[i].type.match("^text/html")) {
      // Drag data item is HTML
      console.log("… Drop: HTML");
    } else if (
      data[i].kind === "string" &&
      data[i].type.match("^text/uri-list")
    ) {
      // Drag data item is URI
      console.log("… Drop: URI");
    } else if (data[i].kind === "file" && data[i].type.match("^image/")) {
      // Drag data item is an image file
      const f = data[i].getAsFile();
      console.log("… Drop: File");
    }
  }
}
```

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

| Specification |
| --- |
| HTML Standard # dom-datatransferitem-type-dev |

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

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

See also
--------

* `DataTransfer.types()`
* List of common MIME types


DataTransferItem: kind property - Web APIs

DataTransferItem: kind property
===============================

The read-only **`DataTransferItem.kind`** property returns the kind–a string or a file–of the `DataTransferItem` object representing the *drag data item*.

Value
-----

 A string representing the drag data item's kind.
 It must be one of the following values:

`'file'`

If the drag data item is a file.

`'string'`

If the kind of drag data item is a *plain Unicode string*.

Examples
--------

This example shows the use of the `kind` property.

```js
function dropHandler(ev) {
  console.log("Drop");
  ev.preventDefault();
  const data = event.dataTransfer.items;
  for (let i = 0; i < data.length; i += 1) {
    if (data[i].kind === "string" && data[i].type.match("^text/plain")) {
      // This item is the target node
      data[i].getAsString((s) => {
        ev.target.appendChild(document.getElementById(s));
      });
    } else if (data[i].kind === "string" && data[i].type.match("^text/html")) {
      // Drag data item is HTML
      console.log("… Drop: HTML");
    } else if (data[i].kind === "file" && data[i].type.match("^image/")) {
      // Drag data item is an image file
      const f = data[i].getAsFile();
      console.log("… Drop: File");
    }
  }
}
```

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

| Specification |
| --- |
| HTML Standard # dom-datatransferitem-kind-dev |

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

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

See also
--------

* Drag and drop
* Drag Operations
* Recommended Drag Types
* DataTransfer test - Paste or Drag


DataTransferItem: webkitGetAsEntry() method - Web APIs

DataTransferItem: webkitGetAsEntry() method
===========================================

If the item described by the `DataTransferItem` is a file, `webkitGetAsEntry()` returns a `FileSystemFileEntry` or `FileSystemDirectoryEntry` representing it. If the item isn't a file, `null` is returned.

**Note:** This function is implemented as `webkitGetAsEntry()` in non-WebKit browsers including Firefox at this time; it may be renamed to
 `getAsEntry()` in the future, so you should code defensively, looking for both.

Syntax
------

```js
webkitGetAsEntry()
```

### Parameters

None.

### Return value

 A `FileSystemEntry`-based object describing the dropped item.
 This will be either `FileSystemFileEntry` or `FileSystemDirectoryEntry`.
 The method aborts and returns `null` if the dropped item isn't a file, or if the `DataTransferItem` object is not in read or read/write mode.

Examples
--------

 In this example, a drop zone is created, which responds to the `drop` event
 by scanning through the dropped files and directories, outputting a hierarchical
 directory listing.

### HTML

The HTML establishes the drop zone itself, which is a `<div>` element with the ID `"dropzone"`, and an unordered list element with the ID `"listing"`.

```html
<p>Drag files and/or directories to the box below!</p>

<div id="dropzone">
  <div id="boxtitle">Drop Files Here</div>
</div>

<h2>Directory tree:</h2>

<ul id="listing"></ul>
```

### CSS

The styles used by the example are shown here.

```css
#dropzone {
  text-align: center;
  width: 300px;
  height: 100px;
  margin: 10px;
  padding: 10px;
  border: 4px dashed red;
  border-radius: 10px;
}

#boxtitle {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  color: black;
  font:
    bold 2em "Arial",
    sans-serif;
  width: 300px;
  height: 100px;
}

body {
  font:
    14px "Arial",
    sans-serif;
}
```

### JavaScript

 First, let's look at the recursive `scanFiles()` function.
 This function takes as input a `FileSystemEntry` representing an entry in the file system to be scanned and processed (the `item` parameter), and an element into which to insert the list of contents (the `container` parameter).

**Note:** To read all files in a directory, `readEntries` needs to be called repeatedly until it returns an empty array.
 In Chromium-based browsers, the following example will only return a max of 100 entries.

```js
let dropzone = document.getElementById("dropzone");
let listing = document.getElementById("listing");

function scanFiles(item, container) {
  let elem = document.createElement("li");
  elem.textContent = item.name;
  container.appendChild(elem);

  if (item.isDirectory) {
    let directoryReader = item.createReader();
    let directoryContainer = document.createElement("ul");
    container.appendChild(directoryContainer);
    directoryReader.readEntries((entries) => {
      entries.forEach((entry) => {
        scanFiles(entry, directoryContainer);
      });
    });
  }
}
```

`scanFiles()` begins by creating a new `<li>` element to represent the item being scanned, inserts the name of the item into it as its text content, and then appends it to the container.
 The container is always a list element in this example, as you'll see shortly.

 Once the current item is in the list, the item's `isDirectory` property is checked.
 If the item is a directory, we need to recurse into that directory.
 The first step is to create a `FileSystemDirectoryReader` to handle fetching the directory's contents.
 That's done by calling the item's `createReader()` method.
 Then a new `<ul>` is created and appended to the parent list; this will contain the directory's contents in the next level down in the list's hierarchy.

 After that, `directoryReader.readEntries()` is called to read in all the entries in the directory.
 These are each, in turn, passed into a recursive call to `scanFiles()` to process them.
 Any of them which are files are inserted into the list; any which are directories are inserted into the list and a new level of the list's hierarchy is added below, and so forth.

Then come the event handlers. First, we prevent the `dragover` event from being handled by the default handler, so that our drop zone can receive the drop:

```js
dropzone.addEventListener(
  "dragover",
  (event) => {
    event.preventDefault();
  },
  false,
);
```

The event handler that kicks everything off, of course, is the handler for the `drop` event:

```js
dropzone.addEventListener(
  "drop",
  (event) => {
    let items = event.dataTransfer.items;

    event.preventDefault();
    listing.textContent = "";

    for (let i = 0; i < items.length; i++) {
      let item = items[i].webkitGetAsEntry();

      if (item) {
        scanFiles(item, listing);
      }
    }
  },
  false,
);
```

 This fetches the list of `DataTransferItem` objects representing the items dropped from `event.dataTransfer.items`.
 Then we call `Event.preventDefault()` to prevent the event from being handled further after we're done.

 Now it's time to start building the list. First, the list is emptied by setting `listing.textContent` to be empty.
 That leaves us with an empty `<ul>` to begin inserting directory entries into.

 Then we iterate over the items in the list of dropped items.
 For each one, we call its `webkitGetAsEntry()` method to obtain a `FileSystemEntry` representing the file.
 If that's successful, we call `scanFiles()` to process the item—either by adding it to the list if it's just a file or by adding it and walking down into it if it's a directory.

### Result

You can see how this works by trying it out below. Find some files and directories and drag them in, and take a look at the resulting output.

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

| Specification |
| --- |
| File and Directory Entries API # dom-datatransferitem-webkitgetasentry |

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
* `DataTransferItem`
* `FileSystemEntry`, `FileSystemFileEntry`, and `FileSystemDirectoryEntry`
* Events: `dragover` and `drop`


DataTransferItem: getAsString() method - Web APIs

DataTransferItem: getAsString() method
======================================

The **`DataTransferItem.getAsString()`** method invokes the given callback with the drag data item's string data as the argument if the item's `kind` is a *Plain unicode string* (i.e. `kind` is `string`).

Syntax
------

```js
getAsString(callbackFn)
```

### Parameters

`callbackFn`

A callback function that receives following arguments:

`data`

The `data transfer item's` string data.

### Return value

None (`undefined`).

Examples
--------

This example shows the use of the `getAsString()` method as an *inline function* in a `drop` event handler.

```js
function dropHandler(ev) {
  console.log("Drop");
  ev.preventDefault();
  const data = ev.dataTransfer.items;
  for (let i = 0; i < data.length; i += 1) {
    if (data[i].kind === "string" && data[i].type.match("^text/plain")) {
      // This item is the target node
      data[i].getAsString((s) => {
        ev.target.appendChild(document.getElementById(s));
      });
    } else if (data[i].kind === "string" && data[i].type.match("^text/html")) {
      // Drag data item is HTML
      console.log("… Drop: HTML");
    } else if (
      data[i].kind === "string" &&
      data[i].type.match("^text/uri-list")
    ) {
      // Drag data item is URI
      console.log("… Drop: URI");
    } else if (data[i].kind === "file" && data[i].type.match("^image/")) {
      // Drag data item is an image file
      const f = data[i].getAsFile();
      console.log("… Drop: File");
    }
  }
}
```

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

| Specification |
| --- |
| HTML Standard # dom-datatransferitem-getasstring-dev |

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

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

See also
--------

* `DataTransfer.getData()`


DataTransferItem: getAsFile() method - Web APIs

DataTransferItem: getAsFile() method
====================================

 If the item is a file, the **`DataTransferItem.getAsFile()`** method returns the drag data item's `File` object.
 If the item is not a file, this method returns `null`.

Syntax
------

```js
getAsFile()
```

### Parameters

None.

### Return value

`File`

If the drag data item is a file, a `File` object is returned; otherwise `null` is returned.

Examples
--------

This example shows the use of the `getAsFile()` method in a `drop` event handler.

```js
function dropHandler(ev) {
  console.log("Drop");
  ev.preventDefault();
  const data = ev.dataTransfer.items;
  for (let i = 0; i < data.length; i += 1) {
    if (data[i].kind === "string" && data[i].type.match("^text/plain")) {
      // This item is the target node
      data[i].getAsString((s) => {
        ev.target.appendChild(document.getElementById(s));
      });
    } else if (data[i].kind === "string" && data[i].type.match("^text/html")) {
      // Drag data item is HTML
      console.log("… Drop: HTML");
    } else if (
      data[i].kind === "string" &&
      data[i].type.match("^text/uri-list")
    ) {
      // Drag data item is URI
      console.log("… Drop: URI");
    } else if (data[i].kind === "file" && data[i].type.match("^image/")) {
      // Drag data item is an image file
      const f = data[i].getAsFile();
      console.log("… Drop: File");
    }
  }
}
```

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

| Specification |
| --- |
| HTML Standard # dom-datatransferitem-getasfile-dev |

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

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

See also
--------

* `DataTransfer.files`


IDBCursor: advance() method - Web APIs

IDBCursor: advance() method
===========================

 The **`advance()`** method of the `IDBCursor`
 interface sets the number of times a cursor should move
 its position forward.

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

Syntax
------

```js
advance(count)
```

### Parameters

`count`

The number of times to move the cursor forward.

### Return value

None (`undefined`).

### Exceptions

This method may raise a `DOMException` of one of the following types:

`TransactionInactiveError` `DOMException`

Thrown if this IDBCursor's transaction is inactive.

`TypeError`

Thrown if the value passed into the `count` parameter was zero or a negative number.

`InvalidStateError` `DOMException`

Thrown if the cursor is currently being iterated or has iterated past its end.

Examples
--------

 In this simple fragment we create a transaction, retrieve an object store, then use a
 cursor to iterate through the records in the object store. Here we use
 `cursor.advance(2)` to jump 2 places forward each time, meaning that only
 every other result will be displayed. `advance()` works in a similar way to
 `IDBCursor.continue`, except that it allows you to jump multiple records at
 a time, not just always go onto the next record.

 Note that in each iteration of the loop, you can grab
 data from the current record under the cursor object using `cursor.value.foo`. For a complete working example, see our IDBCursor example (View the example live).

```js
function advanceResult() {
  list.textContent = "";
  const transaction = db.transaction(["rushAlbumList"], "readonly");
  const objectStore = transaction.objectStore("rushAlbumList");

  objectStore.openCursor().onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const listItem = document.createElement("li");
      listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`;
      list.appendChild(listItem);
      cursor.advance(2);
    } else {
      console.log("Every other entry displayed.");
    }
  };
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbcursor-advance① |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).


IDBCursor: direction property - Web APIs

IDBCursor: direction property
=============================

 The **`direction`** read-only property of the
 `IDBCursor` interface is a string that returns the
 direction of traversal of the cursor (set using
 `IDBObjectStore.openCursor` for example). See the Values
 section below for possible values.

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

Value
-----

 A string indicating the direction in which the cursor is traversing the data.
 Possible values are:

`next`

This direction causes the cursor to be opened at the start of the source.

`nextunique`

 This direction causes the cursor to be opened at the start of the source.
 For every key with duplicate values, only the first record is yielded.

`prev`

This direction causes the cursor to be opened at the end of the source.

`prevunique`

 This direction causes the cursor to be opened at the end of the source.
 For every key with duplicate values, only the first record is yielded.

Examples
--------

 In this simple fragment we create a transaction, retrieve an object store, then use a
 cursor to iterate through all the records in the object store. Within each iteration we
 log the direction of the cursor, something like this:
```

prev
```

**Note:** we can't change the direction of travel of the cursor using
 the `direction` property, as it is read-only. We specify the direction of
 travel using the 2nd argument of `IDBObjectStore.openCursor`.

 The cursor does not require us to select the data based on a key; we can just grab all
 of it. Also note that in each iteration of the loop, you can grab data from the current
 record under the cursor object using `cursor.value.foo`. For a complete
 working example, see our IDBCursor example (View the example live).

```js
function backwards() {
  list.textContent = "";
  const transaction = db.transaction(["rushAlbumList"], "readonly");
  const objectStore = transaction.objectStore("rushAlbumList");

  objectStore.openCursor(null, "prev").onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const listItem = document.createElement("li");
      listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`;
      list.appendChild(listItem);

      console.log(cursor.direction);
      cursor.continue();
    } else {
      console.log("Entries displayed backwards.");
    }
  };
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbcursor-direction① |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).


IDBCursor: continuePrimaryKey() method - Web APIs

IDBCursor: continuePrimaryKey() method
======================================

 The **`continuePrimaryKey()`** method of the
 `IDBCursor` interface advances the cursor to the item whose key
 matches the key parameter as well as whose primary key matches the primary key
 parameter.

 A typical use case, is to resume the iteration where a previous cursor has been closed,
 without having to compare the keys one by one.

 Calling this method more than once before new cursor data has been loaded - for
 example, calling `continuePrimaryKey()` twice from the same onsuccess handler
 - results in an `InvalidStateError` being thrown on the second call because
 the cursor's got value flag has been unset.

 This method is only valid for cursors coming from an index. Using it for cursors coming
 from an object store will throw an error.

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

Syntax
------

```js
continuePrimaryKey(key, primaryKey)
```

### Parameters

`key`

The key to position the cursor at.

`primaryKey`

The primary key to position the cursor at.

### Return value

None (`undefined`).

### Exceptions

This method may raise a `DOMException` of one of the following types:

`TransactionInactiveError` `DOMException`

Thrown if this IDBCursor's transaction is inactive.

`DataError` `DOMException`

Thrown if the key parameter has any of the following conditions:

* The key is not a valid key.
* The key is less than or equal to this cursor's position and the cursor's direction is `next` or `nextunique`.
* The key is greater than or equal to this cursor's position and this cursor's direction is `prev` or `prevunique`.

`InvalidStateError` `DOMException`

Thrown if the cursor is currently being iterated or has iterated past its end.

`InvalidAccessError` `DOMException`

Thrown if the cursor's direction is not `prev` or `next`.

Examples
--------

 here's how you can resume an iteration of all articles tagged with
 `"javascript"` since your last visit:

```js
let request = articleStore.index("tag").openCursor();
let count = 0;
let unreadList = [];
request.onsuccess = (event) => {
  let cursor = event.target.result;
  if (!cursor) {
    return;
  }
  let lastPrimaryKey = getLastIteratedArticleId();
  if (lastPrimaryKey > cursor.primaryKey) {
    cursor.continuePrimaryKey("javascript", lastPrimaryKey);
    return;
  }
  // update lastIteratedArticleId
  setLastIteratedArticleId(cursor.primaryKey);
  // preload 5 articles into the unread list;
  unreadList.push(cursor.value);
  if (++count < 5) {
    cursor.continue();
  }
};
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbcursor-continueprimarykey① |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).


IDBCursor: request property - Web APIs

IDBCursor: request property
===========================

The **`request`** read-only property of the `IDBCursor` interface returns the `IDBRequest` used to obtain the cursor.

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

Value
-----

An `IDBRequest` object instance.

Examples
--------

When you open a cursor, the `request` property is then available on that cursor object, to tell you what request object the cursor originated from. For example:

```js
function displayData() {
  list.textContent = "";
  const transaction = db.transaction(["rushAlbumList"], "readonly");
  const objectStore = transaction.objectStore("rushAlbumList");

  const request = objectStore.openCursor();

  request.onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const listItem = document.createElement("li");
      listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`;
      list.appendChild(listItem);
      console.log(cursor.request);
      cursor.continue();
    } else {
      console.log("Entries all displayed.");
    }
  };
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbcursor-request① |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).


IDBCursor: update() method - Web APIs

IDBCursor: update() method
==========================

 The **`update()`** method of the `IDBCursor`
 interface returns an `IDBRequest` object, and, in a separate thread,
 updates the value at the current position of the cursor in the object store. If the
 cursor points to a record that has just been deleted, a new record is created.

 Be aware that you can't call `update()` (or
 `IDBCursor.delete()`) on cursors obtained from
 `IDBIndex.openKeyCursor()`. For such needs, you have to use
 `IDBIndex.openCursor()` instead.

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

Syntax
------

```js
update(value)
```

### Parameters

`value`

The new value to be stored at the current position.

### Return value

An `IDBRequest` object on which subsequent events related to this operation are fired.

If the operation is successful, the value of the request's `result` property is the key for the updated record.

### Exceptions

This method may raise a `DOMException` of one of the following types:

`TransactionInactiveError` `DOMException`

Thrown if this IDBCursor's transaction is inactive.

`ReadOnlyError` `DOMException`

Thrown if the transaction mode is read-only.

`InvalidStateError` `DOMException`

Thrown if the cursor was created using `IDBindex.openKeyCursor`, is currently being iterated, or has iterated past its end.

`DataError` `DOMException`

 Thrown if the underlying object store uses in-line keys and the property in the value at the object store's key path does not match the key in this
 cursor's position.

`DataCloneError` `DOMException`

 Thrown if the data being stored could not be cloned by the internal structured
 cloning algorithm.

Examples
--------

 In this simple fragment we create a transaction, retrieve an object store, then use a
 cursor to iterate through all the records in the object store. If the
 `albumTitle` of the current cursor is "A farewell to kings", we update year
 the album was released using `const request = cursor.update();`.

 Note that you cannot change primary keys using `cursor.update()`, hence us
 not changing the album title; this would ruin the integrity of the data. In such a
 situation, you would have to delete the record altogether and then add a new one using
 `IDBObjectStore.add`. Note also that you can't directly put
 `cursor.value` into an update call, hence the below example using an
 intermediary `updateData` variable.

 The cursor does not require us to select the data based
 on a key; we can just grab all of it. Also note that in each iteration of the loop,
 you can grab data from the current record under the cursor object using `cursor.value.foo`. For a complete working example, see our IDBCursor example (View the example live).

```js
function updateResult() {
  list.textContent = "";
  const transaction = db.transaction(["rushAlbumList"], "readwrite");
  const objectStore = transaction.objectStore("rushAlbumList");

  objectStore.openCursor().onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      if (cursor.value.albumTitle === "A farewell to kings") {
        const updateData = cursor.value;

        updateData.year = 2050;
        const request = cursor.update(updateData);
        request.onsuccess = () => {
          console.log("A better album year?");
        };
      }

      const listItem = document.createElement("li");
      listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`;
      list.appendChild(listItem);
      cursor.continue();
    } else {
      console.log("Entries displayed.");
    }
  };
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbcursor-update① |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).


IDBCursor: delete() method - Web APIs

IDBCursor: delete() method
==========================

 The **`delete()`** method of the `IDBCursor`
 interface returns an `IDBRequest` object, and, in a separate thread,
 deletes the record at the cursor's position, without changing the cursor's position.
 Once the record is deleted, the cursor's value is set to null.

 Be aware that you can't call `delete()` (or
 `IDBCursor.update()`) on cursors obtained from
 `IDBIndex.openKeyCursor()`. For such needs, you have to use
 `IDBIndex.openCursor()` instead.

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

Syntax
------

```js
delete()
```

### Parameters

None.

### Return value

 An `IDBRequest` object on which subsequent events related to this
 operation are fired.

If the operation is successful, the value of the request's `result` property is `undefined`.

### Exceptions

This method may raise a `DOMException` of one of the following types:

`TransactionInactiveError` `DOMException`

Thrown if this IDBCursor's transaction is inactive.

`ReadOnlyError` `DOMException`

Thrown if the transaction mode is read-only.

`InvalidStateError` `DOMException`

Thrown if the cursor was created using `IDBindex.openKeyCursor`, is currently being iterated, or has iterated past its end.

Examples
--------

 In this simple fragment we create a transaction, retrieve an object store, then use a
 cursor to iterate through all the records in the object store. If the
 `albumTitle` of the current cursor is "Grace under pressure", we delete that
 entire record using `const request = cursor.delete();`.

 The cursor does not require us to select the data based on a key; we can just grab all
 of it. Also note that in each iteration of the loop, you can grab data from the current
 record under the cursor object using `cursor.value.foo`. For a complete
 working example, see our IDBCursor example (View the example live).

```js
function deleteResult() {
  list.textContent = "";
  const transaction = db.transaction(["rushAlbumList"], "readwrite");
  const objectStore = transaction.objectStore("rushAlbumList");

  objectStore.openCursor().onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      if (cursor.value.albumTitle === "Grace under pressure") {
        const request = cursor.delete();
        request.onsuccess = () => {
          console.log(
            "Deleted that mediocre album from 1984. Even Power windows is better.",
          );
        };
      } else {
        const listItem = document.createElement("li");
        listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`;
        list.appendChild(listItem);
      }
      cursor.continue();
    } else {
      console.log("Entries displayed.");
    }
  };
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbcursor-delete① |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).


IDBCursor: source property - Web APIs

IDBCursor: source property
==========================

 The **`source`** read-only property of the
 `IDBCursor` interface returns the `IDBObjectStore` or
 `IDBIndex` that the cursor is iterating over. This function never returns
 null or throws an exception, even if the cursor is currently being iterated, has
 iterated past its end, or its transaction is not active.

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

Value
-----

 The `IDBObjectStore` or `IDBIndex` that the cursor is
 iterating over.

Examples
--------

 In this simple fragment we create a transaction, retrieve an object store, then use a
 cursor to iterate through all the records in the object store. Within each iteration we
 log the source of the cursor, which will log our `IDBObjectStore` object to
 the console, something like this:

```json
IDBObjectStore {autoIncrement: false, transaction: IDBTransaction, indexNames: DOMStringList, keyPath: "albumTitle", name: "rushAlbumList"…}
```

 The cursor does not require us to select the data based
 on a key; we can just grab all of it. Also note that in each iteration of the loop,
 you can grab data from the current record under the cursor object using `cursor.value.foo`. For a complete working example, see our IDBCursor example (View the example live).

```js
function displayData() {
  const transaction = db.transaction(["rushAlbumList"], "readonly");
  const objectStore = transaction.objectStore("rushAlbumList");

  objectStore.openCursor().onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const listItem = document.createElement("li");
      listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`;
      list.appendChild(listItem);

      console.log(cursor.source);
      cursor.continue();
    } else {
      console.log("Entries all displayed.");
    }
  };
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbcursor-source① |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).