HTMLScriptElement: supports() static method - Web APIs

HTMLScriptElement: supports() static method
===========================================

The **`supports()`** static method of the `HTMLScriptElement` interface provides a simple and consistent method to feature-detect what types of scripts are supported by the user agent.

The method is expected to return `true` for classic and module scripts, which are supported by most modern browsers.

Syntax
------

```js
HTMLScriptElement.supports(type)
```

### Parameters

`type`

 A string literal that indicates the type of script for which support is to be checked.
 Supported values are case sensitive, and include:

`"classic"`

 Test if *classic scripts* are supported.
 "Classic" scripts are the normal/traditional JavaScript files that predate module scripts.

`"module"`

Test if module scripts are supported.

`"importmap"`

Test if import maps are supported.

`"speculationrules"`

Test if speculation rules are supported and enabled.

Any other value will cause the method to return `false`.

### Return value

Returns `true` if the indicated script type is supported and `false` otherwise.

Examples
--------

The code below shows how to check if `HTMLScriptElement.supports()` is defined, and if so, to use it to test whether particular types of scripts are supported.

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

function checkSupport(type) {
  const result = HTMLScriptElement.supports(type) ? "true" : "false";
  log.textContent += `HTMLScriptElement.supports('${type}') is ${result}\n`;
}

if (typeof HTMLScriptElement.supports === "undefined") {
  log.textContent = "HTMLScriptElement.supports() method is not supported";
} else {
  // Check if various script types are supported
  checkSupport("module");
  checkSupport("classic");
  checkSupport("importmap");
  checkSupport("speculationrules");
  // Any other value will cause the method to return false
  checkSupport("anything else");
}
```

```
<textarea id="log" rows="6" cols="80"></textarea>
```

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

| Specification |
| --- |
| HTML Standard # dom-script-supports |

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

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

See also
--------

* `HTMLScriptElement`
* `<script>`
* JavaScript modules
* `Worker` constructor


XRRenderState: layers property - Web APIs

XRRenderState: layers property
==============================

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

The read-only **`layers`** property of the `XRRenderState` interface is an ordered array containing `XRLayer` objects that are displayed by the XR compositor.

Value
-----

An ordered array containing `XRLayer` objects. The order of the layers is "back-to-front".

Examples
--------

### Getting render state layers

 To read the WebXR layers array, use the `layers` property on `XRRenderState`.
 Layers can be set using the `XRSession.updateRenderState()` method.

```js
const xrSession = navigator.xr.requestSession("immersive-ar", {
  optionalFeatures: ["layers"],
});

function onXRSessionStarted(xrSession) {
  const glCanvas = document.createElement("canvas");
  const gl = glCanvas.getContext("webgl", { xrCompatible: true });
  const xrGlBinding = new XRWebGLBinding(xrSession, gl);
  const projectionLayer = new XRWebGLLayer(xrSession, gl);
  const quadLayer = xrGlBinding.createQuadLayer({
    pixelWidth: 1024,
    pixelHeight: 1024,
  });

  xrSession.updateRenderState({
    layers: [projectionLayer, quadLayer],
  });

  xrSession.renderState.layers; // [projectionLayer, quadLayer]
}
```

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

| Specification |
| --- |
| WebXR Layers API Level 1 # dom-xrrenderstate-layers |

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

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

See also
--------

* `XRSession.updateRenderState()`


XRRenderState: inlineVerticalFieldOfView property - Web APIs

XRRenderState: inlineVerticalFieldOfView property
=================================================

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

 The read-only **`inlineVerticalFieldOfView`**
 property of the `XRRenderState` interface returns the default vertical
 field of view for `"inline"` sessions and `null` for all immersive
 sessions.

Value
-----

 A `Number` for `"inline"` sessions, which represents the default
 field of view, and `null` for immersive sessions.

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

| Specification |
| --- |
| WebXR Device API # dom-xrrenderstate-inlineverticalfieldofview |

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

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

See also
--------

* `navigator.xr.requestSession()`
* `navigator.xr.isSessionSupported()`


XRRenderState: baseLayer property - Web APIs

XRRenderState: baseLayer property
=================================

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

 The read-only **`baseLayer`** property of the
 `XRRenderState` interface returns the `XRWebGLLayer` instance
 that is the source of bitmap images and a description of how the image is to be rendered
 in the device.

 This property is read-only; however, you can indirectly change its
 value using `XRSession.updateRenderState`.

Value
-----

 A `XRWebGLLayer` object which is used as the source of the world's
 contents when rendering each frame of the scene.

 See the examples below to see how to use `updateRenderState()` to set the current `XRWebGLLayer` used for rendering
 the scene.

Examples
--------

 You can set the `XRWebGLLayer` used for rendering by calling
 `updateRenderState()`, like this:

```js
let canvas = document.querySelector("canvas");
gl = canvas.getContext("webgl", { xrCompatible: true });
setNewWebGLLayer();

