XPathResult: snapshotLength property - Web APIs

XPathResult: snapshotLength property
====================================

 The read-only **`snapshotLength`** property of the
 `XPathResult` interface represents the number of nodes in the result
 snapshot.

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

Value
-----

An integer value representing the number of nodes in the result snapshot.

### Exceptions

#### TYPE\_ERR

 In case `XPathResult.resultType` is not
 `UNORDERED_NODE_SNAPSHOT_TYPE` or `ORDERED_NODE_SNAPSHOT_TYPE`, an
 `XPathException` of type `TYPE_ERR` is thrown.

Examples
--------

The following example shows the use of the `snapshotLength` property.

### HTML

```html
<div>XPath example</div>
<div>Number of matched nodes: <output></output></div>
```

### JavaScript

```js
const xpath = "//div";
const result = document.evaluate(
  xpath,
  document,
  null,
  XPathResult.ORDERED\_NODE\_SNAPSHOT\_TYPE,
  null,
);
document.querySelector("output").textContent = result.snapshotLength;
```

### Result

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

| Specification |
| --- |
| DOM Standard # dom-xpathresult-snapshotlength |

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

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


XPathResult: numberValue property - Web APIs

XPathResult: numberValue property
=================================

 The read-only **`numberValue`** property of the
 `XPathResult` interface returns the numeric value of a result with
 `XPathResult.resultType` being `NUMBER_TYPE`.

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

Value
-----

 The return value is the numeric value of the `XPathResult` returned by
 `Document.evaluate()`.

### Exceptions

#### TYPE\_ERR

 In case `XPathResult.resultType` is not `NUMBER_TYPE`, an
 `XPathException` of type `TYPE_ERR` is thrown.

Examples
--------

The following example shows the use of the `numberValue` property.

### HTML

```html
<div>XPath example</div>
<div>Number of <div>s: <output></output></div>
```

### JavaScript

```js
const xpath = "count(//div)";
const result = document.evaluate(
  xpath,
  document,
  null,
  XPathResult.NUMBER\_TYPE,
  null,
);
document.querySelector("output").textContent = result.numberValue;
```

### Result

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

| Specification |
| --- |
| DOM Standard # dom-xpathresult-numbervalue |

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

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


XPathResult: iterateNext() method - Web APIs

XPathResult: iterateNext() method
=================================

 The **`iterateNext()`** method of the
 `XPathResult` interface iterates over a node set result and returns the
 next node from it or `null` if there are no more nodes.

Syntax
------

```js
iterateNext()
```

### Parameters

None.

### Return value

The next `Node` within the node set of the `XPathResult`.

### Exceptions

#### TYPE\_ERR

 In case `XPathResult.resultType` is not
 `UNORDERED_NODE_ITERATOR_TYPE` or `ORDERED_NODE_ITERATOR_TYPE`, an
 `XPathException` of type `TYPE_ERR` is thrown.

#### INVALID\_STATE\_ERR

 If the document is mutated since the result was returned, an
 `XPathException` of type `INVALID_STATE_ERR` is thrown.

Examples
--------

The following example shows the use of the `iterateNext()` method.

### HTML

```html
<div>XPath example</div>
<div>Tag names of the matched nodes: <output></output></div>
```

### JavaScript

```js
const xpath = "//div";
const result = document.evaluate(
  xpath,
  document,
  null,
  XPathResult.ANY\_TYPE,
  null,
);
let node = null;
const tagNames = [];
while ((node = result.iterateNext())) {
  tagNames.push(node.localName);
}
document.querySelector("output").textContent = tagNames.join(", ");
```

### Result

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

| Specification |
| --- |
| DOM Standard # dom-xpathresult-iteratenext |

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

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


WakeLockSentinel: type property - Web APIs

WakeLockSentinel: type property
===============================

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

The **`type`** read-only property of the `WakeLockSentinel` interface returns a string representation of the currently acquired `WakeLockSentinel` type.

Value
-----

 A string representation of the currently acquired wake lock type.
 Currently, the value is always `screen`, which represents a screen wake lock.
 It prevents devices from dimming or locking the screen.

Examples
--------

This example shows an asynchronous function that acquires a `WakeLockSentinel`, then logs the type to the console.

```js
const requestWakeLock = async () => {
  wakeLock = await navigator.wakeLock.request("screen");
  console.log(wakeLock.type); // logs 'screen'
};

requestWakeLock();
```

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

| Specification |
| --- |
| Screen Wake Lock API # the-type-attribute |

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

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

See also
--------

* Stay awake with the Screen Wake Lock API


WakeLockSentinel: released property - Web APIs

WakeLockSentinel: released property
===================================

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

The **`released`** read-only property of the `WakeLockSentinel` interface returns a boolean that indicates whether a `WakeLockSentinel` has been released.

 The `WakeLockSentinel` is released when the associated platform screen wake lock is revoked; afterwards `released` will always return `true`.
 If a subsequent screen wake lock is required, the application will need to request a new screen wake lock (the current `WakeLockSentinel` cannot be reused).

Value
-----

A boolean value that is `false` until the `WakeLockSentinel` has been released (either through a call to `WakeLockSentinel.release()` or because the lock has been released automatically) and the `release` event has been emitted, after which it becomes `true` and no longer changes.

Examples
--------

This example shows how the value of the `released` property changes within a `WakeLockSentinel`'s life cycle.

```js
const sentinel = await navigator.wakeLock.request("screen");
console.log(sentinel.released); // Logs "false"

sentinel.onrelease = () => {
  console.log(sentinel.released); // Logs "true"
};

await sentinel.release();
```

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

| Specification |
| --- |
| Screen Wake Lock API # dom-wakelocksentinel-released |

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

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

See also
--------

* Stay awake with the Screen Wake Lock API


WakeLockSentinel: release event - Web APIs

WakeLockSentinel: release event
===============================

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

The **`release`** event of the `WakeLockSentinel` interface is fired when the sentinel object's handle has been released.

 A `WakeLockSentinel` can be released manually via the `release()` method, or automatically via the platform wake lock.
 This can happen if the document becomes inactive or looses visibility, if the device is low on power or the user turns on a power save mode.

Syntax
------

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

```js
addEventListener("release", (event) => {});

onrelease = (event) => {};
```

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

A generic `Event`.

Examples
--------

This example updates the UI if the wake lock is released.

```js
wakeLock.addEventListener("release", () => {
  // if wake lock is released alter the UI accordingly
  statusElement.textContent = "Wake Lock has been released";
});
```

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

| Specification |
| --- |
| Screen Wake Lock API # the-onrelease-attribute |

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

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

See also
--------

* Stay awake with the Screen Wake Lock API


WakeLockSentinel: release() method - Web APIs

