MediaTrackConstraints: channelCount property - Web APIs

MediaTrackConstraints: channelCount property
============================================

 The `MediaTrackConstraints` dictionary's
 **`channelCount`** property is a `ConstrainULong`
 describing the requested or mandatory constraints placed upon the value of the
 `channelCount` constrainable property.

 If needed, you can determine whether or not this constraint is supported by checking
 the value of `MediaTrackSupportedConstraints.channelCount` as returned by a
 call to `MediaDevices.getSupportedConstraints()`. However, typically this
 is unnecessary since browsers will ignore any constraints they're unfamiliar with.

Value
-----

 If this value is a number, the user agent will attempt to obtain media whose channel
 count is as close as possible to this number given the capabilities of the hardware and
 the other constraints specified. Otherwise, the value of this
 `ConstrainULong` will guide the user agent in its efforts to provide an
 exact match to the required channel count (if `exact` is specified or both
 `min` and `max` are provided and have the same value) or to a
 best-possible value.

The channel count is 1 for monaural sound, 2 for stereo, and so forth.

Examples
--------

See the Constraint exerciser example.

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

| Specification |
| --- |
| Media Capture and Streams # dom-mediatrackconstraintset-channelcount |

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

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

See also
--------

* Media Capture and Streams API
* Capabilities, constraints, and settings
* `MediaTrackConstraints`
* `MediaDevices.getSupportedConstraints()`
* `MediaTrackSupportedConstraints`
* `MediaStreamTrack`


MediaTrackConstraints: width property - Web APIs

MediaTrackConstraints: width property
=====================================

 The `MediaTrackConstraints` dictionary's
 **`width`** property is a `ConstrainULong`
 describing the requested or mandatory constraints placed upon the value of the
 `width` constrainable property.

 If needed, you can determine whether or not this constraint is supported by checking
 the value of `MediaTrackSupportedConstraints.width` as returned by a call
 to `MediaDevices.getSupportedConstraints()`. However, typically this is
 unnecessary since browsers will ignore any constraints they're unfamiliar with.

Value
-----

 If this value is a number, the user agent will attempt to obtain media whose width is
 as close as possible to this number given the capabilities of the hardware and the other
 constraints specified. Otherwise, the value of this `ConstrainULong` will
 guide the user agent in its efforts to provide an exact match to the required width (if
 `exact` is specified or both `min` and `max` are
 provided and have the same value) or to a best-possible value.

Examples
--------

See the Constraint exerciser example.

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

| Specification |
| --- |
| Media Capture and Streams # dom-mediatrackconstraintset-width |

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

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

See also
--------

* Media Capture and Streams API
* Capabilities, constraints, and settings
* `MediaTrackConstraints`
* `MediaDevices.getSupportedConstraints()`
* `MediaTrackSupportedConstraints`
* `MediaStreamTrack`


MediaTrackConstraints: sampleSize property - Web APIs

MediaTrackConstraints: sampleSize property
==========================================

 The `MediaTrackConstraints` dictionary's
 **`sampleSize`** property is a `ConstrainULong`
 describing the requested or mandatory constraints placed upon the value of the
 `sampleSize` constrainable property.

 If needed, you can determine whether or not this constraint is supported by checking
 the value of `MediaTrackSupportedConstraints.sampleSize` as returned by a
 call to `MediaDevices.getSupportedConstraints()`. However, typically this
 is unnecessary since browsers will ignore any constraints they're unfamiliar with.

Value
-----

 If this value is a number, the user agent will attempt to obtain media whose sample
 size (in bits per linear sample) is as close as possible to this number given the
 capabilities of the hardware and the other constraints specified. Otherwise, the value
 of this `ConstrainULong` will guide the user agent in its efforts to provide
 an exact match to the required sample size (if `exact` is specified or both
 `min` and `max` are provided and have the same value) or to a
 best-possible value.

**Note:** Since this property can only represent linear sample sizes, this constraint can only
 be met by devices that can produce audio with linear samples.

Examples
--------

See the Constraint exerciser example.

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

| Specification |
| --- |
| Media Capture and Streams # dom-mediatrackconstraintset-samplesize |

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

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

See also
--------

* Media Capture and Streams API
* Capabilities, constraints, and settings
* `MediaTrackConstraints`
* `MediaDevices.getSupportedConstraints()`
* `MediaTrackSupportedConstraints`
* `MediaStreamTrack`


MediaTrackConstraints: facingMode property - Web APIs

MediaTrackConstraints: facingMode property
==========================================

 The `MediaTrackConstraints` dictionary's
 **`facingMode`** property is a `ConstrainDOMString`
 describing the requested or mandatory constraints placed upon the value of the
 `facingMode` constrainable property.

 If needed, you can determine whether or not this constraint is supported by checking
 the value of `MediaTrackSupportedConstraints.facingMode` as returned by a
 call to `MediaDevices.getSupportedConstraints()`. However, typically this
 is unnecessary since browsers will ignore any constraints they're unfamiliar with.

 Because RTP doesn't include this information, tracks associated with a
 WebRTC `RTCPeerConnection`
 will never include this property.

Value
-----

 An object based on `ConstrainDOMString` specifying one or more acceptable,
 ideal, and/or exact (mandatory) facing modes are acceptable for a video track.

 An `exact` value in this case indicates that the specified facing mode is
 specifically required; for example:

```js
const constraints = {
  facingMode: { exact: "user" },
};
```

 This indicates that only a user-facing camera is acceptable; if there is no user-facing
 camera, or the user declines permission to use that camera, the media request will fail.

 The following strings are permitted values for the facing mode. These may represent
 separate cameras, or they may represent directions in which an adjustable camera can be
 pointed.

`"user"`

 The video source is facing toward the user; this includes, for example, the
 front-facing camera on a smartphone.

`"environment"`

 The video source is facing away from the user, thereby viewing their environment.
 This is the back camera on a smartphone.

`"left"`

 The video source is facing toward the user but to their left, such as a camera aimed
 toward the user but over their left shoulder.

`"right"`

 The video source is facing toward the user but to their right, such as a camera
 aimed toward the user but over their right shoulder.

Examples
--------

See the Constraint exerciser example.

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

| Specification |
| --- |
| Media Capture and Streams # dom-mediatrackconstraintset-facingmode |

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

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

See also
--------

* Media Capture and Streams API
* Capabilities, constraints, and settings
* `MediaTrackConstraints`
* `MediaDevices.getSupportedConstraints()`
* `MediaTrackSupportedConstraints`
* `MediaStreamTrack`


MediaTrackConstraints: aspectRatio property - Web APIs

MediaTrackConstraints: aspectRatio property
===========================================

 The `MediaTrackConstraints` dictionary's **`aspectRatio`** property is a `ConstrainDouble` describing the requested or mandatory constraints placed upon the value of the
 `aspectRatio` constrainable property.

 If needed, you can determine whether or not this constraint is supported by checking
 the value of `MediaTrackSupportedConstraints.aspectRatio` as returned by a
 call to `MediaDevices.getSupportedConstraints()`. However, typically this
 is unnecessary since browsers will ignore any constraints they're unfamiliar with.

Value
-----

 A `ConstrainDouble` describing the acceptable or required value(s) for a
 video track's aspect ratio. The value is the width divided by the height and is rounded
 to ten decimal places. For example, the standard high-definition video aspect ratio of
 16:9 can be computed as 1920/1080, or 1.7777777778.

 If this value is a number, the user agent will attempt to obtain media whose aspect
 ratio is as close as possible to this number given the capabilities of the hardware and
 the other constraints specified. Otherwise, the value of this
 `ConstrainDouble` will guide the user agent in its efforts to provide an
 exact match to the required aspect ratio (if `exact` is specified or both
 `min` and `max` are provided and have the same value) or to a
 best-possible value.

Examples
--------

See the Constraint exerciser example.

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

| Specification |
| --- |
| Media Capture and Streams # dom-mediatrackconstraintset-aspectratio |

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

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

See also
--------

* Media Capture and Streams API
* Capabilities, constraints, and settings
* `MediaTrackConstraints`
* `MediaDevices.getSupportedConstraints()`
* `MediaTrackSupportedConstraints`
* `MediaStreamTrack`


CSSSkewX: ax property - Web APIs

CSSSkewX: ax property
=====================

 The **`ax`** property of the
 `CSSSkewX` interface gets and sets the angle used to distort the element
 along the x-axis (or abscissa).