function setNewWebGLLayer(gl) {
  if (!gl) {
    /\* WebGL not available \*/
    return;
  }

  xrSession.updateRenderState({
    baseLayer: new XRWebGLLayer(xrSession, gl),
  });
}
```

 Here, the canvas obtained in the first line is the canvas into which WebGL is going to
 draw. That context is passed into `new
 XRWebGLLayer()` to create an `XRWebGLLayer` which uses the contents of the
 WebGL context `gl` as the source of the world's image during presentation.

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

| Specification |
| --- |
| WebXR Device API # dom-xrrenderstate-baselayer |

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

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


XRRenderState: depthNear property - Web APIs

XRRenderState: depthNear property
=================================

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

 The **`depthNear`** read-only property of the
 `XRRenderState` interface returns the distance in meters of the near clip
 plane from the viewer.

Value
-----

A `Number`.

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

| Specification |
| --- |
| WebXR Device API # dom-xrrenderstate-depthnear |

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

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


XRRenderState: depthFar property - Web APIs

XRRenderState: depthFar property
================================

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

 The **`depthFar`** read-only property of the
 `XRRenderState` interface returns the distance in meters of the far clip
 plane from the viewer.

Value
-----

A `Number`.

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

| Specification |
| --- |
| WebXR Device API # dom-xrrenderstate-depthfar |

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

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


IdleDeadline: didTimeout property - Web APIs

IdleDeadline: didTimeout property
=================================

 The read-only **`didTimeout`** property on the
 **`IdleDeadline`** interface is a Boolean value which
 indicates whether or not the idle callback is being invoked because the timeout interval
 specified when `Window.requestIdleCallback()` was called has expired.

 If `didTimeout` is `true`, the `IdleDeadline` object's
 `timeRemaining()` method will return
 approximately 0.

 Idle callbacks support the concept of a timeout in order to ensure that whatever task
 they're meant to perform actually happens, even if the user agent never has enough idle
 time available. Your callback will typically check the value of `didTimeout`
 if it needs to perform an action even if the browser is too busy to grant you the time;
 you should react by performing the needed task or, ideally, a minimal amount of work
 that can be done to keep things moving along, then schedule a new callback to try again
 to get the rest of the work done.

Value
-----

 A Boolean which is `true` if the callback is running due to the callback's
 timeout period elapsing or `false` if the callback is running because the
 user agent is idle and is offering time to the callback.

Examples
--------

 See our complete example
 in the article Cooperative Scheduling of Background Tasks API.

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

| Specification |
| --- |
| requestIdleCallback() Cooperative Scheduling of Background Tasks # dom-idledeadline-didtimeout |

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

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

See also
--------

* Collaborative Scheduling of Background Tasks
* `IdleDeadline`
* `Window.requestIdleCallback()`
* `Window.cancelIdleCallback()`


IdleDeadline: timeRemaining() method - Web APIs

IdleDeadline: timeRemaining() method
====================================

 The **`timeRemaining()`** method
 on the `IdleDeadline` interface returns the estimated number of
 milliseconds remaining in the current idle period. The callback can call this method at
 any time to determine how much time it can continue to work before it must return. For
 example, if the callback finishes a task and has another one to begin, it can call
 `timeRemaining()` to see if there's enough time to complete the next task. If
 there isn't, the callback can just return immediately, or look for other work to do with
 the remaining time.

 By the time `timeRemaining()` reaches 0, it is suggested that the callback
 should return control to the user agent's event loop.

Syntax
------

```js
timeRemaining()
```

### Parameters

None.

### Return value

 A `DOMHighResTimeStamp` value (which is a floating-point number)
 representing the number of milliseconds the user agent estimates are left in the current
 idle period. The value is ideally accurate to within about 5 microseconds.

If the `IdleDeadline` object's `didTimeout` property is true, this method returns zero.

Examples
--------

 See our complete example
 in the article Cooperative Scheduling of Background Tasks API.

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

| Specification |
| --- |
| requestIdleCallback() Cooperative Scheduling of Background Tasks # dom-idledeadline-timeremaining |

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

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

See also
--------

* Collaborative Scheduling of Background Tasks
* `IdleDeadline`
* `Window.requestIdleCallback()`
* `Window.cancelIdleCallback()`


History: forward() method - Web APIs

History: forward() method
=========================

 The **`forward()`** method of the `History` interface causes the browser to move
 forward one page in the session history. It has the same effect as calling
 `history.go(1)`.

This method is asynchronous. Add a listener for the `popstate` event in order to determine when the navigation has completed.

Syntax
------

```js
forward()
```

### Parameters

None.

### Return value

None (`undefined`).

### Exceptions

`SecurityError` `DOMException`

Thrown if the associated document is not fully active.

Examples
--------

 The following examples create a button that moves forward one step in the session
 history.

### HTML

```html
<button id="go-forward">Go Forward!</button>
```

### JavaScript

```js
document.getElementById("go-forward").addEventListener("click", (e) => {
  history.forward();
});
```

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

| Specification |
| --- |
| HTML Standard # dom-history-forward-dev |

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

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

See also
--------

* `History`
* `popstate`
* Working with the History API


History: state property - Web APIs

History: state property
=======================

 The **`state`** read-only property of the `History` interface
 returns a value representing the state at the top of the history stack. This is
 a way to look at the state without having to wait for a `popstate` event.

Value
-----

 The state at the top of the history stack. The value is `null` until the
 `pushState()` or
 `replaceState()` method is used.

Examples
--------

 The code below logs the value of `history.state` before using the
 `pushState()` method to push a value to the history.
 The next line logs the value to the console again, showing that
 `history.state` now has a value.

```js
// Should be null because we haven't modified the history stack yet
console.log("History.state before pushState: ", history.state);

// Now push something on the stack
history.pushState({ name: "Example" }, "pushState example", "page3.html");

// Now state has a value.
console.log("History.state after pushState: ", history.state);
```

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

| Specification |
| --- |
| HTML Standard # dom-history-state-dev |

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

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

See also
--------

* Working with the History API
* `History.pushState()`
* `History.replaceState()`
* `PopStateEvent.state`


History: scrollRestoration property - Web APIs

History: scrollRestoration property
===================================

 The **`scrollRestoration`** property of the `History`
 interface allows web applications to explicitly set default scroll restoration behavior
 on history navigation.

Value
-----

One of the following:

`auto`

The location on the page to which the user has scrolled will be restored.

`manual`

 The location on the page is not restored. The user will have to scroll to the
 location manually.

Examples
--------

### Query the current scroll restoration behavior

```js
const scrollRestoration = history.scrollRestoration;
if (scrollRestoration === "manual") {
  console.log(
    "The location on the page is not restored, user will need to scroll manually.",
  );
}
```

### Prevent automatic page location restoration

```js
if (history.scrollRestoration) {
  history.scrollRestoration = "manual";
}
```

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

| Specification |
| --- |
| HTML Standard # dom-history-scroll-restoration-dev |

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

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


History: replaceState() method - Web APIs

History: replaceState() method
==============================

 The **`replaceState()`** method of the `History` interface modifies the current
 history entry, replacing it with the state object and
 URL passed in the method parameters. This method is particularly useful
 when you want to update the state object or URL of the current history entry in response
 to some user action.

Syntax
------

```js
replaceState(state, unused)
replaceState(state, unused, url)
```

### Parameters

`state`

 An object which is associated with the history entry
 passed to the `replaceState()` method. The state object can be
 `null`.

`unused`

This parameter exists for historical reasons, and cannot be omitted; passing the empty string is traditional, and safe against future changes to the method.

`url` Optional

 The URL of the history entry. The new URL must be of the same origin as the current
 URL; otherwise the `replaceState()` method throws an exception.

### Return value

None (`undefined`).

### Exceptions

`SecurityError` `DOMException`

Thrown if the associated document is not fully active, or if the provided `url` parameter is not a valid URL.

`DataCloneError` `DOMException`

Thrown if the provided `state` parameter is not serializable.

Examples
--------

Suppose `https://www.mozilla.org/foo.html` executes the following JavaScript:

```js
const stateObj = { foo: "bar" };
history.pushState(stateObj, "", "bar.html");
```

On the next page you could then use `history.state` to access the `stateObj` that was just added.

 The explanation of these two lines above can be found in the Working with the History API article. Then suppose
 `https://www.mozilla.org/bar.html` executes the following
 JavaScript:

```js
history.replaceState(stateObj, "", "bar2.html");
```

 This will cause the URL bar to display
 `https://www.mozilla.org/bar2.html`, but won't cause the browser
 to load `bar2.html` or even check that `bar2.html` exists.

 Suppose now that the user navigates to
 `https://www.microsoft.com`, then clicks the Back button. At this
 point, the URL bar will display `https://www.mozilla.org/bar2.html`.
 If the user now clicks Back again, the URL bar will
 display `https://www.mozilla.org/foo.html`, and totally bypass bar.html.

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

| Specification |
| --- |
| HTML Standard # dom-history-replacestate-dev |

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

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


History: pushState() method - Web APIs

History: pushState() method
===========================

 The **`pushState()`** method of the `History` interface adds an entry to the browser's
 session history stack.

Syntax
------

```js
pushState(state, unused)
pushState(state, unused, url)
```

### Parameters

`state`

 The `state` object is a JavaScript object which is associated with the
 new history entry created by `pushState()`. Whenever the user navigates to
 the new `state`, a `popstate` event is fired, and
 the `state` property of the event contains a copy of the history entry's
 `state` object.

The `state` object can be anything that can be serialized.

**Note:** Some browsers save `state` objects to the user's disk so they can be restored after the user restarts the browser, and impose a size limit on the serialized representation of a `state` object, and will throw an exception if you pass a `state` object whose serialized representation is larger than that size limit. So in cases where you want to ensure you have more space than what some browsers might impose, you're encouraged to use `sessionStorage` and/or `localStorage`.

`unused`

This parameter exists for historical reasons, and cannot be omitted; passing an empty string is safe against future changes to the method.