WakeLockSentinel: release() method
==================================

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

The **`release()`** method of the `WakeLockSentinel` interface releases the `WakeLockSentinel`, returning a `Promise` that is resolved once the sentinel has been successfully released.

Syntax
------

```js
release()
```

### Parameters

None.

### Return value

Returns a `Promise` that resolves with `undefined`.

### Exceptions

 No exceptions are thrown.
 You should always listen for the `release` event to check if a wake lock has been released.

Examples
--------

In this example, when a user clicks a button the `WakeLockSentinel` is released.

```js
wakeLockOffButton.addEventListener("click", () => {
  WakeLockSentinel.release();
});
```

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

| Specification |
| --- |
| Screen Wake Lock API # the-release-method |

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

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

See also
--------

* Stay awake with the Screen Wake Lock API


SecurityPolicyViolationEvent: violatedDirective property - Web APIs

SecurityPolicyViolationEvent: violatedDirective property
========================================================

 The **`violatedDirective`** read-only property of the
 `SecurityPolicyViolationEvent` interface is a string
 representing the directive whose enforcement uncovered the violation.

Value
-----

 A string representing the directive whose enforcement uncovered the
 violation.

Examples
--------

```js
document.addEventListener("securitypolicyviolation", (e) => {
  console.log(e.violatedDirective);
});
```

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

| Specification |
| --- |
| Content Security Policy Level 3 # dom-securitypolicyviolationevent-violateddirective |

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

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

See also
--------

* Content Security Policy (CSP)


SecurityPolicyViolationEvent: columnNumber property - Web APIs

SecurityPolicyViolationEvent: columnNumber property
===================================================

 The **`columnNumber`** read-only property of the
 `SecurityPolicyViolationEvent` interface is the column number in the
 document or worker at which the violation occurred.

Value
-----

A number representing the column number where the violation occurred.

Examples
--------

```js
document.addEventListener("securitypolicyviolation", (e) => {
  console.log(e.columnNumber);
});
```

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

| Specification |
| --- |
| Content Security Policy Level 3 # dom-securitypolicyviolationevent-columnnumber |

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

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

See also
--------

* Content Security Policy (CSP)


SecurityPolicyViolationEvent: statusCode property - Web APIs

SecurityPolicyViolationEvent: statusCode property
=================================================

 The **`statusCode`** read-only property of the
 `SecurityPolicyViolationEvent` interface is a number representing the HTTP
 status code of the document or worker in which the violation occurred.

Value
-----

 A number representing the status code of the document or worker in which the violation
 occurred.

Examples
--------

```js
document.addEventListener("securitypolicyviolation", (e) => {
  console.log(e.statusCode);
});
```

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

| Specification |
| --- |
| Content Security Policy Level 3 # dom-securitypolicyviolationevent-statuscode |

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

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

See also
--------

* Content Security Policy (CSP)


SecurityPolicyViolationEvent: lineNumber property - Web APIs

SecurityPolicyViolationEvent: lineNumber property
=================================================

 The **`lineNumber`** read-only property of the
 `SecurityPolicyViolationEvent` interface is the line number in the document
 or worker at which the violation occurred.

Value
-----

A number representing the line number at which the violation occurred.

Examples
--------

```js
document.addEventListener("securitypolicyviolation", (e) => {
  console.log(e.lineNumber);
});
```

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

| Specification |
| --- |
| Content Security Policy Level 3 # dom-securitypolicyviolationevent-linenumber |

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

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

See also
--------

* Content Security Policy (CSP)


SecurityPolicyViolationEvent: disposition property - Web APIs

SecurityPolicyViolationEvent: disposition property
==================================================

 The **`disposition`** read-only property of the
 `SecurityPolicyViolationEvent` interface indicates how the violated policy
 is configured to be treated by the user agent.

Value
-----

 A value defined in the SecurityPolicyViolationEventDisposition enum
 representing the URI of the blocked resource. Possible values are `"enforce"` or `"report"`

Examples
--------

```js
document.addEventListener("securitypolicyviolation", (e) => {
  console.log(e.disposition);
});
```

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

| Specification |
| --- |
| Content Security Policy Level 3 # dom-securitypolicyviolationevent-disposition |

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

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

See also
--------

* Content Security Policy (CSP)


SecurityPolicyViolationEvent: originalPolicy property - Web APIs

SecurityPolicyViolationEvent: originalPolicy property
=====================================================

 The **`originalPolicy`** read-only property of the
 `SecurityPolicyViolationEvent` interface is a string
 containing the policy whose enforcement uncovered the violation.

Value
-----

 A string representing the policy whose enforcement uncovered the
 violation.

Examples
--------

```js
document.addEventListener("securitypolicyviolation", (e) => {
  console.log(e.originalPolicy);
});
```

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

| Specification |
| --- |
| Content Security Policy Level 3 # dom-securitypolicyviolationevent-originalpolicy |

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

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

See also
--------

* Content Security Policy (CSP)


SecurityPolicyViolationEvent: blockedURI property - Web APIs

SecurityPolicyViolationEvent: blockedURI property
=================================================

 The **`blockedURI`** read-only property of the
 `SecurityPolicyViolationEvent` interface is a string
 representing the URI of the resource that was blocked because it violates a policy.

Value
-----

A string representing the URI of the blocked resource.

Examples
--------

```js
document.addEventListener("securitypolicyviolation", (e) => {
  console.log(e.blockedURI);
});
```

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

| Specification |
| --- |
| Content Security Policy Level 3 # dom-securitypolicyviolationevent-blockeduri |

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

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

See also
--------

* Content Security Policy (CSP)


SecurityPolicyViolationEvent: SecurityPolicyViolationEvent() constructor - Web APIs

SecurityPolicyViolationEvent: SecurityPolicyViolationEvent() constructor
========================================================================

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

Syntax
------

```js
new SecurityPolicyViolationEvent(type)
new SecurityPolicyViolationEvent(type, options)
```

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers always set it to `securitypolicyviolation`.

`options` Optional

An object that, *in addition of the properties defined in `Event()`*, can have the following properties:

`blockedURI` Optional

 The `blockedURI` of the `SecurityPolicyViolationEvent`.
 If not included, the default value is `""`.

`columnNumber` Optional

 The `columnNumber` of the `SecurityPolicyViolationEvent`.
 If not included, the default value is `0`.

`disposition`

The `disposition` of the `SecurityPolicyViolationEvent`.

`documentURI`

The `documentURI` of the `SecurityPolicyViolationEvent`.

`effectiveDirective`

The `effectiveDirective` of the `SecurityPolicyViolationEvent`.

`lineNumber` Optional

 The `lineNumber` of the `SecurityPolicyViolationEvent`.
 If not included, the default value is `0`.

`originalPolicy`