Value
-----

A `CSSNumericValue`.

Examples
--------

To do

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssskewx-ax |

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

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


CSSSkewX: CSSSkewX() constructor - Web APIs

CSSSkewX: CSSSkewX() constructor
================================

 The **`CSSSkewX()`** constructor creates a new
 `CSSSkewX` object which represents the
 `skewX()`
 value of the individual `transform` property in CSS.

Syntax
------

```js
new CSSSkewX(ax)
```

### Parameters

`ax`

 A value for the `ax` angle of the `CSSSkewX` object to be
 constructed. This must be a `CSSNumericValue`.

Examples
--------

To do

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssskewx-cssskewx |

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

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


ServiceWorker: error event - Web APIs

ServiceWorker: error event
==========================

The `error` event fires whenever an error occurs in the service worker.

Syntax
------

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

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

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

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

A generic `Event`.

Example
-------

The following code snippet gets a handle to the `ServiceWorker` object via `ServiceWorkerRegistration.active` and sets up an `onerror` handler on the resulting object:

```js
// in the page being controlled
if (navigator.serviceWorker) {
  navigator.serviceWorker.register("service-worker.js");

  navigator.serviceWorker.ready.then((registration) => {
    registration.active.onerror = (event) => {
      console.log("An error occurred in the service worker!");
    };
  });
}
```

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

| Specification |
| --- |
| HTML Standard # handler-abstractworker-onerror |

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

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


ServiceWorker: statechange event - Web APIs

ServiceWorker: statechange event
================================

The `statechange` event fires anytime the `ServiceWorker.state` changes.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

 This code snippet is from the service worker registration-events sample (live demo). The code listens for any change in the `ServiceWorker.state`
 and returns its value.

```js
let serviceWorker;
if (registration.installing) {
  serviceWorker = registration.installing;
  document.querySelector("#kind").textContent = "installing";
} else if (registration.waiting) {
  serviceWorker = registration.waiting;
  document.querySelector("#kind").textContent = "waiting";
} else if (registration.active) {
  serviceWorker = registration.active;
  document.querySelector("#kind").textContent = "active";
}

if (serviceWorker) {
  logState(serviceWorker.state);
  serviceWorker.addEventListener("statechange", (e) => {
    logState(e.target.state);
  });
}
```

 Note that when `statechange` fires, the service worker's references may have
 changed. For example:

```js
navigator.serviceWorker.register("/sw.js").then((swr) => {
  swr.installing.state = "installing";
  swr.installing.onstatechange = () => {
    swr.installing = null;
    // At this point, swr.waiting OR swr.active might be true. This is because the statechange
    // event gets queued, meanwhile the underlying worker may have gone into the waiting
    // state and will be immediately activated if possible.
  };
});
```

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

| Specification |
| --- |
| Service Workers # dom-serviceworker-onstatechange |

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

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


ServiceWorker: postMessage() method - Web APIs

ServiceWorker: postMessage() method
===================================

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

The **`postMessage()`** method of the `ServiceWorker` interface sends a message to the worker. This accepts a single parameter, which is the data to send to the worker. The data may be any JavaScript object which can be handled by the structured clone algorithm.

The service worker can send back information to its clients by using the `postMessage()` method. The message will not be sent back to this `ServiceWorker` object but to the associated `ServiceWorkerContainer` available via `navigator.serviceWorker`.

Syntax
------

```js
postMessage(message)
postMessage(message, options)
postMessage(message, transfer)
```

### Parameters

`message`

The object to deliver to the worker; this will be in the `data` field in the event delivered to the `message` event. This may be any JavaScript object handled by the structured clone algorithm.

The `message` parameter is mandatory. If the data to be passed to the worker is unimportant, `null` or `undefined` must be passed explicitly.

`options` Optional

An optional object containing a `transfer` field with an array of transferable objects to transfer ownership of.

`transfer` Optional

An optional array of transferable objects to transfer ownership of. If the ownership of an object is transferred, it becomes unusable in the context it was sent from and becomes available only to the worker it was sent to.

Transferable objects are instances of classes like `ArrayBuffer`, `MessagePort` or `ImageBitmap` objects that can be transferred. `null` is not an acceptable value for `transfer`.

**Note:** The parameters `options` and `transfer` can't both be used at the same time.

### Return value

None (`undefined`).

### Exceptions

`SyntaxError`

Thrown if the `message` parameter is not provided.

Examples
--------

In this example a `ServiceWorker` is created and a message is immediately sent:

```js
navigator.serviceWorker.register("service-worker.js");

navigator.serviceWorker.ready.then((registration) => {
  registration.active.postMessage(
    "Test message sent immediately after creation",
  );
});
```

In order to receive the message, the service worker, in `service-worker.js` has to listen to the `message` event on its global scope.

```js
// This must be in `service-worker.js`
addEventListener("message", (event) => {
  console.log(`Message received: ${event.data}`);
});
```

Note that the service worker can send back messages to the main thread using the `postMessage()` method. To receive it, the main thread needs to listen for a `message` event on the `ServiceWorkerContainer` object.

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

| Specification |
| --- |
| Service Workers # dom-serviceworker-postmessage |
| Service Workers # dom-serviceworker-postmessage-message-options |

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

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

See also
--------

* The `ServiceWorker` interface it belongs to.
* Its counterpart, the `postMessage()` method that a service worker must use to send a message back to the associated `ServiceWorkerContainer`.


ServiceWorker: scriptURL property - Web APIs

ServiceWorker: scriptURL property
=================================

 Returns the `ServiceWorker` serialized script URL defined as part of `ServiceWorkerRegistration`.
 Must be on the same origin as the document that registers the
 `ServiceWorker`.

Value
-----

A string.

Examples
--------

```js
const sw = navigator.serviceWorker.controller;
console.log(sw.scriptURL);
// https://example.com/scripts/service-worker.js
```

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

| Specification |
| --- |
| Service Workers # service-worker-url |

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

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


ServiceWorker: state property - Web APIs

ServiceWorker: state property
=============================

 The **`state`** read-only property of the
 `ServiceWorker` interface returns a string representing the current state
 of the service worker. It can be one of the following values: `parsed`, `installing`,
 `installed`, `activating`, `activated`, or
 `redundant`.

Value
-----

A `String` that can take one of the following values:

`"parsed"`

 The initial state of a service worker after it is downloaded and confirmed to be runnable.
 A service worker is never updated to this state, so this will never be the value of the `ServiceWorker.statechange_event`

`"installing"`

The service worker in this state is considered an installing worker. During this state, `ExtendableEvent.waitUntil()` can be called inside the `install` event handler to extend the life of the installing worker until the passed promise resolves successfully. This is primarily used to ensure that the service worker is not active until all of the core caches are populated.

`"installed"`

The service worker in this state is considered a waiting worker.

`"activating"`

The service worker in this state is considered an active worker. During this state, `ExtendableEvent.waitUntil()` can be called inside the `onactivate` event handler to extend the life of the active worker until the passed promise resolves successfully. No functional events are dispatched until the state becomes activated.

`"activated"`

The service worker in this state is considered an active worker ready to handle functional events.

`"redundant"`

A new service worker is replacing the current service worker, or the current service worker is being discarded due to an install failure.

Examples
--------

 This code snippet is from the service worker registration-events sample (live demo). The code listens for any change in the `ServiceWorker.state`
 and returns its value.

```js
let serviceWorker;
if (registration.installing) {
  serviceWorker = registration.installing;
  document.querySelector("#kind").textContent = "installing";
} else if (registration.waiting) {
  serviceWorker = registration.waiting;
  document.querySelector("#kind").textContent = "waiting";
} else if (registration.active) {
  serviceWorker = registration.active;
  document.querySelector("#kind").textContent = "active";
}

if (serviceWorker) {
  logState(serviceWorker.state);
  serviceWorker.addEventListener("statechange", (e) => {
    logState(e.target.state);
  });
}
```

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

| Specification |
| --- |
| Service Workers # service-worker-state |

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

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


ProcessingInstruction: target property - Web APIs

ProcessingInstruction: target property
======================================

 The read-only **`target`** property of the `ProcessingInstruction` interface
 represent the application to which the `ProcessingInstruction` is targeted.

For example:

```html
<?xml version="1.0"?>
```

is a processing instruction whose `target` is `xml`.

Value
-----

A string containing the name of the application.

Example
-------

### In an XML document
```

<output></output>
```