`url` Optional

 The new history entry's URL. Note that the browser won't
 attempt to load this URL after a call to `pushState()`, but it may
 attempt to load the URL later, for instance, after the user restarts the browser. The
 new URL does not need to be absolute; if it's relative, it's resolved relative to the
 current URL. The new URL must be of the same origin as the current
 URL; otherwise, `pushState()` will throw an exception. If this parameter
 isn't specified, it's set to the document's current URL.

### Return value

None (`undefined`).

### Exceptions

`SecurityError` `DOMException`

Thrown if the associated document is not fully active, or if the provided `url` parameter is not a valid URL.

`DataCloneError` `DOMException`

Thrown if the provided `state` parameter is not serializable.

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

 In a sense, calling `pushState()` is similar to
 setting `window.location = "#foo"`, in that both will also create and
 activate another history entry associated with the current document.
 But `pushState()` has a few advantages:

* The new URL can be any URL in the same origin as the current URL. In contrast,
 setting `window.location` keeps you at the same document only if you
 modify only the hash.
* Changing the page's URL is optional. In contrast,
 setting `window.location = "#foo";` only creates a new history entry if the
 current hash isn't `#foo`.
* You can associate arbitrary data with your new history entry. With the hash-based
 approach, you need to encode all of the relevant data into a short string.

 Note that `pushState()` never causes a `hashchange` event to be
 fired, even if the new URL differs from the old URL only in its hash.

Examples
--------

This creates a new browser history entry setting the *state* and *url*.

### JavaScript

```js
const state = { page\_id: 1, user\_id: 5 };
const url = "hello-world.html";

history.pushState(state, "", url);
```

### Change a query parameter

```js
const url = new URL(location);
url.searchParams.set("foo", "bar");
history.pushState({}, "", url);
```

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

| Specification |
| --- |
| HTML Standard # dom-history-pushstate-dev |

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

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

See also
--------

* Working with the History API
* Window: popstate event


History: back() method - Web APIs

History: back() method
======================

 The **`back()`** method of the `History` interface causes
 the browser to move back one page in the session history.

 It has the same
 effect as calling `history.go(-1)`. If there is no previous
 page, this method call does nothing.

 This method is asynchronous. Add a listener for the
 `popstate` event in order to determine when the navigation has completed.

Syntax
------

```js
back()
```

### Parameters

None.

### Return value

None (`undefined`).

### Exceptions

`SecurityError` `DOMException`

Thrown if the associated document is not fully active.

Examples
--------

 The following short example causes a button on the page to navigate back one entry in
 the session history.

### HTML

```html
<button id="go-back">Go back!</button>
```

### JavaScript

```js
document.getElementById("go-back").addEventListener("click", () => {
  history.back();
});
```

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

| Specification |
| --- |
| HTML Standard # dom-history-back-dev |

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

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

See also
--------

* `History`
* Working with the History API


History: length property - Web APIs

History: length property
========================

 The **`length`** read-only property of the `History` interface
 returns an integer representing the number of elements in the session
 history, including the currently loaded page.

For example, for a page loaded in a new tab this property returns `1`.

Value
-----

A number.

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

| Specification |
| --- |
| HTML Standard # dom-history-length-dev |

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

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

See also
--------

* The `History` interface it belongs to.


History: go() method - Web APIs

History: go() method
====================

 The **`go()`** method of the `History` interface loads a specific page from the
 session history. You can use it to move forwards and backwards through the history
 depending on the value of a parameter.

 This method is asynchronous. Add a listener for the
 `popstate` event in order to determine when the navigation has completed.

Syntax
------

```js
go()
go(delta)
```

### Parameters

`delta` Optional

 The position in the history to which you want to move, relative to the current page.
 A negative value moves backwards, a positive value moves forwards. So, for example,
 `history.go(2)` moves forward two pages and `history.go(-2)`
 moves back two pages. If no value is passed or if `delta` equals 0, it has
 the same result as calling `location.reload()`.

### Return value

None (`undefined`).

### Exceptions

`SecurityError` `DOMException`

Thrown if the associated document is not fully active.

Examples
--------

To move back one page (the equivalent of calling `back()`):

```js
history.go(-1);
```

To move forward a page, just like calling `forward()`:

```js
history.go(1);
```

To move forward two pages:

```js
history.go(2);
```

To move backwards by two pages:

```js
history.go(-2);
```

And, finally either of the following statements will reload the current page:

```js
history.go();
history.go(0);
```

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

| Specification |
| --- |
| HTML Standard # dom-history-go-dev |

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

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

See also
--------

* `History`
* `back()`
* `forward()`
* `popstate` event
* Working with the History API


VREyeParameters: minimumFieldOfView property - Web APIs

VREyeParameters: minimumFieldOfView property
============================================

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

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

The **`minimumFieldOfView`** read-only property of the `VREyeParameters` interface describes the minimum supported field of view for the current eye.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

Value
-----

A `VRFieldOfView` object.

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

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API
* `VRFieldOfView`


VREyeParameters: offset property - Web APIs

VREyeParameters: offset property
================================

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

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

The **`offset`** read-only property of the `VREyeParameters` interface represents the offset from the center point between the user's eyes to the center of the eye, measured in meters.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

This value should represent half the user's interpupillary distance (IPD), but may also represent the distance from the center point of the headset to the center point of the lens for the given eye.

Value
-----

A `Float32Array` representing a vector describing the offset from the center point between the users eyes to the center of the eye in meters.

**Note:** Values for the left eye will be negative; values for the right eye will be positive.

Examples
--------

See `VRFieldOfView` for example code.

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

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API


VREyeParameters: fieldOfView property - Web APIs

VREyeParameters: fieldOfView property
=====================================

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

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

The **`fieldOfView`** read-only property of the `VREyeParameters` interface returns a `VRFieldOfView` object describing the current field of view for the eye, which can vary as the user adjusts their interpupillary distance (IPD).

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

Value
-----

A `VRFieldOfView` object.

Examples
--------

See `VRFieldOfView` for example code.

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

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API


VREyeParameters: maximumFieldOfView property - Web APIs

VREyeParameters: maximumFieldOfView property
============================================

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

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

The **`maximumFieldOfView`** read-only property of the `VREyeParameters` interface describes the maximum supported field of view for the current eye.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

Value
-----

A `VRFieldOfView` object.

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

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API
* `VRFieldOfView`


VREyeParameters: renderWidth property - Web APIs

VREyeParameters: renderWidth property
=====================================

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

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

The **`renderWidth`** read-only property of the `VREyeParameters` interface describes the recommended render target width of each eye viewport, in pixels.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

This is already in device pixel units, so there's no need to multiply by Window.devicePixelRatio before setting to HTMLCanvasElement.width.

Value
-----

A number, representing the width in pixels.

Examples
--------

See `VREyeParameters` for example code.

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

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API


VREyeParameters: renderHeight property - Web APIs

VREyeParameters: renderHeight property
======================================

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

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

The **`renderHeight`** read-only property of the `VREyeParameters` interface describes the recommended render target height of each eye viewport, in pixels.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

This is already in device pixel units, so there's no need to multiply by Window.devicePixelRatio before setting to HTMLCanvasElement.height.

Value
-----

A number, representing the height in pixels.

Examples
--------

See `VREyeParameters` for example code.

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

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API


IDBObjectStore: deleteIndex() method - Web APIs

IDBObjectStore: deleteIndex() method
====================================

 The **`deleteIndex()`** method of the
 `IDBObjectStore` interface destroys the index with the specified name in
 the connected database, used during a version upgrade.

 Note that this method must be called only from a `VersionChange` transaction
 mode callback. Note that this method synchronously modifies the
 `IDBObjectStore.indexNames` property.

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