The `originalPolicy` of the `SecurityPolicyViolationEvent`.

`referrer` Optional

 The `referrer` of the `SecurityPolicyViolationEvent`.
 If not included, the default value is `""`.

`sample` Optional

 The `sample` of the `SecurityPolicyViolationEvent`.
 If not included, the default value is `""`.

`sourceFile` Optional

 The `sourceFile` of the `SecurityPolicyViolationEvent`.
 If not included, the default value is `""`.

`statusCode`

The `statusCode` of the `SecurityPolicyViolationEvent`.

`violatedDirective`

The `violatedDirective` of the `SecurityPolicyViolationEvent`.

### Return value

A new `SecurityPolicyViolationEvent` object.

Examples
--------

```js
let SPVEvt = new SecurityPolicyViolationEvent("foo", {
  /\* ... \*/
});
```

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

| Specification |
| --- |
| Content Security Policy Level 3 # dom-securitypolicyviolationevent-securitypolicyviolationevent |

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

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

See also
--------

* Content Security Policy (CSP)


SecurityPolicyViolationEvent: referrer property - Web APIs

SecurityPolicyViolationEvent: referrer property
===============================================

 The **`referrer`** read-only property of the
 `SecurityPolicyViolationEvent` interface is a string
 representing the referrer of the resources whose policy was violated. This will be a URL
 or `null`.

Value
-----

 A string representing the URL of the referrer of the violating
 resources.

Examples
--------

```js
document.addEventListener("securitypolicyviolation", (e) => {
  console.log(e.referrer);
});
```

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

| Specification |
| --- |
| Content Security Policy Level 3 # dom-securitypolicyviolationevent-referrer |

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

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

See also
--------

* Content Security Policy (CSP)


SecurityPolicyViolationEvent: effectiveDirective property - Web APIs

SecurityPolicyViolationEvent: effectiveDirective property
=========================================================

 The **`effectiveDirective`** read-only property of the
 `SecurityPolicyViolationEvent` interface is a string
 representing the directive whose enforcement uncovered the violation.

Value
-----

 A string representing the directive whose enforcement uncovered the
 violation.

Examples
--------

```js
document.addEventListener("securitypolicyviolation", (e) => {
  console.log(e.effectiveDirective);
});
```

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

| Specification |
| --- |
| Content Security Policy Level 3 # dom-securitypolicyviolationevent-effectivedirective |

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

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

See also
--------

* Content Security Policy (CSP)


SecurityPolicyViolationEvent: sourceFile property - Web APIs

SecurityPolicyViolationEvent: sourceFile property
=================================================

 The **`sourceFile`** read-only property of the
 `SecurityPolicyViolationEvent` interface is a string
 representing the URI of the document or worker in which the violation was found.

Value
-----

 A string representing the URI of the document or worker in which the
 violation was found.

Examples
--------

```js
document.addEventListener("securitypolicyviolation", (e) => {
  console.log(e.sourceFile);
});
```

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

| Specification |
| --- |
| Content Security Policy Level 3 # dom-securitypolicyviolationevent-sourcefile |

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

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

See also
--------

* Content Security Policy (CSP)


SecurityPolicyViolationEvent: documentURI property - Web APIs

SecurityPolicyViolationEvent: documentURI property
==================================================

 The **`documentURI`** read-only property of the
 `SecurityPolicyViolationEvent` interface is a string
 representing the URI of the document or worker in which the violation was found.

Value
-----

 A string representing the URI of the document or worker in which the
 violation was found.

Examples
--------

```js
document.addEventListener("securitypolicyviolation", (e) => {
  console.log(e.documentURI);
});
```

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

| Specification |
| --- |
| Content Security Policy Level 3 # dom-securitypolicyviolationevent-documenturi |

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

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

See also
--------

* Content Security Policy (CSP)


SecurityPolicyViolationEvent: sample property - Web APIs

SecurityPolicyViolationEvent: sample property
=============================================

 The **`sample`** read-only property of the
 `SecurityPolicyViolationEvent` interface is a string
 representing a sample of the resource that caused the violation.

Value
-----

 A string containing a sample of the resource that caused the
 violation, usually the first 40 characters. This will only be populated if the resource
 is an inline script, event handler, or style — external resources causing a violation
 will not generate a sample.

Examples
--------

```js
document.addEventListener("securitypolicyviolation", (e) => {
  console.log(e.sample);
});
```

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

| Specification |
| --- |
| Content Security Policy Level 3 # dom-securitypolicyviolationevent-sample |

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

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

See also
--------

* Content Security Policy (CSP)


IDBIndex: isAutoLocale property - Web APIs

IDBIndex: isAutoLocale property
===============================

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

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

The **`isAutoLocale`** read-only property of the `IDBIndex` interface returns a boolean value indicating whether the index had a `locale` value of `auto` specified upon its creation (see the `options` parameter to `IDBObjectStore.createIndex()`.)

Value
-----

A boolean value.

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.

The `isAutoLocale` value is logged to the console.

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

  const myIndex = objectStore.index("lName");
  console.log(myIndex.isAutoLocale);

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

Not currently part of any specification.

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


IDBIndex: locale property - Web APIs

IDBIndex: locale property
=========================

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

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

The **`locale`** read-only property of the `IDBIndex` interface returns the locale of the index (for example `en-US`, or `pl`) if it had a `locale` value specified upon its creation (see the `options` parameter to `IDBObjectStore.createIndex()`.) Note that this property always returns the current locale being used in this index, in other words, it never returns `"auto"`.

Value
-----

A string.

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.

The `locale` value is logged to the console.

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

  const myIndex = objectStore.index("lName");
  console.log(myIndex.locale);

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

Not currently part of any specification.

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


IDBIndex: count() method - Web APIs

IDBIndex: count() method
========================

 The **`count()`** method of the `IDBIndex`
 interface returns an `IDBRequest` object, and in a separate thread,
 returns the number of records within a key range.

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

Syntax
------

```js
count()
count(key)
```

### Parameters

`key` Optional

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

### Return value