```js
let parser = new DOMParser();
const doc = parser.parseFromString(
  '<?xml version="1.0"?><test/>',
  "application/xml",
);
const pi = doc.createProcessingInstruction(
  "xml-stylesheet",
  'href="mycss.css" type="text/css"',
);
doc.insertBefore(pi, doc.firstChild);

const output = document.querySelector("output");
output.textContent = `This processing instruction's target is: ${doc.firstChild.target}`;
```

### In an HTML document

The processing instruction line will be considered, and represented, as a `Comment` object.

```html
<?xml version="1.0"?>
<pre></pre>
```

```js
const node = document.querySelector("pre").previousSibling.previousSibling;
const result = `Node with the processing instruction: ${node.nodeName}: ${node.nodeValue}\n`;
document.querySelector("pre").textContent = result;
```

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

| Specification |
| --- |
| DOM Standard # dom-processinginstruction-target |

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

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

See also
--------

* The DOM API


ProcessingInstruction: sheet property - Web APIs

ProcessingInstruction: sheet property
=====================================

 The read-only **`sheet`** property of the `ProcessingInstruction` interface
 contains the stylesheet associated to the `ProcessingInstruction`.

The `xml-stylesheet` processing instruction is used to associate a stylesheet in an XML file.

Value
-----

The associated `Stylesheet` object, or `null` if there are none.

Example
-------

```xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="rule.css"?>
…
```

The `sheet` property of the processing instruction will return the `StyleSheet` object describing `rule.css`.

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-linkstyle-sheet |

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

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

See also
--------

* The DOM API


Highlight: keys() method - Web APIs

Highlight: keys() method
========================

The **`keys()`** method of the `Highlight` interface is an alias for the `values()` method.

`Highlight` is a `Set`-like object, so this is similar to using `Set.keys()`.

Syntax
------

```js
keys()
```

### Return value

A new iterator object containing each `Range` object in the given `Highlight`, in insertion order.

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-set.prototype.keys |

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

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

See also
--------

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


Highlight: size property - Web APIs

Highlight: size property
========================

 The **`size`** property returns the number of `Range` objects in a
 `Highlight` object.

Value
-----

The value of `size` is a read-only integer representing how many entries the highlight object has.

Examples
--------

### Using size

```js
const highlight = new Highlight();
highlight.add(range1);
highlight.add(range2);
highlight.add(range3);

console.log(highlight.size); // 3
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-set.prototype.size |

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

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

See also
--------

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


Highlight: values() method - Web APIs

Highlight: values() method
==========================

The **`values()`** method of the `Highlight` interface returns a new Iterator object that contains the values for each `Range` object in the `Highlight` object in insertion order.

**Note:** The **`keys()`** method is an alias for this method. It behaves exactly the same and returns **values** of `Highlight` elements.

`Highlight` is a `Set`-like object, so this is similar to using `Set.values()`.

Syntax
------

```js
values()
```

### Return value

A new iterator object containing each `Range` object in the given `Highlight`, in insertion order.

Examples
--------

The following code snippet shows how to create a new `Highlight` object with three `Range` objects, and use the iterator returned by the `values()` method to log the three ranges:

```js
const myHighlight = new Highlight();
myHighlight.add(new Range());
myHighlight.add(new Range());
myHighlight.add(new Range());

const iter = myHighlight.values();

for (value of iter) {
  console.log(value); // Range
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-set.prototype.values |

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

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

See also
--------

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


Highlight: entries() method - Web APIs

Highlight: entries() method
===========================

The **`entries()`** method of the `Highlight` interface returns a new Iterator object that contains an array of `[range, range]` for each `Range` object in the `Highlight` object, in insertion order.

`Highlight` is a `Set`-like object, so this is similar to using `Set.entries()`.

Syntax
------

```js
entries()
```

### Return value

A new iterator object that contains an array of `[range, range]` for each `Range` object in the given `Highlight`, in insertion order.

Examples
--------

The code snippet below shows how create a new highlight with two ranges, and then log the ranges by using the iterator returned by the `entries()` method:

```js
const text = new Text("Time is an illusion. Lunchtime doubly so.");

const range1 = document.createRange();
range1.setStart(text, 0);
range1.setEnd(text, 4);

const range2 = document.createRange();
range2.setStart(text, 21);
range2.setEnd(text, 30);

const myHighlight = new Highlight();
myHighlight.add(range1);
myHighlight.add(range2);

const iter = myHighlight.entries();

console.log(iter.next().value); // [Range, Range]
console.log(iter.next().value); // [Range, Range]
```

The following code example shows how to iterate over the ranges in a highlight by using a `for...of` loop:

```js
const text = new Text("Time is an illusion. Lunchtime doubly so.");

const range1 = document.createRange();
range1.setStart(text, 0);
range1.setEnd(text, 4);

const range2 = document.createRange();
range2.setStart(text, 21);
range2.setEnd(text, 30);

const highlight = new Highlight();
highlight.add(range1);
highlight.add(range2);