Syntax
------

```js
deleteIndex(indexName)
```

### Parameters

`indexName`

The name of the existing index to remove.

### Return value

None (`undefined`).

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the method was not called from a `versionchange` transaction mode callback.

`TransactionInactiveError` `DOMException`

Thrown if the transaction this `IDBObjectStore` belongs to is not active (e.g. has been deleted or removed.)

`NotFoundError` `DOMException`

Thrown if there is no index with the given name (case-sensitive) in the database.

Examples
--------

 In the following example you can see
 the `onupgradeneeded` handler being used to update the
 database structure if a database with a higher version number is loaded.
 `IDBObjectStore.createIndex` is used to create new indexes on the object
 store, after which we delete the unneeded old indexes with `deleteIndex()`.
 For a full working example, see our
 To-do Notifications app (view example live).

```js
let db;

// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

// these two event handlers act on the database being opened successfully, or not
DBOpenRequest.onerror = (event) => {
  note.innerHTML += "<li>Error loading database.</li>";
};

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable. This is used a lot below
  db = event.target.result;

  // Run the displayData() function to populate the task list with all the to-do list data already in the IDB
  displayData();
};

// This event handles the event whereby a new version of the database needs to be created
// Either one has not been created before, or a new version number has been submitted via the
// window.indexedDB.open line above
//it is only implemented in recent browsers
DBOpenRequest.onupgradeneeded = (event) => {
  const db = event.target.result;

  db.onerror = (event) => {
    note.innerHTML += "<li>Error loading database.</li>";
  };

  // Create an objectStore for this database
  const objectStore = db.createObjectStore("toDoList", {
    keyPath: "taskTitle",
  });

  // define what data items the objectStore will contain

  objectStore.createIndex("hours", "hours", { unique: false });
  objectStore.createIndex("minutes", "minutes", { unique: false });
  objectStore.createIndex("day", "day", { unique: false });
  objectStore.createIndex("month", "month", { unique: false });
  objectStore.createIndex("year", "year", { unique: false });
  objectStore.createIndex("notified", "notified", { unique: false });

  objectStore.deleteIndex("seconds");
  objectStore.deleteIndex("contact");
};
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-deleteindex① |

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).


IDBObjectStore: clear() method - Web APIs

IDBObjectStore: clear() method
==============================

 The **`clear()`** method of the `IDBObjectStore`
 interface creates and immediately returns an `IDBRequest` object, and
 clears this object store in a separate thread. This is for deleting all the current
 data out of an object store.

 Clearing an object store consists of removing all records from the object store and
 removing all records in indexes that reference the object store. To remove only some of
 the records in a store, use `IDBObjectStore.delete` passing a key
 or `IDBKeyRange`.

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

Syntax
------

```js
clear()
```

### 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

`ReadOnlyError` `DOMException`

Thrown if the transaction associated with this operation is in read-only mode.

`TransactionInactiveError` `DOMException`

Thrown if this `IDBObjectStore`'s transaction is inactive.

Examples
--------

 In the following code snippet, we open a read/write transaction on our database and
 clear all the current data out of the object store using `clear()`. For a
 full working example, see our To-do Notifications app
 (view example live).

```js
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable.
  // This is used a lot below
  db = DBOpenRequest.result;

  // Clear all the data from the object store
  clearData();
};

function clearData() {
  // open a read/write db transaction, ready for clearing the data
  const transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of the transaction completing, when everything is done
  transaction.oncomplete = (event) => {
    note.innerHTML += "<li>Transaction completed.</li>";
  };

  transaction.onerror = (event) => {
    note.innerHTML += `<li>Transaction not opened due to error: ${transaction.error}</li>`;
  };

  // create an object store on the transaction
  const objectStore = transaction.objectStore("toDoList");

  // Make a request to clear all the data out of the object store
  const objectStoreRequest = objectStore.clear();

  objectStoreRequest.onsuccess = (event) => {
    // report the success of our request
    note.innerHTML += "<li>Request successful.</li>";
  };
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-clear③ |

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).


IDBObjectStore: keyPath property - Web APIs

IDBObjectStore: keyPath property
================================

 The **`keyPath`** read-only property of the
 `IDBObjectStore` interface returns the key path of this object store.

 If this property is null, the application must provide a key for each modification
 operation.

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

Value
-----

Any value type.

Examples
--------

 In the following code snippet, we open a read/write transaction on our database and add
 some data to an object store using `add()`. After the object store has been
 created, we log `objectStore.keyPath` to
 the console. For a full working example, see our To-do Notifications app
 (view example live).

```js
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable.
  // This is used a lot below
  db = DBOpenRequest.result;

  // Run the addData() function to add the data to the database
  addData();
};

function addData() {
  // Create a new object ready to insert into the IDB
  const newItem = [
    {
      taskTitle: "Walk dog",
      hours: 19,
      minutes: 30,
      day: 24,
      month: "December",
      year: 2013,
      notified: "no",
    },
  ];

  // open a read/write db transaction, ready for adding the data
  const transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of the transaction completing, when everything is done
  transaction.oncomplete = (event) => {
    note.innerHTML += "<li>Transaction completed.</li>";
  };

  transaction.onerror = (event) => {
    note.innerHTML +=
      "<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
  };

  // create an object store on the transaction
  const objectStore = transaction.objectStore("toDoList");
  console.log(objectStore.keyPath);

  // Make a request to add our newItem object to the object store
  const objectStoreRequest = objectStore.add(newItem[0]);

  objectStoreRequest.onsuccess = (event) => {
    // report the success of our request
    note.innerHTML += "<li>Request successful.</li>";
  };
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-keypath① |

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).


IDBObjectStore: openCursor() method - Web APIs

IDBObjectStore: openCursor() method
===================================

 The **`openCursor()`** method of the
 `IDBObjectStore` interface returns an `IDBRequest` object,
 and, in a separate thread, returns a new `IDBCursorWithValue` object.
 Used for iterating through an object store with a cursor.

 To determine if the add operation has completed successfully, listen for the results's
 `success` event.

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

Syntax
------

```js
openCursor()
openCursor(query)
openCursor(query, direction)
```

### Parameters

`query` Optional

 A key or `IDBKeyRange` to be queried. If a single valid key is passed,
 this will default to a range containing only that key. If nothing is passed, this will
 default to a key range that selects all the records in this object store.

`direction` Optional

A string telling the cursor which direction to travel. The default is `next`. Valid values are:

`next`

 The cursor is opened at the start of the store; then, the cursor returns all records, even duplicates,
 in the increasing order of keys.

`nextunique`

 The cursor is opened at the start of the store; then, the cursor returns all records, that are not duplicates,
 in the increasing order of keys.

`prev`

 The cursor is opened at the start of the store; then, the cursor returns all records, even duplicates,
 in the decreasing order of keys.

`prevunique`

 The cursor is opened at the start of the store; then, the cursor returns all records, that are not duplicates,
 in the decreasing order of keys.

### 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:

* an `IDBCursorWithValue` object pointing at the first record matching the given query
* `null` if no matching records were found.
### Exceptions

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

`InvalidStateError` `DOMException`

Thrown if this `IDBObjectStore` or `IDBIndex` has been deleted.

`TransactionInactiveError` `DOMException`

Thrown if this `IDBObjectStore`'s transaction is inactive.

`DataError` `DOMException`

Thrown if the specified key or key range is invalid.

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:

```js
const transaction = db.transaction("name", "readonly");
const objectStore = transaction.objectStore("name");
const request = objectStore.openCursor();
request.onsuccess = (event) => {
  const cursor = event.target.result;
  if (cursor) {
    // cursor.value contains the current record being iterated through
    // this is where you'd do something with the result
    cursor.continue();
  } else {
    // no more results
  }
};
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-opencursor② |

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).