A `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 key or key range.

### Exceptions

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

`TransactionInactiveError` `DOMException`

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

`DataError` `DOMException`

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

`InvalidStateError` `DOMException`

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

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.

`myIndex.count()` is then used to count the number of records in the index,
 and the result of that request is logged to the console when its success callback
 returns.

 Finally, we iterate through each record, and insert the data into an HTML table. For a
 complete working example, see our 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");
  const countRequest = myIndex.count();
  countRequest.onsuccess = () => {
    console.log(countRequest.result);
  };

  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 # ref-for-dom-idbindex-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).


IDBIndex: multiEntry property - Web APIs

IDBIndex: multiEntry property
=============================

 The **`multiEntry`** read-only property of the
 `IDBIndex` interface returns a boolean value that affects how the index
 behaves when the result of evaluating the index's key path yields an array.

 This is decided when the index is created, using the
 `IDBObjectStore.createIndex` method. This method takes an optional
 `options` parameter whose `multiEntry` property is set to `true`/`false`.

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

Value
-----

A boolean value:

| Value | Effect |
| --- | --- |
| true | There is one record in the index for each item in an array of keys. |
| false | There is one record for each key that is an array. |

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.

 The multi-entry status of the index is logged to the console: it should be returned
 as `false`.

 Finally, we iterate through each record, and insert the data into an HTML table. For a
 complete working example, see our 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");
  console.log(myIndex.multiEntry);

  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-idbindex-multientry |

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


IDBIndex: get() method - Web APIs

IDBIndex: get() method
======================

 The **`get()`** method of the `IDBIndex`
 interface returns an `IDBRequest` object, and, in a separate thread,
 finds either the value in the referenced object store that corresponds to the given
 key or the first corresponding value, if `key` is set to an
 `IDBKeyRange`.

 If a value is found, then a structured clone of it is created and set as the
 `result` of the request object: this returns the record the key is associated
 with.

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

Syntax
------

```js
get()
get(key)
```

### Parameters

`key` Optional

 A key or `IDBKeyRange` that identifies the record to be retrieved. If
 this value is null or missing, the browser will use an unbound key 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 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 `IDBIndex`'s transaction is inactive.

`DataError` `DOMException`

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

`InvalidStateError` `DOMException`

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

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.

`myIndex.get('Bungle')` is then used to retrieve the record with an
 `lName` of `Bungle`, and the result of that request is logged to
 the console when its success callback returns.

 Finally, we iterate through each record, and insert the data into an HTML table. For a
 complete working example, see our 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");
  const getRequest = myIndex.get("Bungle");
  getRequest.onsuccess = () => {
    console.log(getRequest.result);
  };

  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 # ref-for-dom-idbindex-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).


IDBIndex: openKeyCursor() method - Web APIs

IDBIndex: openKeyCursor() method
================================

 The **`openKeyCursor()`** method of the
 `IDBIndex` interface returns an `IDBRequest` object, and, in
 a separate thread, creates a cursor over the specified key range, as arranged by this
 index.

 The method sets the position of the cursor to the appropriate key, based on the
 specified direction.

If the key range is not specified or is null, then the range includes all the keys.

**Note:** Cursors returned by `openKeyCursor()` do not
 make the referenced value available as `IDBIndex.openCursor` does.
 This makes obtaining a list of keys much more efficient.

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

Syntax
------

```js
openKeyCursor()
openKeyCursor(range)
openKeyCursor(range, direction)
```

### Parameters

`range` Optional

 A key or `IDBKeyRange` to use as the cursor's range. If nothing is
 passed, this will default to a key range that selects all the records in this object
 store.

`direction` Optional

 The cursor's direction. See IDBCursor Constants for possible
 values.

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

`TransactionInactiveError` `DOMException`

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

`TypeError`

Thrown if the value for the direction parameter is invalid.

`DataError` `DOMException`

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

`InvalidStateError` `DOMException`

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

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 key cursor on
 the index using `openKeyCursor()` — this works the same as opening a cursor
 directly on an `ObjectStore` using
 `IDBObjectStore.openKeyCursor` except that the returned records are sorted
 based on the index, not the primary key.

 Finally, we iterate through each record in the index, and insert the last name and the
 corresponding primary key of the referenced record into an HTML table.

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

  const myIndex = objectStore.index("lName");

  myIndex.openKeyCursor().onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const tableRow = document.createElement("tr");
      tableRow.innerHTML =
        `<td>${cursor.key}</td>` + `<td>${cursor.primaryKey}</td>`;
      tableEntry.appendChild(tableRow);

      cursor.continue();
    } else {
      console.log("All last names displayed.");
    }
  };
}
```

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

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


IDBIndex: objectStore property - Web APIs

IDBIndex: objectStore property
==============================

 The **`objectStore`** property of the `IDBIndex`
 interface returns the object store referenced by the current index.

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

Value
-----

An `IDBObjectStore`.

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.

 The current object store is logged to the console: it should be returned something like
 this:

```json
IDBObjectStore { name: "contactsList", keyPath: "id", indexNames: DOMStringList[7], transaction: IDBTransaction, autoIncrement: false }
```

 Finally, we iterate through each record, and insert the data into an HTML table. For a
 complete working example, see our 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");
  console.log(myIndex.objectStore);

  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 # ref-for-dom-idbindex-objectstore① |

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


IDBIndex: name property - Web APIs

IDBIndex: name property
=======================

 The **`name`** property of the `IDBIndex`
 interface contains a string which names the index.

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

Value
-----

A string specifying a name for the index.

### Exceptions

 There are a several exceptions that can occur when you attempt to change an index's
 name.

`InvalidStateError` `DOMException`

 Thrown if the index, or its object store, has been deleted or if the current transaction is not
 an upgrade transaction. You can only rename indexes during upgrade transactions; that
 is, when the mode is `"versionchange"`.

`TransactionInactiveError` `DOMException`

Thrown if the current transaction is not active.

`ConstraintError` `DOMException`

Thrown if an index is already using the specified `name`.

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 `IDBObjectStore` using
 `openCursor()` except that the returned
 records are sorted based on the index, not the primary key.

 The name of the index is logged to the console: it should be returned as
 `lName`.

 Finally, we iterate through each record, inserting the data into an HTML table. For a
 complete working example, see our 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");
  console.log(myIndex.name);

  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 # ref-for-dom-idbindex-name① |

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


IDBIndex: getAll() method - Web APIs

IDBIndex: getAll() method
=========================

 The **`getAll()`** method of the `IDBIndex`
 interface retrieves all objects that are inside the index.

 There is a performance cost associated with looking at the `value` property
 of a cursor, because the object is created lazily. To use a feature
 like `getAll()`, the browser has to create all the objects at once. If you
 are just interested in looking at each of the keys, for instance, it is more efficient
 to use a cursor. If you are trying to get an
 array of all the objects in an object store, though, you should
 use `getAll()`.

Syntax
------

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

### Parameters

`query` Optional

 A key or an `IDBKeyRange` identifying the records to retrieve. If this
 value is null or missing, the browser will use an unbound key range.

`count` Optional

 The number of records to return. If this value exceeds the number of records in the
 query, the browser will only retrieve the queried records. 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 the following types:

`TransactionInactiveError` `DOMException`

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

`InvalidStateError` `DOMException`

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

 A `TypeError` exception is thrown if the `count` parameter is
 not between `0` and `2^32 - 1` included.

Examples
--------