for (const [range] of highlight.entries()) {
  console.log(range.toString());
  // Time
  // Lunchtime
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-set.prototype.entries |

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

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

See also
--------

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


Highlight: delete() method - Web APIs

Highlight: delete() method
==========================

The **`delete()`** method of the `Highlight` interface removes a specified `Range` object from a `Highlight` object.

`Highlight` is a `Set`-like object, so this is similar to using `Set.delete()`.

Syntax
------

```js
delete(range)
```

### Parameters

`range`

The `Range` object to remove from the `Highlight`.

### Return value

Returns `true` if `range` was already in `Highlight`; otherwise `false`.

Examples
--------

The code snippet below shows how to create a new highlight with two ranges, and then delete one of them:

```js
const range1 = new Range();
const range2 = new Range();

const highlight = new Highlight(range1, range2);
console.log(highlight.size); // 2

highlight.delete(range1);
console.log(highlight.size); // 1
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-set.prototype.delete |

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

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

See also
--------

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


Highlight: priority property - Web APIs

Highlight: priority property
============================

It is possible to create `Range` objects that overlap in a document.

When overlapping ranges are used by multiple different `Highlight` objects, and when those highlights are styled using `::highlight` pseudo-elements, this may lead to conflicting styles.

If two text ranges overlap and are both highlighted using the CSS Custom Highlight API, and if they're both styled using the `color` CSS property, the browser needs to decide which color should be used for styling the text in the overlapping part.

By default, all highlights have the same priority and the browser chooses the most recently registered highlight to style the overlapping parts.

The `priority` property of the `Highlight` interface is a `Number` used to change this default behavior and determine which highlight's styles should be used to resolve style conflicts in overlapping parts.

Note that all the styles of a highlight are applied and the browser only needs to resolve conflicts when the same CSS properties are used by multiple overlapping highlights. The highlight style conflict resolution also does not depend on the order in which the `::highlight` pseudo-elements rules appear in the source, or whether or not CSS properties are marked as `!important`.

Value
-----

An integer.

Examples
--------

### Default priority

#### HTML

```html
<p>Time is an illusion. Lunchtime doubly so.</p>
```

#### CSS

```css
::highlight(highlight-2) {
  color: blue;
}

::highlight(highlight-1) {
  color: white;
  background: orange;
}
```

#### JavaScript

```js
const text = document.querySelector("p").firstChild;

// Create two overlapping highlights
const range1 = new Range();
range1.setStart(text, 5);
range1.setEnd(text, 25);

const range2 = new Range();
range2.setStart(text, 15);
range2.setEnd(text, 35);

const highlight1 = new Highlight(range1);
const highlight2 = new Highlight(range2);

CSS.highlights.set("highlight-1", highlight1);
CSS.highlights.set("highlight-2", highlight2);
```

#### Result

As seen below, by default, the part of the text node where the two registered highlights overlap is displayed in blue because `highlight-2` is registered after `highlight-1`. The background color defined by `highlight-1` includes the entire `range1` range because it does not conflict with another background color.

### Setting priority

#### HTML

```html
<button id="prioritize-1" type="button">Prioritize 1</button>
<button id="prioritize-2" type="button">Prioritize 2</button>
<button id="reset" type="button">Reset</button>
<p>Time is an illusion. Lunchtime doubly so.</p>
```

#### CSS

```css
::highlight(highlight-1) {
  background-color: blue;
  color: white;
}

::highlight(highlight-2) {
  background-color: orange;
}
```

#### JavaScript

```js
const text = document.querySelector("p").firstChild;

// Create two overlapping highlights
const range1 = new Range();
range1.setStart(text, 5);
range1.setEnd(text, 25);

const range2 = new Range();
range2.setStart(text, 15);
range2.setEnd(text, 35);

const highlight1 = new Highlight(range1);
const highlight2 = new Highlight(range2);

CSS.highlights.set("highlight-1", highlight1);
CSS.highlights.set("highlight-2", highlight2);

// Add buttons to change the highlight priority.
const prioritize1 = document.querySelector("#prioritize-1");
const prioritize2 = document.querySelector("#prioritize-2");
const reset = document.querySelector("#reset");

prioritize1.addEventListener("click", () => {
  highlight1.priority = 1;
  highlight2.priority = 0;
});

prioritize2.addEventListener("click", () => {
  highlight1.priority = 0;
  highlight2.priority = 1;
});

reset.addEventListener("click", () => {
  highlight1.priority = 0;
  highlight2.priority = 0;
});
```

#### Result

As seen below, by default, the part of the text node where the two registered highlights overlap is displayed in blue because `highlight-2` is registered after `highlight-1`.

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

| Specification |
| --- |
| CSS Custom Highlight API Module Level 1 # dom-highlight-priority |

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

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

See also
--------

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


Highlight: forEach() method - Web APIs

Highlight: forEach() method
===========================

The **`forEach()`** method of the `Highlight` interface executes a provided function once for each `Range` object in the `Highlight` object, in insertion order.

`Highlight` is a `Set`-like object, so this is similar to using `Set.forEach()`.

Syntax
------

```js
forEach(callbackFn)
forEach(callbackFn, thisArg)
```

### Parameters

`callback`

Function to execute for each `Range` object, taking three arguments:

`range`, `key`

 The current `Range` object being processed in the `Highlight`. As there are no
 keys in `Highlight`, the `range` is passed for both arguments.

`highlight`

The `Highlight` object which `forEach()` was called upon.

`thisArg`

Value to use as `this` when executing `callbackFn`.

### Return value

None (`undefined`).

Examples
--------

The code snippet below shows how create a new highlight with two ranges, and then log the ranges by using the `forEach()` method:

```js
function logRanges(range, key, highlight) {
  console.log(`Highlight object ${highlight} contains range ${range}`);
}

const text = new Text("Time is an illusion. Lunchtime doubly so.");

const range1 = document.createRange();
range1.setStart(text, 0);
range1.setEnd(text, 4);

const range2 = document.createRange();
range2.setStart(text, 21);
range2.setEnd(text, 30);

const myHighlight = new Highlight();
myHighlight.add(range1);
myHighlight.add(range2);

myHighlight.forEach(logRanges);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-set.prototype.foreach |

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

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

See also
--------

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


Highlight: add() method - Web APIs

Highlight: add() method
=======================

The **`add()`** method of the `Highlight` interface adds a new `Range` object to a highlight, to be styled using the CSS Custom Highlight API.

`Highlight` is a `Set`-like object, so this is similar to using `Set.add()`.

Syntax
------

```js
add(range)
```

### Parameters

`range`

A `Range` object to add to the `Highlight`.

### Return value

The `Highlight` object, with the added range.

Examples
--------

The code snippet below shows how to add two ranges to a new highlight object:

```js
const highlight = new Highlight();

const range1 = new Range();
const range2 = new Range();

highlight.add(range1).add(range2);

console.log(highlight.size); // 2
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-set.prototype.add |

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

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

See also
--------

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


Highlight: has() method - Web APIs

Highlight: has() method
=======================

The **`has()`** method of the `Highlight` interface returns a boolean indicating whether a `Range` object exists in a `Highlight` object or not.

`Highlight` is a `Set`-like object, so this is similar to using `Set.has()`.

Syntax
------

```js
has(range)
```

### Parameters

`range`

The `Range` object to test for presence in the `Highlight` object.

### Return value

Returns `true` if the specified range exists in the `Highlight` object; otherwise `false`.

Examples
--------

The code snippet below creates two ranges, and a highlight object that contains one of them. The code then uses the `has()` method to check whether each range exists in the highlight:

```js
const range1 = new Range();
const range2 = new Range();
const myHighlight = new Highlight(range1);

myHighlight.has(range1); // true
myHighlight.has(range2); // false
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-set.prototype.has |

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

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

See also
--------

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


Highlight: Highlight() constructor - Web APIs

Highlight: Highlight() constructor
==================================

 The **`Highlight()`** constructor returns a newly created
 `Highlight` object which can hold a collection of `Range` objects to be styled using the CSS Custom Highlight API.

Syntax
------

```js
new Highlight()
new Highlight(range)
new Highlight(range1, range2, /\* …, \*/ rangeN)
```

### Parameters

`range1, /* …, */ rangeN` Optional

One ore more initial `Range` objects to add in the new highlight.

### Return value

A new `Highlight` object.

Examples
--------

The example code below demonstrates how to create an empty highlight object, and then add ranges to it:

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

The example code below demonstrates how to create a new highlight object and add ranges to it during instantiation:

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

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

| Specification |
| --- |
| CSS Custom Highlight API Module Level 1 # dom-highlight-highlight |

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

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

See also
--------

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


Highlight: type property - Web APIs

Highlight: type property
========================

The `type` property of the `Highlight` interface is an enumerated `String` used to specify the meaning of the highlight. This allows assistive technologies, such as screen readers, to include this meaning when exposing the highlight to users.

By default, a highlight object will have its type set to `highlight`, but you can change it to `spelling-error` or `grammar-error`.

Value
-----

The possible values of the `type` enumerated value are:

`highlight`

This is the default highlight type. It does not have any specific meaning.

`spelling-error`

Use this type when the highlight is used to emphasize misspelled content.

`grammar-error`

Use this type when the highlight is used to emphasize content that is grammatically incorrect.

Examples
--------

```js
const spellErrorRange = new Range();
spellErrorRange.setStart(textNode, 10);
spellErrorRange.setEnd(textNode, 20);

const spellErrorsHighlight = new Highlight(spellErrorRange);

spellErrorsHighlight.type = "spelling-error";
```

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

| Specification |
| --- |
| CSS Custom Highlight API Module Level 1 # enumdef-highlighttype |

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

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

See also
--------

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


Highlight: clear() method - Web APIs

Highlight: clear() method
=========================

The **`clear()`** method of the `Highlight` interface removes all the `Range` objects from a `Highlight` object.

`Highlight` is a `Set`-like object, so this is similar to using `Set.clear()`.

Syntax
------

```js
clear()
```

### Return value

None (`undefined`).

Examples
--------

The code snippet below shows how to create a new highlight with two ranges, and then clear it:

```js
const highlight = new Highlight(range1, range2);
console.log(highlight.size); // 2

highlight.clear();
console.log(highlight.size); // 0
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-set.prototype.clear |

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

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

See also
--------

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


ContentIndex: delete() method - Web APIs

ContentIndex: delete() method
=============================

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

 The **`delete()`** method of the
 `ContentIndex` interface unregisters an item from the currently indexed
 content.

**Note:** Calling `delete()` only affects the index. It does not delete anything
 from the `Cache`.

Syntax
------

```js
ContentIndex.delete(id).then(/\* … \*/)
```

### Parameters

`id`

The unique identifier of the indexed content you want the `ContentIndex` object to remove.

### Return value

Returns a `Promise` that resolves with `undefined`

### Exceptions

No exceptions are thrown.

Examples
--------

 Below is an asynchronous function, that removes an item from the content index. We receive a reference to the current
 `ServiceWorkerRegistration`, which allows us to access the
 `index` property and thus access the
 `delete` method.

```js
async function unregisterContent(article) {
  // reference registration
  const registration = await navigator.serviceWorker.ready;

  // feature detect Content Index
  if (!registration.index) return;

  // unregister content from index
  await registration.index.delete(article.id);
}
```

 The `delete` method can also be used within the
 service worker scope.

```js
self.registration.index.delete("my-id");
```

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

| Specification |
| --- |
| Content Index # content-index-delete |

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

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

See also
--------

* An introductory article on the Content Index API
* An app which uses the Content Index API to list and remove 'save for later' content
* Service Worker API, along with information about Cache and CacheStorage


ContentIndex: add() method - Web APIs

ContentIndex: add() method
==========================

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

 The **`add()`** method of the
 `ContentIndex` interface registers an item with the content index.

Syntax
------

```js
add(contentDescription)
```

### Parameters

`contentDescription`

An `Object` containing the following data:

`id`

A unique `String` identifier.

`title`

 A `String` title for the item. Used in
 user-visible lists of content.

`description`

 A `String` description of the item. Used
 in user-visible lists of content.

`url`

 A `String` containing the URL of the corresponding
 HTML document. Needs to be under the scope of the current
 `service worker`.

`category` Optional

 A `String` defining the
 category of content. Can be:

* `''` An empty `String`, this is the default.
* `homepage`
* `article`
* `video`
* `audio`

`icons` Optional

 An `Array` of image
 resources, defined as an `Object` with the following data:

`src`

A URL `String` of the source image.

`sizes` Optional

A `String` representation of the image size.

`type` Optional

The MIME type of the image.

### Return value

Returns a `Promise` that resolves with `undefined`

### Exceptions

`TypeError`

This exception is thrown in the following conditions:

* The service worker's registration is not present or the service worker does not
 contain a `FetchEvent`.
* The `id`, `title`, `description` or
 `url` are missing, not of type `String`, or an empty `String`.
* One of the items in `icons` are not an image type, or fetching one of the items in `icons` failed with a network error.

Examples
--------

 Here we're declaring an item in the correct format and creating an asynchronous
 function which uses the `add` method to register it with the
 content index.

```js
// our content
const item = {
  id: "post-1",
  url: "/posts/amet.html",
  title: "Amet consectetur adipisicing",
  description:
    "Repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.",
  icons: [
    {
      src: "/media/dark.png",
      sizes: "128x128",
      type: "image/png",
    },
  ],
  category: "article",
};

// our asynchronous function to add indexed content
async function registerContent(data) {
  const registration = await navigator.serviceWorker.ready;

  // feature detect Content Index
  if (!registration.index) {
    return;
  }

  // register content
  try {
    await registration.index.add(data);
  } catch (e) {
    console.log("Failed to register content: ", e.message);
  }
}
```

 The `add` method can also be used within the
 service worker scope.

```js
// our content
const item = {
  id: "post-1",
  url: "/posts/amet.html",
  title: "Amet consectetur adipisicing",
  description:
    "Repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.",
  icons: [
    {
      src: "/media/dark.png",
      sizes: "128x128",
      type: "image/png",
    },
  ],
  category: "article",
};

self.registration.index.add(item);
```

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

| Specification |
| --- |
| Content Index # content-index-add |

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

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

See also
--------

* An introductory article on the Content Index API
* An app which uses the Content Index API to list and remove 'save for later' content
* Service Worker API, along with information about Cache and CacheStorage


ContentIndex: getAll() method - Web APIs

ContentIndex: getAll() method
=============================

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

 The **`getAll()`** method of the
 `ContentIndex` interface returns a `Promise` that resolves with
 an iterable list of content index entries.

Syntax
------

```js
getAll()
```

### Parameters

This method receives no parameters.

### Return value

 Returns a `Promise` that resolves with an `Array` of
 `contentDescription` items.

`contentDescription`

Each item returned is an `Object` containing the following data:

`id`

A unique `String` identifier.

`title`

 A `String` title of the item.
 Used in user-visible lists of content.

`description`

 A `String` description of the item.
 Used in user-visible lists of content.

`url`

 A `String` containing the URL of the corresponding HTML document.
 Needs to be under the scope of the current `service worker`.

`category` Optional

 A `String` defining the category of content.
 Can be:

* `''` An empty `String`, this is the default.
* `homepage`
* `article`
* `video`
* `audio`

`icons` Optional

An `Array` of image resources, defined as an `Object` with the following data:

`src`

A URL `String` of the source image.

`sizes` Optional

A `String` representation of the image size.

`type` Optional

The MIME type of the image.

### Exceptions

 No exceptions are thrown. If there are no items in the Content Index, an empty
 `Array` is returned.

Examples
--------

 The below example shows an asynchronous function that retrieves items within the
 content index and iterates over each entry, building
 a list for the interface.

```js
async function createReadingList() {
  // access our service worker registration
  const registration = await navigator.serviceWorker.ready;

  // get our index entries
  const entries = await registration.index.getAll();

  // create a containing element
  const readingListElem = document.createElement("div");

  // test for entries
  if (!Array.length) {
    // if there are no entries, display a message
    const message = document.createElement("p");
    message.innerText =
      "You currently have no articles saved for offline reading.";

    readingListElem.append(message);
  } else {
    // if entries are present, display in a list of links to the content
    const listElem = document.createElement("ul");

    for (const entry of entries) {
      const listItem = document.createElement("li");

      const anchorElem = document.createElement("a");
      anchorElem.innerText = entry.title;
      anchorElem.setAttribute("href", entry.url);

      listElem.append(listItem);
    }

    readingListElem.append(listElem);
  }
}
```

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

| Specification |
| --- |
| Content Index # content-index-getall |

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

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

See also
--------

* An introductory article on the Content Index API
* An app which uses the Content Index API to list and remove 'save for later' content
* Service Worker API, along with information about Cache and CacheStorage


SyncEvent: tag property - Web APIs

SyncEvent: tag property
=======================

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

 The **`tag`** read-only property of the
 `SyncEvent` interface returns the developer-defined identifier for
 this `SyncEvent`. This is the value passed in the `tag` parameter
 of the `SyncEvent()` constructor.

Value
-----

The developer-defined identifier for this `SyncEvent`.

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

| Specification |
| --- |
| Web Background Synchronization # ref-for-dom-syncevent-tag |

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

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


SyncEvent: lastChance property - Web APIs

SyncEvent: lastChance property
==============================

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

 The **`lastChance`** read-only property of the
 `SyncEvent` interface returns `true` if the user agent will not
 make further synchronization attempts after the current attempt. This is the value
 passed in the `lastChance` parameter of the
 `SyncEvent()` constructor.

Value
-----

 A boolean value that indicates whether the user agent will not make further
 synchronization attempts after the current attempt.

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

| Specification |
| --- |
| Web Background Synchronization # ref-for-dom-syncevent-lastchance③ |

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

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


SyncEvent: SyncEvent() constructor - Web APIs

SyncEvent: SyncEvent() constructor
==================================

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

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

Syntax
------

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

### Parameters

`type`

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

`options`

An object that, in addition to the properties defined in `ExtendableEvent()`, can have the following properties:

`tag`

A developer-defined unique identifier for this `SyncEvent`.

`lastChance` Optional

 A boolean value indicating that the user agent will not make further synchronization attempts after the current attempt.
 It defaults to `false`.

### Return value

A new `SyncEvent` object.

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

| Specification |
| --- |
| Web Background Synchronization # dom-syncevent-syncevent |

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

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


SpeechRecognition: maxAlternatives property - Web APIs

SpeechRecognition: maxAlternatives property
===========================================

 The **`maxAlternatives`** property of the
 `SpeechRecognition` interface sets the maximum number of
 `SpeechRecognitionAlternative`s provided per
 `SpeechRecognitionResult`.

The default value is 1.

Value
-----

A number representing the maximum returned alternatives for each result.

Examples
--------

This code is excerpted from our Speech color changer example.

```js
const grammar =
  "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
//recognition.continuous = false;
recognition.lang = "en-US";
recognition.interimResults = false;
recognition.maxAlternatives = 1;

// ...
```

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

| Specification |
| --- |
| Web Speech API # dom-speechrecognition-maxalternatives |

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

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

See also
--------

* Web Speech API


SpeechRecognition: abort() method - Web APIs

SpeechRecognition: abort() method
=================================

 The **`abort()`** method of the Web Speech API stops the speech
 recognition service from listening to incoming audio, and doesn't attempt to return a
 `SpeechRecognitionResult`.

Syntax
------

```js
abort()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
const grammar =
  "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;

const diagnostic = document.querySelector(".output");
const bg = document.querySelector("html");

document.body.onclick = () => {
  recognition.start();
  console.log("Ready to receive a color command.");
};

abortBtn.onclick = () => {
  recognition.abort();
  console.log("Speech recognition aborted.");
};

recognition.onspeechend = () => {
  recognition.stop();
  console.log("Speech recognition has stopped.");
};
```

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

| Specification |
| --- |
| Web Speech API # dom-speechrecognition-abort |

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

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

See also
--------

* Web Speech API


SpeechRecognition: grammars property - Web APIs

SpeechRecognition: grammars property
====================================

 The **`grammars`** property of the
 `SpeechRecognition` interface returns and sets a collection of
 `SpeechGrammar` objects that represent the grammars that will be understood
 by the current `SpeechRecognition`.

Value
-----

 A `SpeechGrammarList` containing the `SpeechGrammar` objects
 that represent your grammar for your app.

Examples
--------

 This code is excerpted from our
 Speech color changer example.

```js
const grammar =
  "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
//recognition.continuous = false;
recognition.lang = "en-US";
recognition.interimResults = false;
recognition.maxAlternatives = 1;

// ...
```

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

| Specification |
| --- |
| Web Speech API # dom-speechrecognition-grammars |

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

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

See also
--------

* Web Speech API


SpeechRecognition: soundend event - Web APIs

SpeechRecognition: soundend event
=================================

The **`soundend`** event of the Web Speech API is fired when any sound — recognizable speech or not — has stopped being detected.

Syntax
------

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

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

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

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

A generic `Event` with no added properties.

Examples
--------

You can use the `soundend` event in an `addEventListener` method:

```js
const recognition = new webkitSpeechRecognition() || new SpeechRecognition();

recognition.addEventListener("soundend", (event) => {
  console.log("Sound has stopped being received");
});
```

Or use the `onsoundend` event handler property:

```js
recognition.onsoundend = (event) => {
  console.log("Sound has stopped being received");
};
```

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

| Specification |
| --- |
| Web Speech API # eventdef-speechrecognition-soundend |
| Web Speech API # dom-speechrecognition-onsoundend |

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

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

See also
--------

* Web Speech API


SpeechRecognition: speechend event - Web APIs

SpeechRecognition: speechend event
==================================

The **`speechend`** event of the Web Speech API is fired when speech recognized by the speech recognition service has stopped being detected.

Syntax
------

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

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

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

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

A generic `Event` with no added properties.

Examples
--------

You can use the `speechend` event in an `addEventListener` method:

```js
const recognition = new webkitSpeechRecognition() || new SpeechRecognition();

recognition.addEventListener("speechend", () => {
  console.log("Speech has stopped being detected");
});
```

Or use the `onspeechend` event handler property:

```js
recognition.onspeechend = () => {
  console.log("Speech has stopped being detected");
};
```

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

| Specification |
| --- |
| Web Speech API # eventdef-speechrecognition-speechend |
| Web Speech API # dom-speechrecognition-onspeechend |

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

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

See also
--------

* Web Speech API


SpeechRecognition: end event - Web APIs

SpeechRecognition: end event
============================

The **`end`** event of the Web Speech API `SpeechRecognition` object is fired when the speech recognition service has disconnected.

Syntax
------

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

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

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

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

A generic `Event` with no added properties.

Examples
--------

You can use the `end` event in an `addEventListener` method:

```js
const recognition = new webkitSpeechRecognition() || new SpeechRecognition();

recognition.addEventListener("end", () => {
  console.log("Speech recognition service disconnected");
});
```

Or use the `onend` event handler property:

```js
recognition.onend = () => {
  console.log("Speech recognition service disconnected");
};
```

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

| Specification |
| --- |
| Web Speech API # eventdef-speechrecognition-end |
| Web Speech API # dom-speechrecognition-onend |

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

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

See also
--------

* Web Speech API


SpeechRecognition: stop() method - Web APIs

SpeechRecognition: stop() method
================================

 The **`stop()`** method of the Web Speech API stops the speech
 recognition service from listening to incoming audio, and attempts to return a
 `SpeechRecognitionResult` using the audio captured so far.

Syntax
------

```js
stop()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
const grammar =
  "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;

const diagnostic = document.querySelector(".output");
const bg = document.querySelector("html");

document.body.onclick = () => {
  recognition.start();
  console.log("Ready to receive a color command.");
};

abortBtn.onclick = () => {
  recognition.abort();
  console.log("Speech recognition aborted.");
};

recognition.onspeechend = () => {
  recognition.stop();
  console.log("Speech recognition has stopped.");
};
```

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

| Specification |
| --- |
| Web Speech API # dom-speechrecognition-stop |

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

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

See also
--------

* Web Speech API


SpeechRecognition: continuous property - Web APIs

SpeechRecognition: continuous property
======================================

 The **`continuous`** property of the
 `SpeechRecognition` interface controls whether continuous results are
 returned for each recognition, or only a single result.

It defaults to single results (`false`.)

Value
-----

 A boolean value representing the current `SpeechRecognition`'s
 continuous status. `true` means continuous, and `false` means not
 continuous (single result each time.)

Examples
--------

This code is excerpted from our Speech color changer example.

```js
const grammar =
  "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
recognition.continuous = false;
recognition.lang = "en-US";
recognition.interimResults = false;
recognition.maxAlternatives = 1;

// ...
```

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

| Specification |
| --- |
| Web Speech API # dom-speechrecognition-continuous |

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

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

See also
--------

* Web Speech API


SpeechRecognition: audioend event - Web APIs

SpeechRecognition: audioend event
=================================

The **`audioend`** event of the Web Speech API is fired when the user agent has finished capturing audio for speech recognition.

Syntax
------

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

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

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

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

A generic `Event` with no added properties.

Examples
--------

You can use the `audioend` event in an `addEventListener` method:

```js
const recognition = new webkitSpeechRecognition() || new SpeechRecognition();

recognition.addEventListener("audioend", () => {
  console.log("Audio capturing ended");
});
```

Or use the `onaudioend` event handler property:

```js
recognition.onaudioend = () => {
  console.log("Audio capturing ended");
};
```

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

| Specification |
| --- |
| Web Speech API # eventdef-speechrecognition-audioend |
| Web Speech API # dom-speechrecognition-onaudioend |

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

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

See also
--------

* Web Speech API


SpeechRecognition: error event - Web APIs

SpeechRecognition: error event
==============================

The **`error`** event of the Web Speech API `SpeechRecognition` object is fired when a speech recognition error occurs.

Syntax
------

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

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

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

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

A `SpeechRecognitionErrorEvent`. Inherits from `Event`.

Event

SpeechRecognitionErrorEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`SpeechRecognitionErrorEvent.error` Read only

Returns the type of error raised.

`SpeechRecognitionErrorEvent.message` Read only

Returns a message describing the error in more detail.

Examples
--------

You can use the `error` event in an `addEventListener` method:

```js
const recognition = new webkitSpeechRecognition() || new SpeechRecognition();

recognition.addEventListener("error", (event) => {
  console.error(`Speech recognition error detected: ${event.error}`);
});
```

Or use the `onerror` event handler property:

```js
recognition.onerror = (event) => {
  console.error(`Speech recognition error detected: ${event.error}`);
};
```

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

| Specification |
| --- |
| Web Speech API # eventdef-speechrecognition-error |
| Web Speech API # dom-speechrecognition-onerror |

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

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

See also
--------

* Web Speech API


SpeechRecognition: lang property - Web APIs

SpeechRecognition: lang property
================================

 The **`lang`** property of the `SpeechRecognition`
 interface returns and sets the language of the current `SpeechRecognition`.
 If not specified, this defaults to the HTML `lang` attribute
 value, or the user agent's language setting if that isn't set either.

Value
-----

A string representing the BCP 47 language tag for the current `SpeechRecognition`.

Examples
--------

This code is excerpted from our Speech color changer example.

```js
const grammar =
  "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
//recognition.continuous = false;
recognition.lang = "en-US";
recognition.interimResults = false;
recognition.maxAlternatives = 1;

// ...
```

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

| Specification |
| --- |
| Web Speech API # dom-speechrecognition-lang |

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

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

See also
--------

* Web Speech API


SpeechRecognition: audiostart event - Web APIs

SpeechRecognition: audiostart event
===================================

The **`audiostart`** event of the Web Speech API is fired when the user agent has started to capture audio for speech recognition.

Syntax
------

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

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

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

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

A generic `Event` with no added properties.

Examples
--------

You can use the `audiostart` event in an `addEventListener` method:

```js
const recognition = new webkitSpeechRecognition() || new SpeechRecognition();

recognition.addEventListener("audiostart", () => {
  console.log("Audio capturing started");
});
```

Or use the `onaudiostart` event handler property:

```js
recognition.onaudiostart = () => {
  console.log("Audio capturing started");
};
```

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

| Specification |
| --- |
| Web Speech API # eventdef-speechrecognition-audiostart |
| Web Speech API # dom-speechrecognition-onaudiostart |

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

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

See also
--------

* Web Speech API


SpeechRecognition: speechstart event - Web APIs

SpeechRecognition: speechstart event
====================================

The **`speechstart`** event of the Web Speech API is fired when sound recognized by the speech recognition service as speech has been detected.

Syntax
------

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

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

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

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

A generic `Event` with no added properties.

Examples
--------

You can use the `speechstart` event in an `addEventListener` method:

```js
const recognition = new webkitSpeechRecognition() || new SpeechRecognition();

recognition.addEventListener("speechstart", () => {
  console.log("Speech has been detected");
});
```

Or use the `onspeechstart` event handler property:

```js
recognition.onspeechstart = () => {
  console.log("Speech has been detected");
};
```

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

| Specification |
| --- |
| Web Speech API # eventdef-speechrecognition-speechstart |
| Web Speech API # dom-speechrecognition-onspeechstart |

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

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

See also
--------

* Web Speech API


SpeechRecognition: result event - Web APIs

SpeechRecognition: result event
===============================

The **`result`** event of the Web Speech API is fired when the speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app

Syntax
------

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

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

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

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

A `SpeechRecognitionEvent`. Inherits from `Event`.

Event

SpeechRecognitionEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`SpeechRecognitionEvent.emma` Read only

Returns an Extensible MultiModal Annotation markup language (EMMA) — XML — representation of the result.

`SpeechRecognitionEvent.interpretation` Read only

Returns the semantic meaning of what the user said.

`SpeechRecognitionEvent.resultIndex` Read only

Returns the lowest index value result in the `SpeechRecognitionResultList` "array" that has actually changed.

`SpeechRecognitionEvent.results` Read only

Returns a `SpeechRecognitionResultList` object representing all the speech recognition results for the current session.

Examples
--------

This code is excerpted from our Speech color changer example.

You can use the `result` event in an `addEventListener` method:

```js
const recognition = new SpeechRecognition();

recognition.addEventListener("result", (event) => {
  const color = event.results[0][0].transcript;
  diagnostic.textContent = `Result received: ${color}.`;
  bg.style.backgroundColor = color;
});
```

Or use the `onresult` event handler property:

```js
recognition.onresult = (event) => {
  const color = event.results[0][0].transcript;
  diagnostic.textContent = `Result received: ${color}.`;
  bg.style.backgroundColor = color;
};
```

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

| Specification |
| --- |
| Web Speech API # eventdef-speechrecognition-result |
| Web Speech API # dom-speechrecognition-onresult |

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

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

See also
--------

* Web Speech API


SpeechRecognition: nomatch event - Web APIs

SpeechRecognition: nomatch event
================================

The **`nomatch`** event of the Web Speech API is fired when the speech recognition service returns a final result with no significant recognition.

This may involve some degree of recognition, which doesn't meet or exceed the `confidence` threshold.

Syntax
------

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

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

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

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

A `SpeechRecognitionEvent`. Inherits from `Event`.

Event

SpeechRecognitionEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`SpeechRecognitionEvent.emma` Read only

Returns an Extensible MultiModal Annotation markup language (EMMA) — XML — representation of the result.

`SpeechRecognitionEvent.interpretation` Read only

Returns the semantic meaning of what the user said.

`SpeechRecognitionEvent.resultIndex` Read only

Returns the lowest index value result in the `SpeechRecognitionResultList` "array" that has actually changed.

`SpeechRecognitionEvent.results` Read only

Returns a `SpeechRecognitionResultList` object representing all the speech recognition results for the current session.

Examples
--------

You can use the `nomatch` event in an `addEventListener` method:

```js
const recognition = new webkitSpeechRecognition() || new SpeechRecognition();

recognition.addEventListener("nomatch", () => {
  console.error("Speech not recognized");
});
```

Or use the `onnomatch` event handler property:

```js
recognition.onnomatch = () => {
  console.error("Speech not recognized");
};
```

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

| Specification |
| --- |
| Web Speech API # eventdef-speechrecognition-nomatch |
| Web Speech API # dom-speechrecognition-onnomatch |

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

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

See also
--------

* Web Speech API


SpeechRecognition: interimResults property - Web APIs

SpeechRecognition: interimResults property
==========================================

 The **`interimResults`** property of the
 `SpeechRecognition` interface controls whether interim results should be
 returned (`true`) or not (`false`.) Interim results are results
 that are not yet final (e.g. the `SpeechRecognitionResult.isFinal` property
 is `false`.)

The default value for **`interimResults`** is `false`.

Value
-----

 A boolean value representing the state of the current
 `SpeechRecognition`'s interim results. `true` means interim
 results are returned, and `false` means they aren't.

Examples
--------

This code is excerpted from our Speech color changer example.

```js
const grammar =
  "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
//recognition.continuous = false;
recognition.lang = "en-US";
recognition.interimResults = false;
recognition.maxAlternatives = 1;

// ...
```

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

| Specification |
| --- |
| Web Speech API # dom-speechrecognition-interimresults |

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

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

See also
--------

* Web Speech API


SpeechRecognition: soundstart event - Web APIs

SpeechRecognition: soundstart event
===================================

The **`soundstart`** event of the Web Speech API is fired when any sound — recognizable speech or not — has been detected.

Syntax
------

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

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

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

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

A generic `Event` with no added properties.

Examples
--------

You can use the `soundstart` event in an `addEventListener` method:

```js
const recognition = new webkitSpeechRecognition() || new SpeechRecognition();

recognition.addEventListener("soundstart", () => {
  console.log("Some sound is being received");
});
```

Or use the `onsoundstart` event handler property:

```js
recognition.onsoundstart = () => {
  console.log("Some sound is being received");
};
```

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

| Specification |
| --- |
| Web Speech API # eventdef-speechrecognition-soundstart |
| Web Speech API # dom-speechrecognition-onsoundstart |

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

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

See also
--------

* Web Speech API


SpeechRecognition: SpeechRecognition() constructor - Web APIs

SpeechRecognition: SpeechRecognition() constructor
==================================================

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

Syntax
------

```js
new SpeechRecognition()
```

### Parameters

None.

Examples
--------

This code is excerpted from our Speech color changer example.

```js
const grammar =
  "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
//recognition.continuous = false;
recognition.lang = "en-US";
recognition.interimResults = false;
recognition.maxAlternatives = 1;

// ...
```

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

| Specification |
| --- |
| Web Speech API # dom-speechrecognition-speechrecognition |

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

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

See also
--------

* Web Speech API


SpeechRecognition: start event - Web APIs

SpeechRecognition: start event
==============================

The **`start`** event of the Web Speech API `SpeechRecognition` object is fired when the speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current `SpeechRecognition`.

Syntax
------

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

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

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

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

A generic `Event` with no added properties.

Examples
--------

You can use the `start` event in an `addEventListener` method:

```js
const recognition = new webkitSpeechRecognition() || new SpeechRecognition();

recognition.addEventListener("start", () => {
  console.log("Speech recognition service has started");
});
```

Or use the `onstart` event handler property:

```js
recognition.onstart = () => {
  console.log("Speech recognition service has started");
};
```

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

| Specification |
| --- |
| Web Speech API # eventdef-speechrecognition-start |
| Web Speech API # dom-speechrecognition-onstart |

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

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

See also
--------

* Web Speech API


SpeechRecognition: start() method - Web APIs

SpeechRecognition: start() method
=================================

 The **`start()`** method of the Web Speech API starts the speech
 recognition service listening to incoming audio with intent to recognize grammars
 associated with the current `SpeechRecognition`.

Syntax
------

```js
start()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
const grammar =
  "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;

const diagnostic = document.querySelector(".output");
const bg = document.querySelector("html");

document.body.onclick = () => {
  recognition.start();
  console.log("Ready to receive a color command.");
};

abortBtn.onclick = () => {
  recognition.abort();
  console.log("Speech recognition aborted.");
};

recognition.onspeechend = () => {
  recognition.stop();
  console.log("Speech recognition has stopped.");
};
```

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

| Specification |
| --- |
| Web Speech API # dom-speechrecognition-start |

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

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

See also
--------

* Web Speech API


DOMException: name property - Web APIs

DOMException: name property
===========================

 The **`name`** read-only property of the
 `DOMException` interface returns a string that contains
 one of the strings associated with an error name.

Value
-----

A string.

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

| Specification |
| --- |
| Web IDL Standard # dom-domexception-name |

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

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


DOMException: code property - Web APIs

DOMException: code property
===========================

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

The **`code`** read-only property of the `DOMException` interface returns one of the legacy error code constants, or `0` if none match.

This field is used for historical reasons. New DOM exceptions don't use this anymore: they put this info in the `DOMException.name` attribute.

Value
-----

One of the error code constants, or `0` if none match.

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

| Specification |
| --- |
| Web IDL Standard # dom-domexception-code |

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

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


DOMException: DOMException() constructor - Web APIs

DOMException: DOMException() constructor
========================================

 The **`DOMException()`** constructor returns a
 `DOMException` object with a specified message and name.

Syntax
------

```js
new DOMException()
new DOMException(message)
new DOMException(message, name)
```

### Parameters

`message` Optional

 A description of the exception. If not present, the empty string `''` is
 used.

`name` Optional

A string. If the specified name is a standard error name, then getting the `code` property of the `DOMException` object will return the code number corresponding to the specified name.

### Return value

A newly created `DOMException` object.

Examples
--------

In this example, pressing the button causes a custom `DOMException` to be thrown, which is then caught and the custom error message shown in an alert.

### HTML

```html
<button>Trigger DOM Exception</button>

<p id="output"></p>
```

### JavaScript

```js
const button = document.querySelector("button");

button.onclick = () => {
  try {
    throw new DOMException("Custom DOM Exception Triggered.");
  } catch (error) {
    document.querySelector("#output").textContent = `Error: ${error.message}`;
  }
};
```

### Result

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

| Specification |
| --- |
| Web IDL Standard # dom-domexception-domexception |

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

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

See also
--------

* A polyfill of `DOMException` constructor is available in `core-js`


DOMException: message property - Web APIs

DOMException: message property
==============================

 The **`message`** read-only property of the
 `DOMException` interface returns a string representing
 a message or description associated with the given error name.

Value
-----

A string.

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

| Specification |
| --- |
| Web IDL Standard # dom-domexception-message |

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

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


Accelerometer: z property - Web APIs

Accelerometer: z property
=========================

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

The **`z`** read-only property of the `Accelerometer` interface returns a number specifying the acceleration of the device along its z-axis.

Value
-----

A `Number`.

Examples
--------

Acceleration is typically read in the `reading` event callback. In the example below this occurs sixty times a second.

```js
const accelerometer = new Accelerometer({ frequency: 60 });

accelerometer.addEventListener("reading", (e) => {
  console.log(`Acceleration along the X-axis ${accelerometer.x}`);
  console.log(`Acceleration along the Y-axis ${accelerometer.y}`);
  console.log(`Acceleration along the Z-axis ${accelerometer.z}`);
});
accelerometer.start();
```

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

| Specification |
| --- |
| Accelerometer # accelerometer-z |

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

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


Accelerometer: Accelerometer() constructor - Web APIs

Accelerometer: Accelerometer() constructor
==========================================

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

The **`Accelerometer()`** constructor creates a new `Accelerometer` object which returns the acceleration of the device along all three axes at the time it is read.

Syntax
------

```js
new Accelerometer()
new Accelerometer(options)
```

### Parameters

`options` Optional

Options are as follows:

`frequency`

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

`referenceFrame`

Either `'device'` or `'screen'`. The default is `'device'`.

### Exceptions

`SecurityError` `DOMException`

Use of this feature was blocked by a Permissions Policy.

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

| Specification |
| --- |
| Accelerometer # dom-accelerometer-accelerometer |

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

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

See also
--------

* `reading` event


Accelerometer: y property - Web APIs

Accelerometer: y property
=========================

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

The **`y`** read-only property of the `Accelerometer` interface returns a number specifying the acceleration of the device along its y-axis.

Value
-----

A `Number`.

Examples
--------

Acceleration is typically read in the `reading` event callback. In the example below this occurs sixty times a second.

```js
const accelerometer = new Accelerometer({ frequency: 60 });

accelerometer.addEventListener("reading", (e) => {
  console.log(`Acceleration along the X-axis ${accelerometer.x}`);
  console.log(`Acceleration along the Y-axis ${accelerometer.y}`);
  console.log(`Acceleration along the Z-axis ${accelerometer.z}`);
});
accelerometer.start();
```

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

| Specification |
| --- |
| Accelerometer # accelerometer-y |

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

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


Accelerometer: x property - Web APIs

Accelerometer: x property
=========================

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

The **`x`** read-only property of the `Accelerometer` interface returns a number specifying the acceleration of the device along its x-axis.

Value
-----

A `Number`.

Examples
--------

Acceleration is typically read in the `reading` event callback. In the example below this occurs sixty times a second.

```js
const accelerometer = new Accelerometer({ frequency: 60 });

accelerometer.addEventListener("reading", (e) => {
  console.log(`Acceleration along the X-axis ${accelerometer.x}`);
  console.log(`Acceleration along the Y-axis ${accelerometer.y}`);
  console.log(`Acceleration along the Z-axis ${accelerometer.z}`);
});
accelerometer.start();
```

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

| Specification |
| --- |
| Accelerometer # accelerometer-x |

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

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


AudioParam: cancelAndHoldAtTime() method - Web APIs

AudioParam: cancelAndHoldAtTime() method
========================================

 The **`cancelAndHoldAtTime()`** method of the
 `AudioParam` interface cancels all scheduled future changes to the
 `AudioParam` but holds its value at a given time until further changes are
 made using other methods.

Syntax
------

```js
cancelAndHoldAtTime(cancelTime)
```

### Parameters

`cancelTime`

 A double representing the time (in seconds) after the `AudioContext` was
 first created after which all scheduled changes will be cancelled.

### Return value

A reference to the `AudioParam` it was called on.

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

| Specification |
| --- |
| Web Audio API # dom-audioparam-cancelandholdattime |

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

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


AudioParam: setValueAtTime() method - Web APIs

AudioParam: setValueAtTime() method
===================================

 The `setValueAtTime()` method of the
 `AudioParam` interface schedules an instant change to the
 `AudioParam` value at a precise time, as measured against
 `AudioContext.currentTime`. The new value is given in the value parameter.

Syntax
------

```js
setValueAtTime(value, startTime)
```

### Parameters

`value`

 A floating point number representing the value the AudioParam will change to at the
 given time.

`startTime`

 A double representing the time (in seconds) after the `AudioContext`
 was first created that the change in value will happen. If the time is less than `AudioContext.currentTime`, the change happens immediately. A `TypeError` is thrown if this value is negative.

### Return value

 A reference to this `AudioParam` object. In some browsers older
 implementations of this interface return `undefined`.

Examples
--------

 This simple example features a media element source with two control buttons (see our
 webaudio-examples repo for the source code, or view the example live). When the buttons are pressed, the `currGain` variable is
 incremented/decremented by 0.25, then the `setValueAtTime()` method is used
 to set the gain value equal to `currGain`, one second from now
 (`audioCtx.currentTime + 1`.)

```js
// create audio context
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioCtx = new AudioContext();

// set basic variables for example
const myAudio = document.querySelector("audio");
const pre = document.querySelector("pre");
const myScript = document.querySelector("script");

pre.innerHTML = myScript.innerHTML;

const targetAtTimePlus = document.querySelector(".set-target-at-time-plus");
const targetAtTimeMinus = document.querySelector(".set-target-at-time-minus");

// Create a MediaElementAudioSourceNode
// Feed the HTMLMediaElement into it
const source = audioCtx.createMediaElementSource(myAudio);

// Create a gain node and set it's gain value to 0.5
const gainNode = audioCtx.createGain();
gainNode.gain.value = 0.5;
let currGain = gainNode.gain.value;

// connect the AudioBufferSourceNode to the gainNode
// and the gainNode to the destination
source.connect(gainNode);
gainNode.connect(audioCtx.destination);

// set buttons to do something onclick
targetAtTimePlus.onclick = () => {
  currGain += 0.25;
  gainNode.gain.setValueAtTime(currGain, audioCtx.currentTime + 1);
};

targetAtTimeMinus.onclick = () => {
  currGain -= 0.25;
  gainNode.gain.setValueAtTime(currGain, audioCtx.currentTime + 1);
};
```

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

| Specification |
| --- |
| Web Audio API # dom-audioparam-setvalueattime |

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

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

See also
--------

* Using the Web Audio API