IDBObjectStore: autoIncrement property - Web APIs

IDBObjectStore: autoIncrement property
======================================

 The **`autoIncrement`** read-only property of the
 `IDBObjectStore` interface returns the value of the auto increment flag
 for this object store.

Note that every object store has its own separate auto increment counter.

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

Value
-----

A boolean value:

| Value | Meaning |
| --- | --- |
| `true` | The object store auto increments. |
| `false` | The object store does not auto increment. |

Examples
--------

 In the following code snippet, we open a read/write transaction on our database and add
 some data to an object store using `add()`. After the object store has been
 created, we log `objectStore.autoIncrement` to
 the console. For a full working example, see
 our To-do Notifications app
 (view example live).

```js
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable.
  // This is used a lot below
  db = DBOpenRequest.result;

  // Run the addData() function to add the data to the database
  addData();
};

function addData() {
  // Create a new object ready to insert into the IDB
  const newItem = [
    {
      taskTitle: "Walk dog",
      hours: 19,
      minutes: 30,
      day: 24,
      month: "December",
      year: 2013,
      notified: "no",
    },
  ];

  // open a read/write db transaction, ready for adding the data
  const transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of the transaction completing, when everything is done
  transaction.oncomplete = (event) => {
    note.innerHTML += "<li>Transaction completed.</li>";
  };

  transaction.onerror = (event) => {
    note.innerHTML +=
      "<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
  };

  // create an object store on the transaction
  const objectStore = transaction.objectStore("toDoList");
  console.log(objectStore.autoIncrement);

  // Make a request to add our newItem object to the object store
  const objectStoreRequest = objectStore.add(newItem[0]);

  objectStoreRequest.onsuccess = (event) => {
    // report the success of our request
    note.innerHTML += "<li>Request successful.</li>";
  };
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-autoincrement① |

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).


IDBObjectStore: getAll() method - Web APIs

IDBObjectStore: getAll() method
===============================

 The **`getAll()`** method of the
 `IDBObjectStore` interface returns an `IDBRequest` object
 containing all objects in the object store matching the specified parameter or all
 objects in the store if no parameters are given.

 If a value is successfully found, then a structured clone of it is created and set as
 the result of the request object.

This method produces the same result for:

* a record that doesn't exist in the database
* a record that has an undefined value

To tell these situations apart, you either call

1. the `openCursor()` method with the same
 key. That method provides a cursor if the record exists, and no cursor if it does not.
2. the `count()` method with the same key, which
 will return 1 if the row exists and 0 if it doesn't.
Syntax
------

```js
getAll()
getAll(query)
getAll(query, count)
```

### Parameters

`query` Optional

 A key or `IDBKeyRange` to be queried. If nothing is passed, this will
 default to a key range that selects all the records in this object store.

`count` Optional

 Specifies the number of values to return if more than one is found. If it is lower
 than `0` or greater than `2^32 - 1` a
 `TypeError` exception will be thrown.

### 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 an `Array` of the values of all records matching the given query, up to the value of `count`, if `count` was supplied.

### Exceptions

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

`TransactionInactiveError` `DOMException`

Thrown if this `IDBObjectStore`'s transaction is inactive.

`DataError` `DOMException`

Thrown if key or key range provided contains an invalid key or is null.

`InvalidStateError` `DOMException`

Thrown if the `IDBObjectStore` has been deleted or removed.

`TypeError`

Thrown if the `count` parameter is not between `0` and `2^32 - 1` included.

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-getall① |

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).


IDBObjectStore: getAllKeys() method - Web APIs

IDBObjectStore: getAllKeys() method
===================================

 The `getAllKeys()` method of the `IDBObjectStore`
 interface returns an `IDBRequest` object retrieves record keys for all
 objects in the object store matching the specified parameter or all objects in the
 store if no parameters are given.

 If a value is successfully found, then a structured clone of it is created and set as
 the result of the request object.

This method produces the same result for:

* a record that doesn't exist in the database
* a record that has an undefined value

 To tell these situations apart, you need to call the
 `openCursor()` method with the same key. That
 method provides a cursor if the record exists, and no cursor if it does not.

Syntax
------

```js
getAllKeys()
getAllKeys(query)
getAllKeys(query, count)
```

### Parameters

`query` Optional

A value that is or resolves to an `IDBKeyRange`.

`count` Optional

 Specifies the number of values to return if more than one is found. If it is lower
 than `0` or greater than `2^32 - 1` a
 `TypeError` exception will be thrown.

### 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 an `Array` of the keys for all records matching the given query, up to the value of `count`, if `count` was supplied.

### Exceptions

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

`TransactionInactiveError` `DOMException`

Thrown if this `IDBObjectStore`'s transaction is inactive.

`DataError` `DOMException`

Thrown if the key or key range provided contains an invalid key or is null.

`InvalidStateError` `DOMException`

Thrown if the `IDBObjectStore` has been deleted or removed.

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-getallkeys① |

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).


IDBObjectStore: getKey() method - Web APIs

IDBObjectStore: getKey() method
===============================

 The **`getKey()`** method of the
 `IDBObjectStore` interface returns an `IDBRequest` object,
 and, in a separate thread, returns the key selected by the specified query. This is
 for retrieving specific records from an object store.

 If a key is successfully found, then a structured clone of it is created and set as the
 result of the request object.

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

Syntax
------

```js
getKey(key)
```

### Parameters

`key`

The key or key range that identifies the record to be retrieved.

### 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 first record matching the given key or key range.

### Exceptions

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

`InvalidStateError` `DOMException`

Thrown if the `IDBObjectStore` has been deleted or removed.

`TransactionInactiveError` `DOMException`

Thrown if this `IDBObjectStore`'s transaction is inactive.

`DataError` `DOMException`

Thrown if the key or key range provided contains an invalid key.

Example
-------

```js
let openRequest = indexedDB.open("telemetry");
openRequest.onsuccess = (event) => {
  let db = event.target.result;
  let store = db.transaction("netlogs").objectStore("netlogs");

  let today = new Date();
  let yesterday = new Date(today);
  yesterday.setDate(today.getDate() - 1);
  let request = store.getKey(IDBKeyRange(yesterday, today));
  request.onsuccess = (event) => {
    let when = event.target.result;
    alert(`The 1st activity in last 24 hours was occurred at ${when}`);
  };
};
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-getkey① |

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).


IDBObjectStore: transaction property - Web APIs

IDBObjectStore: transaction property
====================================

 The **`transaction`** read-only property of the
 `IDBObjectStore` interface returns the transaction object to which this
 object store belongs.

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

Value
-----

An `IDBTransaction` object.

Examples
--------

 In the following code snippet, we open a read/write transaction on our database and add
 some data to an object store using `add()`. After the object store has been
 created, we log `objectStore.transaction` to
 the console. For a full working example, see our To-do Notifications app
 (view example live).