```js
const myIndex = objectStore.index("index");
const getAllRequest = myIndex.getAll();
getAllRequest.onsuccess = () => {
  console.log(getAllRequest.result);
};
```

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

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


IDBIndex: getKey() method - Web APIs

IDBIndex: getKey() method
=========================

 The **`getKey()`** method of the `IDBIndex`
 interface returns an `IDBRequest` object, and, in a separate thread,
 finds either the primary key that corresponds to the given key in this index or the
 first corresponding primary key, if `key` is set to an
 `IDBKeyRange`.

 If a primary key is found, it is set as the `result` of the request object.
 Note that this doesn't return the whole record as `IDBIndex.get` does.

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

Syntax
------

```js
getKey()
getKey(key)
```

### Parameters

`key` Optional

 A key or `IDBKeyRange` that identifies a record to be retrieved. If
 this value is null or missing, the browser will use an unbound key 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 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:

`TransactionInactiveError` `DOMException`

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

`DataError` `DOMException`

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

`InvalidStateError` `DOMException`

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

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.

`myIndex.getKey('Bungle')` is then used to retrieve the primary key of the
 record with an `lName` of `Bungle`, and the result of that request
 is logged to the console when its success callback returns.

 Finally, we iterate through each record, and insert the data into an HTML table. For a
 complete working example, see our 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");
  const getKeyRequest = myIndex.getKey("Bungle");
  getKeyRequest.onsuccess = () => {
    console.log(getKeyRequest.result);
  };

  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 # ref-for-dom-idbindex-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).


IDBIndex: openCursor() method - Web APIs

IDBIndex: openCursor() method
=============================

 The **`openCursor()`** method of the `IDBIndex`
 interface returns an `IDBRequest` object, and, in a separate thread,
 creates a cursor over the specified key
 range.

 The method sets the position of the cursor to the appropriate record, based on the
 specified direction.

If the key range is not specified or is null, then the range includes all the records.

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

Syntax
------

```js
openCursor()
openCursor(range)
openCursor(range, direction)
```

### Parameters

`range` Optional

 A key or `IDBKeyRange` to use as the cursor's range. If nothing is
 passed, this will default to a key range that selects all the records in this object
 store.

`direction` Optional

 The cursor's direction. See IDBCursor Constants for possible
 values.

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

`TransactionInactiveError` `DOMException`

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

`TypeError`

Thrown if the value for the direction parameter is invalid.

`DataError` `DOMException`

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

`InvalidStateError` `DOMException`

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

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 `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 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 # ref-for-dom-idbindex-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).


IDBIndex: unique property - Web APIs

IDBIndex: unique property
=========================

 The **`unique`** read-only property returns a boolean that
 states whether the index allows duplicate keys.

 This is decided when the index is created, using the
 `IDBObjectStore.createIndex` method. This method takes an optional
 parameter, `unique`, which if set to `true` means that the index
 will not be able to accept duplicate entries.

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

Value
-----

A boolean value:

| Value | Effect |
| --- | --- |
| `true` | The current index does not allow duplicate values for a key. |
| `false` | The current index allows duplicate key values. |

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.

 The unique status of the index is logged to the console: it should be returned
 as `false`.

 Finally, we iterate through each record, and insert the data into an HTML table. For a
 complete working example, see our 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");
  console.log(myIndex.unique);

  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-idbindex-unique |

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


IDBIndex: getAllKeys() method - Web APIs

IDBIndex: getAllKeys() method
=============================

 The **`getAllKeys()`** method of the `IDBIndex`
 interface asynchronously retrieves the primary keys of all objects inside the index,
 setting them as the `result` of the request object.

Syntax
------

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

### Parameters

`query` Optional

 A key or an `IDBKeyRange` identifying the keys to retrieve. If this
 value is null or missing, the browser will use an unbound key range.

`count` Optional

 The number records to return. If this value exceeds the number of records in the
 query, the browser will only retrieve the first item. 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 the following types:

`TransactionInactiveError` `DOMException`

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

`InvalidStateError` `DOMException`

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

 A `TypeError` exception is thrown if the `count` parameter is
 not between `0` and `2^32 - 1` included.

Examples
--------

```js
const myIndex = objectStore.index("index");
const getAllKeysRequest = myIndex.getAllKeys();
getAllKeysRequest.onsuccess = () => {
  console.log(getAllKeysRequest.result);
};
```

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

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


IDBIndex: keyPath property - Web APIs

IDBIndex: keyPath property
==========================

 The **`keyPath`** property of the `IDBIndex`
 interface returns the key path of the current index. If null, this index is not auto-populated.

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

Value
-----

Any data type that can be used as a key path.

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.

 The key path of the current index is logged to the console: it should be returned
 as `lName`.

 Finally, we iterate through each record, and insert the data into an HTML table. For a
 complete working example, see our 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");
  console.log(myIndex.keyPath);

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


GamepadHapticActuator: pulse() method - Web APIs

GamepadHapticActuator: pulse() method
=====================================

The **`pulse()`** method of the `GamepadHapticActuator` interface makes the hardware pulse at a certain intensity for a specified duration.

Syntax
------

```js
pulse(value, duration)
```

### Parameters

`value`

A double representing the intensity of the pulse. This can vary depending on the hardware type, but generally takes a value between 0.0 (no intensity) and 1.0 (full intensity).

`duration`

A double representing the duration of the pulse, in milliseconds.

**Note:** Repeated calls to `pulse()` override the previous calls if they are still ongoing.

### Return value

A promise that resolves with a value of `true` when the pulse has successfully completed.

Examples
--------

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

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

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

| Specification |
| --- |
| Gamepad Extensions # dom-gamepadhapticactuator-pulse |

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

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

See also
--------

* Gamepad API


GamepadHapticActuator: playEffect() method - Web APIs

GamepadHapticActuator: playEffect() method
==========================================

**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 **`playEffect()`** method of the `GamepadHapticActuator` interface makes the hardware play a specific vibration pattern.

Syntax
------

```js
playEffect(type, params)
```

### Parameters

`type`

A string representing the desired effect. This can vary depending on the hardware type. Possible values are "dual-rumble" or "vibration".

`params`

An object to describe a desired haptic effect.

Expected values are:

`duration`

The duration of the effect in milliseconds.

`startDelay`

The delay in milliseconds before the effect is started.

`strongMagnitude`

Rumble intensity of the low-frequency (strong) rumble motors, normalized to the range between 0.0 and 1.0.

`weakMagnitude`

Rumble intensity of the high-frequency (weak) rumble motors, normalized to the range between 0.0 and 1.0.

**Note:** A new call to `playEffect()` overrides a previous ongoing call.

### Return value

A promise that resolves with `true` when the playEffect successfully completes.

Examples
--------

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

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

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

#### No specification found

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

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

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

See also
--------

* Gamepad API


GamepadHapticActuator: type property - Web APIs

GamepadHapticActuator: type property
====================================

The **`type`** read-only property of the `GamepadHapticActuator` interface returns an enum representing the type of the haptic hardware.

Value
-----

An enum of type `GamepadHapticActuatorType`; currently available types are:

* `vibration` — vibration hardware, which creates a rumbling effect.
Examples
--------

TBC

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

| Specification |
| --- |
| Gamepad Extensions # dom-gamepadhapticactuatortype |

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

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

See also
--------

* Gamepad API


MediaCapabilities: decodingInfo() method - Web APIs

MediaCapabilities: decodingInfo() method
========================================

 The **`MediaCapabilities.decodingInfo()`** method, part of the Media Capabilities API, returns a promise with the tested media configuration's capabilities info.
 This contains the three boolean properties `supported`, `smooth`, and `powerefficient`, which describe whether decoding the media described would be supported, smooth, and powerefficient.

Syntax
------

```js
decodingInfo(configuration)
```

### Parameters

`configuration`

An object with a property `type` and *either* a `video` or `audio` property containing a configuration of the appropriate type:

`type`

The type of media being tested. This takes one of three values:

`file`

Represents a configuration that is meant to be used for a plain file playback.

`media-source`

Represents a configuration that is meant to be used for playback of a `MediaSource`.

`webrtc`

Represents a configuration that is meant to be received using `RTCPeerConnection`.

`video`

 Configuration object for a video media source.
 This has the following properties:

`contentType`

String containing a valid video MIME type, and (optionally) a `codecs` parameter.

`width`

The width of the video.

`height`

The height of the video.

`bitrate`

The number of bits used to encode one second of the video file.

`framerate`

The number of frames making up one second of video playback.

`audio`

 Configuration object for an audio media source.
 This has the following properties:

`contentType`

String containing a valid audio MIME type, and (optionally) a `codecs` parameter.

`channels`

The number of channels used by the audio track.

`bitrate`

The number of bits used to encode one second of the audio file.

`samplerate`

The number of audio samples making up one second of the audio file.

### Return value

A `Promise` fulfilling with an object containing three Boolean attributes:

`supported`

`true` if the media content can be decoded at all. Otherwise, it is `false`.

`smooth`

`true` if playback of the media will be smooth (of high quality). Otherwise it is `false`.

`powerEfficient`

`true` if playback of the media will be power efficient. Otherwise, it is `false`.

 Browsers will report a supported media configuration as `smooth` and `powerEfficient` until stats on this device have been recorded.
 All supported audio codecs are reported to be power efficient.

### Exceptions

`TypeError`

Thrown if the `configuration` passed to the `decodingInfo()` method is invalid, either because the type is not video or audio, the `contentType` is not a valid codec MIME type, the media decoding configuration is not a valid value for the `type` (file, media-source, or webrtc), or any other error in the media configuration passed to the method, including omitting any values.

Examples
--------

This example shows how to create a media configuration for an audio file and then use it in `MediaCapabilities.decodingInfo()`.

```js
//Create media configuration to be tested
const mediaConfig = {
  type: "file", // or 'media-source' or 'webrtc'
  audio: {
    contentType: "audio/ogg; codecs=vorbis", // valid content type
    channels: 2, // audio channels used by the track
    bitrate: 132700, // number of bits used to encode 1s of audio
    samplerate: 5200, // number of audio samples making up that 1s.
  },
};