```js
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable.
  // This is used a lot below
  db = DBOpenRequest.result;

  // Run the addData() function to add the data to the database
  addData();
};

function addData() {
  // Create a new object ready to insert into the IDB
  const newItem = [
    {
      taskTitle: "Walk dog",
      hours: 19,
      minutes: 30,
      day: 24,
      month: "December",
      year: 2013,
      notified: "no",
    },
  ];

  // open a read/write db transaction, ready for adding the data
  const transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of the transaction completing, when everything is done
  transaction.oncomplete = (event) => {
    note.innerHTML += "<li>Transaction completed.</li>";
  };

  transaction.onerror = (event) => {
    note.innerHTML +=
      "<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
  };

  // create an object store on the transaction
  const objectStore = transaction.objectStore("toDoList");
  console.log(objectStore.transaction);

  // Make a request to add our newItem object to the object store
  const objectStoreRequest = objectStore.add(newItem[0]);

  objectStoreRequest.onsuccess = (event) => {
    // report the success of our request
    note.innerHTML += "<li>Request successful.</li>";
  };
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-transaction① |

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).


IDBObjectStore: get() method - Web APIs

IDBObjectStore: get() method
============================

 The **`get()`** method of the `IDBObjectStore`
 interface returns an `IDBRequest` object, and, in a separate thread,
 returns the object selected by the specified key. This is for retrieving
 specific records from an object store.

 If a value is successfully found, then a structured clone of it is created and set as
 the `result` of the
 request object.

**Note:** This method produces the same result for: a) a record that doesn't exist in the database and b) a record that has an undefined value.
 To tell these situations apart, call the `openCursor()` method with the same key. That method provides a cursor if the record exists, and no cursor if it does not.

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

Syntax
------

```js
get(key)
```

### Parameters

`key`

The key or key range that identifies the record to be retrieved.

### 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 value of the first record matching the given key or key range.

### Exceptions

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

`TransactionInactiveError` `DOMException`

Thrown if this `IDBObjectStore`'s transaction is inactive.

`DataError` `DOMException`

Thrown if key or key range provided contains an invalid key.

`InvalidStateError` `DOMException`

Thrown if the `IDBObjectStore` has been deleted or removed.

Examples
--------

 In the following code snippet, we open a read/write transaction on our database and get
 one specific record from object store using `get()` — a sample record with
 the key "Walk dog". Once this data object is retrieved, you could then update it using
 normal JavaScript, then put it back into the database using a
 `IDBObjectStore.put` operation. For a full working example, see our To-do Notifications app
 (view example live).

```js
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable.
  // This is used a lot below
  db = DBOpenRequest.result;

  // Run the getData() function to get the data from the database
  getData();
};

function getData() {
  // open a read/write db transaction, ready for retrieving the data
  const transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of the transaction completing, when everything is done
  transaction.oncomplete = (event) => {
    note.innerHTML += "<li>Transaction completed.</li>";
  };

  transaction.onerror = (event) => {
    note.innerHTML += `<li>Transaction not opened due to error: ${transaction.error}</li>`;
  };

  // create an object store on the transaction
  const objectStore = transaction.objectStore("toDoList");

  // Make a request to get a record by key from the object store
  const objectStoreRequest = objectStore.get("Walk dog");

  objectStoreRequest.onsuccess = (event) => {
    // report the success of our request
    note.innerHTML += "<li>Request successful.</li>";

    const myRecord = objectStoreRequest.result;
  };
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-get① |

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).


IDBObjectStore: add() method - Web APIs

IDBObjectStore: add() method
============================

The **`add()`** method of the `IDBObjectStore` interface returns an `IDBRequest` object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. This is for adding new records to an object store.

 To determine if the add operation has completed successfully, listen for the
 transaction's `complete` event in addition to the
 `IDBObjectStore.add` request's `success` event, because the
 transaction may still fail after the success event fires. In other words, the success
 event is only triggered when the transaction has been successfully queued.

 The add method is an *insert only* method. If a
 record already exists in the object store with the `key` parameter as its
 key, then an error `ConstraintError` event is fired on the returned request
 object. For updating existing records, you should use the
 `IDBObjectStore.put` method instead.

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

Syntax
------

```js
add(value)
add(value, key)
```

### Parameters

`value`

The value to be stored.

`key` Optional

The key to use to identify the record. If unspecified, it results to null.

### 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 new record.

### Exceptions

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

`ReadOnlyError` `DOMException`

Thrown if the transaction associated with this operation is in read-only mode.

`TransactionInactiveError` `DOMException`

Thrown if this `IDBObjectStore`'s transaction is inactive.

`DataError` `DOMException`

Thrown if any of the following conditions apply:

* The object store uses in-line keys or has a key generator, and a key parameter was provided.
* The object store uses out-of-line keys and has no key generator, and no key parameter was provided.
* The object store uses in-line keys but no key generator, and the object store's key path does not yield a valid key.
* The key parameter was provided but does not contain a valid key.

`InvalidStateError` `DOMException`

Thrown if the `IDBObjectStore` has been deleted or removed.

`DataCloneError` `DOMException`

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

`ConstraintError` `DOMException`

 Thrown if an insert operation failed because the primary key constraint was
 violated (due to an already existing record with the same primary key
 value).

Examples
--------

 In the following code snippet, we open a read/write transaction on our database and add
 some data to an object store using `add()`. Note also the functions attached
 to transaction event handlers to report on the outcome of the transaction opening in the
 event of success or failure. For a full working example, see our To-do Notifications app (view example live).

```js
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable.
  // This is used a lot below
  db = DBOpenRequest.result;

  // Run the addData() function to add the data to the database
  addData();
};

function addData() {
  // Create a new object ready to insert into the IDB
  const newItem = [
    {
      taskTitle: "Walk dog",
      hours: 19,
      minutes: 30,
      day: 24,
      month: "December",
      year: 2013,
      notified: "no",
    },
  ];

  // open a read/write db transaction, ready for adding the data
  const transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of the transaction completing, when everything is done
  transaction.oncomplete = (event) => {
    note.innerHTML += "<li>Transaction completed.</li>";
  };

  transaction.onerror = (event) => {
    note.innerHTML +=
      "<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
  };

  // create an object store on the transaction
  const objectStore = transaction.objectStore("toDoList");

  // Make a request to add our newItem object to the object store
  const objectStoreRequest = objectStore.add(newItem[0]);

  objectStoreRequest.onsuccess = (event) => {
    // report the success of our request
    note.innerHTML += "<li>Request successful.</li>";
  };
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-add① |

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).


IDBObjectStore: indexNames property - Web APIs

IDBObjectStore: indexNames property
===================================

 The **`indexNames`** read-only property of the
 `IDBObjectStore` interface returns a list of the names of indexes on objects
 in this object store.

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

Value
-----

A `DOMStringList`.

Examples
--------

 In the following code snippet, we open a read/write transaction on our database and add
 some data to an object store using `add()`. After the object store has been
 created, we log `objectStore.indexNames` to the console. For a full working example, see
 our To-do Notifications app
 (view example live).

```js
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable.
  // This is used a lot below
  db = this.result;

  // Run the addData() function to add the data to the database
  addData();
};

function addData() {
  // Create a new object ready to insert into the IDB
  const newItem = [
    {
      taskTitle: "Walk dog",
      hours: 19,
      minutes: 30,
      day: 24,
      month: "December",
      year: 2013,
      notified: "no",
    },
  ];

  // open a read/write db transaction, ready for adding the data
  const transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of the transaction completing, when everything is done
  transaction.oncomplete = (event) => {
    note.innerHTML += "<li>Transaction completed.</li>";
  };

  transaction.onerror = (event) => {
    note.innerHTML +=
      "<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
  };

  // create an object store on the transaction
  const objectStore = transaction.objectStore("toDoList");
  console.log(objectStore.indexNames);

  // Make a request to add our newItem object to the object store
  const objectStoreRequest = objectStore.add(newItem[0]);

  objectStoreRequest.onsuccess = (event) => {
    // report the success of our request
    note.innerHTML += "<li>Request successful.</li>";
  };
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-indexnames① |

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).