// check support and performance
navigator.mediaCapabilities.decodingInfo(mediaConfig).then((result) => {
  console.log(
    `This configuration is ${result.supported ? "" : "not "}supported,`,
  );
  console.log(`${result.smooth ? "" : "not "}smooth, and`);
  console.log(`${result.powerEfficient ? "" : "not "}power efficient.`);
});
```

Similarly, the code below shows the configuration for a video file.

```js
const mediaConfig = {
  type: "file",
  video: {
    contentType: "video/webm;codecs=vp8", // valid content type
    width: 800, // width of the video
    height: 600, // height of the video
    bitrate: 10000, // number of bits used to encode 1s of video
    framerate: 30, // number of frames making up that 1s.
  },
};
```

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

| Specification |
| --- |
| Media Capabilities # ref-for-dom-mediacapabilities-decodinginfo |

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

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

See also
--------

* `MediaCapabilities.encodingInfo()`
* `HTMLMediaElement.canPlayType()` for file
* `MediaSource.isTypeSupported()` for media-source


MediaCapabilities: encodingInfo() method - Web APIs

MediaCapabilities: encodingInfo() method
========================================

 The **`MediaCapabilities.encodingInfo()`** method, part of the `MediaCapabilities` interface of the Media Capabilities API, returns a promise with the tested media configuration's capabilities information.
 This contains the three boolean properties `supported`, `smooth`, and `powerefficient`, which describe how compatible the device is with the type of media.

Syntax
------

```js
encodingInfo(configuration)
```

### Parameters

`configuration`

An object with a property `type` and *either* a `video` or `audio` property containing a configuration of the appropriate type:

`type`

The type of media being tested. This takes one of two values:

`record`

Represents a configuration for recording of media, e.g. using `MediaRecorder`.

`webrtc`

Represents a configuration meant to be transmitted over electronic means (e.g. using `RTCPeerConnection`). **Note:** Firefox uses `transmission` for this type, and `webrtc` does not work.

`transmission`
Non-standard

The synonym of `webrtc` to be used in Firefox.

`video`

 Configuration object for a video media source.
 This has the following properties:

`contentType`

String containing a valid video MIME type, and (optionally) a `codecs` parameter.

`width`

The width of the video.

`height`

The height of the video.

`bitrate`

The number of bits used to encode one second of the video file.

`framerate`

The number of frames making up one second of video playback.

`audio`

 Configuration object for an audio media source.
 This has the following properties:

`contentType`

String containing a valid audio MIME type, and (optionally) a `codecs` parameter.

`channels`

The number of channels used by the audio track.

`bitrate`

The number of bits used to encode one second of the audio file.

`samplerate`

The number of audio samples making up one second of the audio file.

### Return value

A `Promise` fulfilling with an object containing three Boolean attributes:

`supported`

`true` if the media content can be decoded at all. Otherwise, it is `false`.

`smooth`

`true` if playback of the media will be smooth (of high quality). Otherwise it is `false`.

`powerEfficient`

`true` if playback of the media will be power efficient. Otherwise, it is `false`.

 Browsers will report a supported media configuration as `smooth` and `powerEfficient` until stats on this device have been recorded.
 All supported audio codecs are reported to be power efficient.

### Exceptions

`TypeError`

Thrown if the `configuration` passed to the `encodingInfo()` method is invalid, which may be for any of the following reasons:

* the type is not video or audio,
* the `contentType` is not a valid codec MIME type,
* there is some other error in the media configuration passed to the method, including omitting any of the `configuration` elements.

Examples
--------

```js
//Create media configuration to be tested
const mediaConfig = {
  type: "record", // or 'transmission'
  video: {
    contentType: "video/webm;codecs=vp8.0", // valid content type
    width: 1920, // width of the video
    height: 1080, // height of the video
    bitrate: 120000, // number of bits used to encode 1s of video
    framerate: 48, // number of frames making up that 1s.
  },
};

// check support and performance
navigator.mediaCapabilities.encodingInfo(mediaConfig).then((result) => {
  console.log(
    `This configuration is ${result.supported ? "" : "not "}supported,`,
  );
  console.log(`${result.smooth ? "" : "not "}smooth, and`);
  console.log(`${result.powerEfficient ? "" : "not "}power efficient.`);
});
```

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

| Specification |
| --- |
| Media Capabilities # ref-for-dom-mediacapabilities-encodinginfo |

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

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

See also
--------

* `MediaCapabilities.decodingInfo()`


PaymentResponse: payerEmail property - Web APIs

PaymentResponse: payerEmail property
====================================

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

**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 `payerEmail` read-only property of the `PaymentResponse`
 interface returns the email address supplied by the user. This option is only present
 when the `requestPayerEmail` option is set to `true` in the
 `PaymentOptions` object passed to the
 `PaymentRequest` constructor.

Value
-----

A string.

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

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


PaymentResponse: complete() method - Web APIs

PaymentResponse: complete() method
==================================

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

 The `PaymentRequest` method
 **`complete()`** of the Payment Request API notifies the
 user agent that the user interaction is over, and causes any remaining
 user interface to be closed.

 This method must be called after the user accepts
 the payment request and the `Promise` returned by the
 `PaymentRequest.show()` method is resolved.

Syntax
------

```js
complete()
complete(result)
```

### Parameters

`result` Optional

 A string indicating the state of the payment operation upon
 completion. It must be one of the following:

`success`

 The payment was successfully processed. The user agent may or may not present
 some form of "payment successful" indication to the user.

`fail`

 The payment was not successfully processed. The failure may or may not be
 announced to the user by the user agent, depending on its design.

`unknown`

 The success or failure status of the transaction is unknown or irrelevant, and
 the user agent should not present any notification, even if it normally would.
 *This is the default value.*

**Note:** In older versions of the specification, an empty string,
 `""`, was used instead of `unknown` to indicate a completion
 without a known result state. See the Browser compatibility section
 below for details.

### Return value

 A `Promise` which resolves with no input value once the payment interface
 has been fully closed. If an error occurs, the promise instead rejects, returning one of
 the exceptions listed below.

### Exceptions

`AbortError` `DOMException`

 Returned if the document in which the payment request is taking place became inactive while the
 user interface was shown.

`InvalidStateError` `DOMException`

 Returned if the payment has already completed, or `complete()` was called while a
 request to retry the payment is pending. You can't treat a payment as complete after
 requesting that the payment be tried again.

Examples
--------

 The following example sends payment information to a secure server using the Fetch API. It
 calls `complete()` with an answer appropriate to the status in the response.

```js
// Initialization of PaymentRequest arguments are excerpted for the
// sake of brevity.
const payment = new PaymentRequest(supportedInstruments, details, options);

payment
  .show()
  .then((paymentResponse) => {
    const fetchOptions = {
      method: "POST",
      credentials: include,
      body: JSON.stringify(paymentResponse),
    };
    const serverPaymentRequest = new Request("secure/payment/endpoint");
    fetch(serverPaymentRequest, fetchOptions)
      .then((response) => {
        if (response.status < 400) {
          paymentResponse.complete("success");
        } else {
          paymentResponse.complete("fail");
        }
      })
      .catch((reason) => {
        paymentResponse.complete("fail");
      });
  })
  .catch((err) => {
    console.error("Uh oh, something bad happened", err.message);
  });
```

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

| Specification |
| --- |
| Payment Request API 1.1 # dom-paymentresponse-complete |

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

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


PaymentResponse: shippingOption property - Web APIs

PaymentResponse: shippingOption property
========================================

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

**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 **`shippingOption`** read-only property of
 the `PaymentRequest` interface returns the ID attribute of the shipping
 option selected by the user. This option is only present when the
 `requestShipping` option is set to `true` in the
 `PaymentOptions` object passed to the
 `PaymentRequest` constructor.

Value
-----

A string.

Examples
--------

 In the example below, the `shippingoptionchange` event
 is called. It calls `updateDetails()` to toggle the shipping method between
 "standard" and "express".

```js
// Initialization of PaymentRequest arguments are excerpted for brevity.
const payment = new PaymentRequest(supportedInstruments, details, options);

request.addEventListener("shippingoptionchange", (evt) => {
  evt.updateWith(
    new Promise((resolve, reject) => {
      updateDetails(details, request.shippingOption, resolve, reject);
    }),
  );
});

payment
  .show()
  .then((paymentResponse) => {
    // Processing of paymentResponse excerpted for the same of brevity.
  })
  .catch((err) => {
    console.error("Uh oh, something bad happened", err.message);
  });