IDBObjectStore: openKeyCursor() method - Web APIs

IDBObjectStore: openKeyCursor() method
======================================

 The **`openKeyCursor()`** method of the
 `IDBObjectStore` interface returns an `IDBRequest` object
 whose result will be set to an `IDBCursor` that can be used to iterate
 through matching results. Used for iterating through the keys of an object store with
 a cursor.

 To determine if the add operation has completed successfully, listen for the
 results's `success` event.

Syntax
------

```js
openKeyCursor()
openKeyCursor(query)
openKeyCursor(query, direction)
```

### Parameters

`query` Optional

 The key range to be queried. If a single valid key is passed, this will default to a
 range containing only that key. If nothing is passed, this will default to a key range
 that selects all the records in this object store.

`direction` Optional

 An `IDBCursorDirection` telling the cursor what direction to travel.
 Valid values are `"next"`, `"nextunique"`, `"prev"`,
 and `"prevunique"`. The default is `"next"`.

### 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:

* an `IDBCursor` object pointing at the first record matching the given query
* `null` if no matching records were found.
### Exceptions

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

`InvalidStateError` `DOMException`

Thrown if this `IDBObjectStore` or `IDBIndex` has been deleted.

`TransactionInactiveError` `DOMException`

Thrown if this `IDBObjectStore`'s transaction is inactive.

`DataError` `DOMException`

Thrown if the specified key or key range is invalid.

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:

```js
const transaction = db.transaction("name", "readonly");
const objectStore = transaction.objectStore("name");
const request = objectStore.openKeyCursor();
request.onsuccess = (event) => {
  const cursor = event.target.result;
  if (cursor) {
    // cursor.key contains the key of the current record being iterated through
    // note that there is no cursor.value, unlike for openCursor
    // this is where you'd do something with the result
    cursor.continue();
  } else {
    // no more results
  }
};
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-openkeycursor① |

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).


IDBObjectStore: count() method - Web APIs

IDBObjectStore: count() method
==============================

 The **`count()`** method of the `IDBObjectStore`
 interface returns an `IDBRequest` object, and, in a separate thread,
 returns the total number of records that match the provided key or
 `IDBKeyRange`. If no arguments are provided, it returns the total number
 of records in the store.

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

Syntax
------

```js
count()
count(query)
```

### Parameters

`query` Optional

 A key or `IDBKeyRange` object that specifies a range of records you
 want to count.

### 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 number of records that match the given query.

### Exceptions

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

`InvalidStateError` `DOMException`

Thrown if this `IDBObjectStore` has been deleted.

`TransactionInactiveError` `DOMException`

Thrown if this `IDBObjectStore`'s transaction is inactive.

`DataError` `DOMException`

Thrown if the specified key or key range is invalid.

Examples
--------

 In this simple fragment we create a transaction, retrieve an object store, then count
 the number of records in the store using `count()` — when the success handler
 fires, we log the count value (an integer) to the console.

```js
const transaction = db.transaction(["fThings"], "readonly");
const objectStore = transaction.objectStore("fThings");

const countRequest = objectStore.count();
countRequest.onsuccess = () => {
  console.log(countRequest.result);
};
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-count① |

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).


IDBObjectStore: delete() method - Web APIs

IDBObjectStore: delete() method
===============================

 The **`delete()`** method of the
 `IDBObjectStore` interface returns an `IDBRequest` object,
 and, in a separate thread, deletes the specified record or records.

 Either a key or an `IDBKeyRange` can be passed, allowing one or multiple
 records to be deleted from a store. To delete all records in a store, use
 `IDBObjectStore.clear`.

 Bear in mind that if you are using a `IDBCursor`, you can use
 the `IDBCursor.delete()` method to more efficiently delete the current
 record — without having to explicitly look up the record's key.

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

Syntax
------

```js
delete(key)
```

### Parameters

`key`

 The key of the record to be deleted, or an `IDBKeyRange` to delete all
 records with keys in range.

### 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 the following types:

`TransactionInactiveError` `DOMException`

Thrown if this object store's transaction is inactive.

`ReadOnlyError` `DOMException`

Thrown if the object store's transaction mode is read-only.

`InvalidStateError` `DOMException`

Thrown if the object store has been deleted.

`DataError` `DOMException`

Thrown if `key` is not a valid key or a key range.

Examples
--------

 The following code snippet shows the `deleteItem()` function,
 which is part of the To-do Notifications example app. This app stores to-do
 list items using IndexedDB. You can
 see the app's complete code on GitHub, and
 try out the app live.

 The `deleteItem()` function is called when the user clicks the
 button to delete a to-do list item. The item key is set in the button's
 `'data-task'` data attribute, so the function
 knows which item to delete. The function opens a database transaction in
 which to delete the item, supplying its key. When the transaction completes,
 the function updates the app UI to report that the item was deleted.

 Note that in this function `db` is a global variable
 referring to an `IDBDatabase` object that is initialized when
 the app loads.

```js
function deleteItem(event) {
  // retrieve the name of the task we want to delete
  let dataTask = event.target.getAttribute("data-task");

  // open a database transaction and delete the task, finding it by the name we retrieved above
  let transaction = db.transaction(["toDoList"], "readwrite");
  let request = transaction.objectStore("toDoList").delete(dataTask);

  // report that the data item has been deleted
  transaction.oncomplete = () => {
    // delete the parent of the button, which is the list item, so it no longer is displayed
    event.target.parentNode.parentNode.removeChild(event.target.parentNode);
    note.innerHTML += `<li>Task "${dataTask}" deleted.</li>`;
  };
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-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).


IDBObjectStore: createIndex() method - Web APIs

IDBObjectStore: createIndex() method
====================================

 The **`createIndex()`** method of the
 `IDBObjectStore` interface creates and returns a new
 `IDBIndex` object in the connected database. It creates a new
 field/column defining a new data point for each database record to contain.

 Bear in mind that IndexedDB indexes can contain *any* JavaScript data type;
 IndexedDB uses the structured clone algorithm to serialize stored objects, which allows for storage of simple
 and complex objects.

 Note that this method must be called only from a `VersionChange` transaction
 mode callback.

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

Syntax
------

```js
createIndex(indexName, keyPath)
createIndex(indexName, keyPath, options)
```

### Parameters

`indexName`

 The name of the index to create. Note that it is possible to create an index with an
 empty name.

`keyPath`

 The key path for the index to use. Note that it is possible to create an index with
 an empty `keyPath`, and also to pass in a sequence (array) as a
 `keyPath`.

`options` Optional

 An object which can include the following
 properties:

`unique`

If `true`, the index will not allow duplicate values for a single key. Defaults to `false`.

`multiEntry`

 If `true`, the index will add an entry in the index for each array element when the `keyPath` resolves to an array.
 If `false`, it will add one single entry containing the array. Defaults to `false`.

`locale`
Non-standard

 Currently Firefox-only (43+), this allows you to specify a locale for the index.
 Any sorting operations performed on the data via key ranges will then obey sorting rules of that locale
 (see locale-aware sorting).
 You can specify its value in one of three ways:

* `string`: A string containing a specific locale code, e.g. `en-US`, or `pl`.
* `auto`: The platform default locale will be used (may be changed by user agent settings).
* `null` or `undefined`: If no locale is specified, normal JavaScript sorting will be used — not locale-aware.

### Return value

An `IDBIndex` object: the newly created index.

### Exceptions

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

`ConstraintError` `DOMException`

Thrown if an index with the same name already exists in the database. Index names are case-sensitive.

`InvalidAccessError` `DOMException`

Thrown if the provided key path is a sequence, and `multiEntry` is set to `true` in the `objectParameters` object.

`InvalidStateError` `DOMException`

Thrown if:

* The method was not called from a `versionchange` transaction mode callback, i.e. from inside a `onupgradeneeded` handler.
* The object store has been deleted.

`SyntaxError` `DOMException`

Thrown if the provided `keyPath` is not a valid key path.

`TransactionInactiveError` `DOMException`

 Thrown if the transaction this `IDBObjectStore`
 belongs to is not active (e.g. has been deleted or removed.) In Firefox
 previous to version 41, an `InvalidStateError` was raised in
 this case as well, which was misleading; this has now been fixed (see
 Firefox bug 1176165.)

Examples
--------

 In the following example you can see
 the `onupgradeneeded` handler being used to update the
 database structure if a database with a higher version number is loaded.
 `createIndex()` is used to create new indexes on the object store. For a
 full working example, see our To-do Notifications app (view example live).

```js
let db;

// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

// Two event handlers for opening the database.
DBOpenRequest.onerror = (event) => {
  note.innerHTML += "<li>Error loading database.</li>";
};

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable.
  // This is used a lot below.
  db = request.result;

  // Run the displayData() function to populate the task list with
  // all the to-do list data already in the IDB
  displayData();
};

// This handler fires when a new database is created and indicates
// either that one has not been created before, or a new version
// was submitted with window.indexedDB.open(). (See above.)
// It is only implemented in recent browsers.
DBOpenRequest.onupgradeneeded = (event) => {
  const db = event.target.result;

  db.onerror = (event) => {
    note.innerHTML += "<li>Error loading database.</li>";
  };

  // Create an objectStore for this database
  const objectStore = db.createObjectStore("toDoList", {
    keyPath: "taskTitle",
  });

  // define what data items the objectStore will contain

  objectStore.createIndex("hours", "hours", { unique: false });
  objectStore.createIndex("minutes", "minutes", { unique: false });
  objectStore.createIndex("day", "day", { unique: false });
  objectStore.createIndex("month", "month", { unique: false });
  objectStore.createIndex("year", "year", { unique: false });
  objectStore.createIndex("notified", "notified", { unique: false });
};
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-createindex① |

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).


IDBObjectStore: index() method - Web APIs

IDBObjectStore: index() method
==============================

 The **`index()`** method of the `IDBObjectStore`
 interface opens a named index in the current object store, after which it can be used
 to, for example, return a series of records sorted by that index using a cursor.

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

Syntax
------

```js
index(name)
```

### Parameters

`name`

The name of the index to open.

### Return value

An `IDBIndex` object for accessing the index.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the source object store has been deleted, or the transaction for the object store has finished.

`NotFoundError` `DOMException`

Thrown if there is no index with the given name (case-sensitive) in the database.

Examples
--------

 In the following example we open a transaction and an object store, then get the index
 `lName` from a simple contacts database. We then open a basic cursor on the
 index using `IDBIndex.openCursor` — this works the same as opening a cursor
 directly on an `ObjectStore` using `IDBObjectStore.openCursor`
 except that the returned records are sorted based on the index, not the primary key.

 Finally, we iterate through each record, and insert the data into an HTML table. For a
 complete working example, see our IDBIndex example in IndexedDB-examples demo repo (View the example live.)

```js
function displayDataByIndex() {
  tableEntry.innerHTML = "";
  const transaction = db.transaction(["contactsList"], "readonly");
  const objectStore = transaction.objectStore("contactsList");

  const myIndex = objectStore.index("lName");
  myIndex.openCursor().onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const tableRow = document.createElement("tr");
      tableRow.innerHTML =
        `<td>${cursor.value.id}</td>` +
        `<td>${cursor.value.lName}</td>` +
        `<td>${cursor.value.fName}</td>` +
        `<td>${cursor.value.jTitle}</td>` +
        `<td>${cursor.value.company}</td>` +
        `<td>${cursor.value.eMail}</td>` +
        `<td>${cursor.value.phone}</td>` +
        `<td>${cursor.value.age}</td>`;
      tableEntry.appendChild(tableRow);

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

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

| Specification |
| --- |
| Indexed Database API 3.0 # dom-idbobjectstore-index |

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).


IDBObjectStore: put() method - Web APIs

IDBObjectStore: put() method
============================

The **`put()`** method of the `IDBObjectStore` interface updates a given record in a database, or inserts a new record if the given item does not already exist.

It returns an `IDBRequest` object, and, in a separate thread, creates a structured clone of the value and stores the cloned value in the object store. This is for adding new records, or updating existing records in an object store when the transaction's mode is `readwrite`. If the record is successfully stored, then a success event is fired on the returned request object with the `result` set to the key for the stored record, and the `transaction` set to the transaction in which this object store is opened.

 The put method is an *update or insert* method.
 See the `IDBObjectStore.add` method for an *insert only* method.

 Bear in mind that if you have a `IDBCursor` to the record you
 want to update, updating it with `IDBCursor.update()` is preferable to
 using `IDBObjectStore.put()`. Doing so makes it clear that an existing
 record will be updated, instead of a new record being inserted.

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

Syntax
------

```js
put(item)
put(item, key)
```

### Parameters

`item`

The item you wish to update (or insert).

`key` Optional

 The primary key of the record you want to update (e.g. from
 `IDBCursor.primaryKey`).

### 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 new or updated record.

### Exceptions

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

`ReadOnlyError` `DOMException`

Thrown if the transaction associated with this operation is in read-only mode.

`TransactionInactiveError` `DOMException`

Thrown if this `IDBObjectStore`'s transaction is inactive.

`DataError` `DOMException`

Thrown if any of the following conditions apply:

* The object store uses in-line keys or has a key generator, and a `key` parameter was provided.
* The object store uses out-of-line keys and has no key generator, and no `key` parameter was provided.
* The object store uses in-line keys but no `key` generator, and the object store's key path does not yield a valid key.
* The `key` parameter was provided but does not contain a valid key.

`InvalidStateError` `DOMException`

Thrown if the `IDBObjectStore` has been deleted or removed.

`DataCloneError` `DOMException`

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

Examples
--------

 The following example requests a given record title; when that request is successful
 the `onsuccess` function gets the associated record from the
 `IDBObjectStore` (made available
 as `objectStoreTitleRequest.result`), updates
 one property of the record, and then puts the updated record back into the object
 store in another request with `put()`. For a full working example, see
 our To-do Notifications app
 (view example live).

```js
const title = "Walk dog";

// Open up a transaction as usual
const objectStore = db
  .transaction(["toDoList"], "readwrite")
  .objectStore("toDoList");

// Get the to-do list object that has this title as it's title
const objectStoreTitleRequest = objectStore.get(title);

objectStoreTitleRequest.onsuccess = () => {
  // Grab the data object returned as the result
  const data = objectStoreTitleRequest.result;

  // Update the notified value in the object to "yes"
  data.notified = "yes";

  // Create another request that inserts the item back into the database
  const updateTitleRequest = objectStore.put(data);

  // Log the transaction that originated this request
  console.log(
    `The transaction that originated this request is ${updateTitleRequest.transaction}`,
  );

  // When this new request succeeds, run the displayData() function again to update the display
  updateTitleRequest.onsuccess = () => {
    displayData();
  };
};
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-put① |

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).