function updateDetails(details, shippingOption, resolve, reject) {
  let selectedShippingOption;
  let otherShippingOption;
  if (shippingOption === "standard") {
    selectedShippingOption = details.shippingOptions[0];
    otherShippingOption = details.shippingOptions[1];
    details.total.amount.value = "55.00";
  } else if (shippingOption === "express") {
    selectedShippingOption = details.shippingOptions[1];
    otherShippingOption = details.shippingOptions[0];
    details.total.amount.value = "67.00";
  } else {
    reject(`Unknown shipping option '${shippingOption}'`);
    return;
  }
  selectedShippingOption.selected = true;
  otherShippingOption.selected = false;
  details.displayItems.splice(2, 1, selectedShippingOption);
  resolve(details);
}
```

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

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


PaymentResponse: methodName property - Web APIs

PaymentResponse: methodName property
====================================

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

 The **`methodName`** read-only
 property of the `PaymentResponse` interface returns a string uniquely
 identifying the payment handler selected by the user.

 This string may be either
 one of the standardized payment method identifiers or a URL used by the payment handler
 to process payments.

Value
-----

 A string uniquely identifying the payment handler being used to
 process the payment. This may be either a standardized identifier, or a URL used by the
 payment processor to handle payments. See
 how merchant validation works.

Examples
--------

 The following example extracts the method name from the `PaymentResponse`
 object to the promise returned from `PaymentRequest.show()`. In a
 real-world implementation this data would then be sent to a payment server.

```js
payment.show().then((paymentResponse) => {
  const paymentData = {
    // payment method string
    method: paymentResponse.methodName,
    // payment details as you requested
    details: paymentResponse.details,
    // shipping address information
    address: toDict(paymentResponse.shippingAddress),
  };
  // Send information to the server
});
```

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

| Specification |
| --- |
| Payment Request API 1.1 # dom-paymentresponse-methodname |

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

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


PaymentRequest: payerName property - Web APIs

PaymentRequest: payerName property
==================================

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

**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 **`payerName`** read-only property of the
 `PaymentResponse` interface returns the name supplied by the user. This
 option is only present when the `requestPayerName` option is set to
 `true` in the options parameter of the
 `PaymentRequest()` constructor.

Value
-----

A string containing the payer name.

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

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


PaymentResponse: details property - Web APIs

PaymentResponse: details property
=================================

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

 The **`details`** read-only property of the
 `PaymentResponse` interface returns a JSON-serializable object that
 provides a payment method specific message used by the merchant to process the
 transaction and determine a successful funds transfer.

This data is returned by the payment app that satisfies the payment request. Developers need to consult whomever controls the URL for the expected shape of the details object.

Value
-----

Examples
--------

 The following example extracts the details from the `PaymentResponse`
 object to the promise returned from `PaymentRequest.show()`. In a
 real-world implementation this data would then be sent to a payment server.

```js
payment.show().then((paymentResponse) => {
  const paymentData = {
    // payment method string
    method: paymentResponse.methodName,
    // payment details as you requested
    details: paymentResponse.details,
    // shipping address information
    address: toDict(paymentResponse.shippingAddress),
  };
  // Send information to the server
});
```

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

| Specification |
| --- |
| Payment Request API 1.1 # dom-paymentresponse-details |

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

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


PaymentResponse: requestId property - Web APIs

PaymentResponse: requestId property
===================================

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

 The **`requestId`** read-only property of the
 `PaymentResponse` interface returns the free-form identifier supplied by
 the `PaymentResponse()` constructor by details.id.

Value
-----

A string.

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

| Specification |
| --- |
| Payment Request API 1.1 # dom-paymentresponse-requestid |

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

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


PaymentResponse: toJSON() method - Web APIs

PaymentResponse: toJSON() method
================================

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

The **`toJSON()`** method of the `PaymentResponse` interface is a serializer; it returns a JSON representation of the `PaymentResponse` object.

Syntax
------

```js
toJSON()
```

### Parameters

None.

### Return value

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

Examples
--------

### Using the toJSON method

In this example, calling `paymentResponse.toJSON()` returns a JSON representation of the `PaymentResponse` object.

```js
payment.show().then((paymentResponse) => {
  console.log(paymentResponse.toJSON())
  };
});
```

To get a JSON string, you can use `JSON.stringify(paymentResponse)` directly; it will call `toJSON()` automatically.

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

#### No specification found

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

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

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

See also
--------

* `JSON`


PaymentResponse: payerdetailchange event - Web APIs

PaymentResponse: payerdetailchange event
========================================

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

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

A **`payerdetailchange`** event is fired by the Payment Request API to a `PaymentResponse` object when the user makes changes to their personal information while filling out a payment request form. This can happen when the payer is retrying to submit its details after an error has been detected.

The event handler for `payerdetailchange` should check each value in the form that has changed and ensure that the values are valid. If any are invalid, appropriate error messages should be configured and the `retry()` method should be called on the `PaymentResponse` to ask the user to update the invalid entries.

This event is not cancelable and does not bubble.

Syntax
------

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

```js
addEventListener("payerdetailchange", async (event) => {});

onpayerdetailchange = async (event) => {};
```

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

A `PaymentRequestUpdateEvent`. Inherits from `Event`.

Event

PaymentRequestUpdateEventEvent properties
----------------

Although this event type is `PaymentRequestUpdateEvent`, it doesn't implement any property that is not already on `Event`.

Examples
--------

In the example below, `onpayerdetailchange` is used to set up a listener for the `payerdetailchange` event in order to validate the information entered by the user, requesting that any mistakes be corrected

```js
// Options for PaymentRequest(), indicating that shipping address,
// payer email address, name, and phone number all be collected.

const options = {
  requestShipping: true,
  requestPayerEmail: true,
  requestPayerName: true,
  requestPayerPhone: true,
};
const request = new PaymentRequest(methods, details, options);
const response = request.show();

// Get the data from the response

let {
  payerName: oldPayerName,
  payerEmail: oldPayerEmail,
  payerPhone: oldPayerPhone,
} = response;

// Set up a handler for payerdetailchange events, to
// request corrections as needed.

response.onpayerdetailchange = async (ev) => {
  const promisesToValidate = [];
  const { payerName, payerEmail, payerPhone } = response;

  // Validate each value which changed by calling a function
  // that validates each type of data, returning a promise which
  // resolves if the data is valid.

  if (oldPayerName !== payerName) {
    promisesToValidate.push(validateName(payerName));
    oldPayerName = payerName;
  }
  if (oldPayerEmail !== payerEmail) {
    promisesToValidate.push(validateEmail(payerEmail));
    oldPayerEmail = payerEmail;
  }
  if (oldPayerPhone !== payerPhone) {
    promisesToValidate.push(validatePhone(payerPhone));
    oldPayerPhone = payerPhone;
  }

  // As each validation promise resolves, add the results of the
  // validation to the errors list

  const errors = await Promise.all(promisesToValidate).then((results) =>
    results.reduce((errors, result), Object.assign(errors, result)),
  );

  // If we found any errors, wait for them to be corrected

  if (Object.getOwnPropertyNames(errors).length) {
    await response.retry(errors);
  } else {
    // We have a good payment; send the data to the server
    await fetch("/pay-for-things/", { method: "POST", body: response.json() });
    response.complete("success");
  }
};

await response.retry({
  payer: {
    email: "invalid domain.",
    phone: "invalid number.",
  },
});
```

### addEventListener equivalent

You could also set up the event handler using the `addEventListener()` method:

```js
response.addEventListener("payerdetailchange", async (ev) => {
  // …
});
```

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

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

See also
--------

* Payment Request API
* Using the Payment Request API
* `PaymentResponse`
* `paymentmethodchange`
* `shippingaddresschange`
* `shippingoptionchange`


PayerResponse: payerPhone property - Web APIs

PayerResponse: payerPhone property
==================================

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

**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 `payerPhone` read-only property of the `PaymentResponse`
 interface returns the phone number supplied by the user. This option is only present
 when the `requestPayerPhone` option is set to `true` in the
 `PaymentOptions` object passed to the
 `PaymentRequest` constructor.

Value
-----

A string.

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

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