Animation: finish event - Web APIs

Animation: finish event
=======================

Baseline 2022
-------------

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

* Learn more
* See full compatibility
* Report feedback

 The **`finish`** event of the `Animation` interface is fired when the animation finishes playing, either when the animation completes naturally, or
 when the `Animation.finish()` method is called to immediately cause the
 animation to finish up.

**Note:** The `"paused"` play state supersedes the `"finished"` play
 state; if the animation is both paused and finished, the `"paused"` state
 is the one that will be reported. You can force the animation into the
 `"finished"` state by setting its `startTime` to
 `document.timeline.currentTime - (Animation.currentTime * Animation.playbackRate)`.

Syntax
------

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

```js
addEventListener("finish", (event) => { })
onfinish = (event) => { }
```

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

An `AnimationPlaybackEvent`. Inherits from `Event`.

Event

AnimationPlaybackEventEvent properties
----------------

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

`AnimationPlaybackEvent.currentTime` Read only

The current time of the animation that generated the event.

`AnimationPlaybackEvent.timelineTime` Read only

The time value of the timeline of the animation that generated the event.

Examples
--------

`Animation.onfinish` is used several times in the Alice in Web Animations API Land
 Growing/Shrinking Alice Game.
 Here is one instance where we add pointer events back to an element after
 its opacity animation has faded it in:

```js
// Add an animation to the game's ending credits
const endingUI = document.getElementById("ending-ui");
const bringUI = endingUI.animate(keysFade, timingFade);

// Pause said animation's credits
bringUI.pause();

// This function removes pointer events on the credits.
hide(endingUI);

// When the credits are later faded in,
// we re-add the pointer events when they're done
bringUI.onfinish = (event) => {
  endingUI.style.pointerEvents = "auto";
};
```

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

| Specification |
| --- |
| Web Animations # dom-animation-onfinish |
| Web Animations # finish-event |

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

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

See also
--------

* Web Animations API
* `Animation`
* `Animation.finish()`


MediaQueryListEvent: media property - Web APIs

MediaQueryListEvent: media property
===================================

 The **`media`** read-only property of the
 `MediaQueryListEvent` interface is a string representing
 a serialized media query.

Value
-----

A string representing a serialized media query.

Examples
--------

```js
const para = document.querySelector("p"); // This is the UI element where to display the text
const mql = window.matchMedia("(max-width: 600px)");

mql.addEventListener("change", (event) => {
  if (event.matches) {
    // The viewport is 600 pixels wide or less
    para.textContent = "This is a narrow screen — less than 600px wide.";
    document.body.style.backgroundColor = "red";
  } else {
    // The viewport is more than 600 pixels wide
    para.textContent = "This is a wide screen — more than 600px wide.";
    document.body.style.backgroundColor = "blue";
  }

  console.log(event.media);
});
```

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

| Specification |
| --- |
| CSSOM View Module # dom-mediaquerylistevent-media |

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

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

See also
--------

* Media queries
* Using media queries from code
* `window.matchMedia()`
* `MediaQueryList`
* `MediaQueryListEvent`


MediaQueryListEvent: MediaQueryListEvent() constructor - Web APIs

MediaQueryListEvent: MediaQueryListEvent() constructor
======================================================

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

Syntax
------

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

### Parameters

`type`

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

`options` Optional

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

`media` Optional

A string representing a serialized media query. It defaults to `""`.

`matches` Optional

A boolean value representing the media query status; `true` if it matches, `false` if not. It defaults to `false`.

### Return value

A new `MediaQueryListEvent` object.

Examples
--------

```js
const media = "(max-width: 600px)";
const matches = true;

const myMediaQueryListEvent = new MediaQueryListEvent("change", {
  media,
  matches,
});
```

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

| Specification |
| --- |
| CSSOM View Module # dom-mediaquerylistevent-mediaquerylistevent |

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

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

See also
--------

* Media queries
* Using media queries from code
* `window.matchMedia()`
* `MediaQueryList`
* `MediaQueryListEvent`


MediaQueryListEvent: matches property - Web APIs

MediaQueryListEvent: matches property
=====================================

 The **`matches`** read-only property of the
 `MediaQueryListEvent` interface is a boolean value that is
 `true` if the `document` currently matches the media query list,
 or `false` if not.

Value
-----

 A boolean value; returns `true` if the `document`
 currently matches the media query list, `false` if not.

Examples
--------

```js
const para = document.querySelector("p"); // This is the UI element where to display the text
const mql = window.matchMedia("(max-width: 600px)");

mql.addEventListener("change", (event) => {
  if (event.matches) {
    // The viewport is 600 pixels wide or less
    para.textContent = "This is a narrow screen — less than 600px wide.";
    document.body.style.backgroundColor = "red";
  } else {
    // The viewport is more than 600 pixels wide
    para.textContent = "This is a wide screen — more than 600px wide.";
    document.body.style.backgroundColor = "blue";
  }
});
```

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

| Specification |
| --- |
| CSSOM View Module # dom-mediaquerylistevent-matches |

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

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

See also
--------

* Media queries
* Using media queries from code
* `window.matchMedia()`
* `MediaQueryList`
* `MediaQueryListEvent`


CSSLayerBlockRule: name property - Web APIs

CSSLayerBlockRule: name property
================================

Baseline 2022
-------------

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

* Learn more
* See full compatibility
* Report feedback
The read-only **`name`** property of the `CSSLayerBlockRule` interface represents the name of the associated cascade layer.

Value
-----

A string containing the name of the layer, or `""` if the layer is anonymous.

Examples
--------

### HTML

```html
<output></output> <output></output>
```

### CSS

```css
output {
  display: block;
}

@layer special {
  div {
    color: rebeccapurple;
  }
}

@layer {
  div {
    color: black;
  }
}
```

### JavaScript

```js
const item1 = document.getElementsByTagName("output")[0];
const item2 = document.getElementsByTagName("output")[1];
const rules = document.styleSheets[1].cssRules;
// Note that stylesheet #1 is the stylesheet associated with this embedded example,
// while stylesheet #0 is the stylesheet associated with the whole MDN page

const layer = rules[1]; // A CSSLayerBlockRule
const anonymous = rules[2]; // An anonymous CSSLayerBlockRule

item1.textContent = `The first CSSLayerBlockRule defines the "${layer.name}" layer.`;
item2.textContent = `A second CSSLayerBlockRule defines a layer with the following name: "${anonymous.name}".`;
```

### Result

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

| Specification |
| --- |
| CSS Cascading and Inheritance Level 5 # dom-csslayerblockrule-name |

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

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

See also
--------

* The statement declaration of an `@layer` is represented by a `CSSLayerStatementRule`.
* How to create named cascade layers in CSS.


ImageBitmapRenderingContext: transferFromImageBitmap() method - Web APIs

ImageBitmapRenderingContext: transferFromImageBitmap() method
=============================================================

 The **`ImageBitmapRenderingContext.transferFromImageBitmap()`**
 method displays the given `ImageBitmap` in the canvas associated with this
 rendering context. The ownership of the `ImageBitmap` is transferred to the
 canvas as well.

 This method was previously named `transferImageBitmap()`, but was renamed in
 a spec change. The old name is being kept as an alias to avoid code breakage.

Syntax
------

```js
transferFromImageBitmap(bitmap)
```

### Parameters

`bitmap`

An `ImageBitmap` object to transfer.

### Return value

None (`undefined`).

Examples
--------

### HTML

```html
<canvas id="htmlCanvas"></canvas>
```

### JavaScript

```js
const htmlCanvas = document
  .getElementById("htmlCanvas")
  .getContext("bitmaprenderer");

// Draw a WebGL scene offscreen
const offscreen = new OffscreenCanvas(256, 256);
const gl = offscreen.getContext("webgl");

// Perform some drawing using the gl context

// Transfer the current frame to the visible canvas
const bitmap = offscreen.transferToImageBitmap();
htmlCanvas.transferFromImageBitmap(bitmap);
```

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

| Specification |
| --- |
| HTML Standard # dom-imagebitmaprenderingcontext-transferfromimagebitmap-dev |

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

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

See also
--------

* The interface defining this method, `ImageBitmapRenderingContext`
* `OffscreenCanvas`
* `OffscreenCanvas.transferToImageBitmap()`


HTMLTitleElement: text property - Web APIs

HTMLTitleElement: text property
===============================

The **`text`** property of the `HTMLTitleElement` interface represents the text of the document's title. Only the text part is included; tags within the element and their content are stripped and ignored.

Value
-----

A string.

Examples
--------

Consider the example below:

```html
<!doctype html>
<html lang="en-US">
  <head>
    <title>
      Hello world! <span class="highlight">Isn't this wonderful</span> really?
    </title>
  </head>
  <body></body>
</html>
```

```js
const title = document.querySelector("title");
console.log(title.text); // yield: "Hello world! really?"
```

As you can see, the tag `span` and its content were skipped.

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

| Specification |
| --- |
| HTML Standard # dom-title-text-dev |

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

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


CSSKeywordValue: value property - Web APIs

CSSKeywordValue: value property
===============================

 The **`value`** property of the
 `CSSKeywordValue` interface returns or sets the value of the
 `CSSKeywordValue`.

Value
-----

A string.

### Exceptions

`TypeError`

Thrown if the `value` property is an empty `String` when being set.

Examples
--------

The following example resets the CSS `display` property to its defaults.

```js
let indicator = document.getElementById("indicator");
indicator.attributeStyleMap.set("display", new CSSKeywordValue("initial"));
indicator.attributeStyleMap.get("display").value; // 'initial'
```

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-csskeywordvalue-value |

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

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


CSSKeywordValue: CSSKeywordValue() constructor - Web APIs

CSSKeywordValue: CSSKeywordValue() constructor
==============================================

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

Syntax
------

```js
new CSSKeywordValue(val)
```

### Parameters

`value`

Sets or returns the value of the new `CSSKeywordValue`.

### Exceptions

`TypeError`

Thrown if the `value` parameter is not specified or it is not of type `String`.

Examples
--------

 The following example resets the CSS `display` property to its defaults,
 setting the inline
 `style` attribute
 to `style="display: initial"` if viewed in the developer tools inspector.
```

#myElement {
  display: flex;
}
```

```
<div id="myElement">
  Check the developer tools to see the log in the console and to inspect the
  style attribute on this div.
</div>
```

```js
const keyword = new CSSKeywordValue("initial");
const myElement = document.getElementById("myElement").attributeStyleMap;
myElement.set("display", keyword);

console.log(myElement.get("display").value); // 'initial'
console.dir(keyword);
```

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

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

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

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


PerformanceNavigationTiming: type property - Web APIs

PerformanceNavigationTiming: type property
==========================================

The **`type`** read-only property returns the type of navigation.

You can use this property to categorize your navigation timing data as each of these types will have different performance characteristics. Users going back and forth might experience a faster site than users performing navigation for the first time or submitting forms, etc.

For example, if your site provides new content frequently, you might want to refresh that content using Fetch or similar and avoid users having to hit reload for the entire page all the time. The `"reload"` type can help you find pages that are reloaded frequently.

Value
-----

The `type` property can have the following values:

`"navigate"`

Navigation started by clicking a link, entering the URL in the browser's address bar, form submission, or initializing through a script operation other than `reload` and `back_forward` as listed below.

`"reload"`

Navigation is through the browser's reload operation, `location.reload()` or a Refresh pragma directive like `<meta http-equiv="refresh" content="300">`.

`"back_forward"`

Navigation is through the browser's history traversal operation.

`"prerender"`

Navigation is initiated by a prerender hint.

Examples
--------

### Logging reload navigation

The `type` property can be used to check whether the navigation was of type `reload`. You could collect these `reload` entries in a server-side endpoint to determine which pages of your site gets reloaded the most, or collect all navigation types and determine what percent of users go back and forward, for example.

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

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (entry.type === "reload") {
      console.log(`${entry.name} was reloaded!`);
      console.log(entry);
    }
  });
});

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

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

```js
const entries = performance.getEntriesByType("navigation");
entries.forEach((entry) => {
  if (entry.type === "reload") {
    console.log(`${entry.name} was reloaded!`);
    console.log(entry);
  }
});
```

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

| Specification |
| --- |
| Navigation Timing Level 2 # dom-performancenavigationtiming-type |

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

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


PerformanceNavigationTiming: unloadEventStart property - Web APIs

PerformanceNavigationTiming: unloadEventStart property
======================================================

The **`unloadEventStart`** read-only property returns a `DOMHighResTimeStamp` representing the time immediately before the current document's `unload` event handler starts.

Value
-----

The `unloadEventStart` property can have the following values:

* A `DOMHighResTimeStamp` representing the time immediately before the current document's `unload` event handler starts.
* `0` if there is no previous document.
* `0` if the previous page was on another origin.
Examples
--------

### Measuring `unload` event handler time

The `unloadEventStart` property can be used to measure how long it takes process the`unload` event handler.

This is useful to measure the time of long running `unload` event handlers.

```js
window.addEventListener("unload", (event) => {
  // Some long running code
});
```

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

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    const unloadEventTime = entry.unloadEventEnd - entry.unloadEventStart;
    if (unloadEventTime > 0) {
      console.log(
        `${entry.name}: unload event handler time: ${unloadEventTime}ms`,
      );
    }
  });
});

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

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

```js
const entries = performance.getEntriesByType("navigation");
entries.forEach((entry) => {
  const loadEventTime = entry.unloadEventEnd - entry.unloadEventStart;
  if (unloadEventTime > 0) {
    console.log(`${entry.name}:
 load event handler time: ${unloadEventTime}ms`);
  }
});
```

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

| Specification |
| --- |
| Navigation Timing Level 2 # dom-performancenavigationtiming-unloadeventstart |

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

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

See also
--------

* `unload` event


PerformanceNavigationTiming: redirectCount property - Web APIs

PerformanceNavigationTiming: redirectCount property
===================================================

The **`redirectCount`** read-only property returns a number representing the number of redirects since the last non-redirect navigation in the current browsing context.

The higher the number of redirects on a page, the longer the page load time. To improve the performance of your web page, avoid multiple redirects.

The `redirectStart` and `redirectEnd` properties can be used to measure redirection time. Note that they will return `0` for cross-origin redirects.

Note that client side redirects, such as `<meta http-equiv="refresh" content="0; url=https://example.com/">` are not considered here.

Value
-----

The `redirectCount` property can have the following values:

* A number representing the number of redirects since the last non-redirect navigation in the current browsing context.
* `0` if the redirect is cross-origin.
Examples
--------

### Logging entries with redirects

The `redirectCount` property can be used to check whether there are one or more redirects. We log the entry's name and the redirection time if it is available.

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

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    const name = entry.name;
    const redirectCount = entry.redirectCount;
    const redirectTime = entry.redirectEnd - entry.redirectStart;
    if (redirectCount > 0) {
      console.log(`${name}: Redirect count: ${redirectCount}`);
      if (redirectTime > 0) {
        console.log(`${name}: Redirect time: ${redirectTime}ms`);
      }
    }
  });
});

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

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

```js
const entries = performance.getEntriesByType("navigation");
entries.forEach((entry) => {
  const name = entry.name;
  const redirectCount = entry.redirectCount;
  const redirectTime = entry.redirectEnd - entry.redirectStart;
  if (redirectCount > 0) {
    console.log(`${name}: Redirect count: ${redirectCount}`);
    if (redirectTime > 0) {
      console.log(`${name}: Redirect time: ${redirectTime}ms`);
    }
  }
});
```

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

| Specification |
| --- |
| Navigation Timing Level 2 # dom-performancenavigationtiming-redirectcount |

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

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

See also
--------

* `PerformanceResourceTiming.redirectStart`
* `PerformanceResourceTiming.redirectEnd`


PerformanceNavigationTiming: domComplete property - Web APIs

PerformanceNavigationTiming: domComplete property
=================================================

The **`domComplete`** read-only property returns a `DOMHighResTimeStamp` representing the time immediately before the user agent sets the document's `readyState` to `"complete"`.

See also the `complete` state of `Document.readyState` which corresponds to this property and refers to the state in which the document and all sub-resources have finished loading. The state also indicates that the `load` event is about to fire.

Value
-----

A `DOMHighResTimeStamp` representing the time immediately before the user agent sets the document's `readyState` to `"complete"`.

Examples
--------

### Logging DOM completion time

The `domComplete` property can be used to log the time when the DOM is complete.

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

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    console.log(`${entry.name}: domComplete time: ${entry.domComplete}ms`);
  });
});

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

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

```js
const entries = performance.getEntriesByType("navigation");
entries.forEach((entry) => {
  console.log(`${entry.name}: domComplete time: ${entry.domComplete}ms`);
});
```

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

| Specification |
| --- |
| Navigation Timing Level 2 # dom-performancenavigationtiming-domcomplete |

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

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

See also
--------

* `Document.readyState`


PerformanceNavigationTiming: domInteractive property - Web APIs

PerformanceNavigationTiming: domInteractive property
====================================================

The **`domInteractive`** read-only property returns a `DOMHighResTimeStamp` representing the time immediately before the user agent sets the document's `readyState` to `"interactive"`.

**Note:** This property is **not** Time to interactive (TTI). This property refers to the time when DOM construction is finished and interaction to it from JavaScript is possible. See also the `interactive` state of `Document.readyState` which corresponds to this property.

Measuring DOM processing time may not be consequential unless your site has a very large HTML source to a construct a Document Object Model from.

If there is no parser-blocking JavaScript then the `DOMContentLoaded` event (see `domContentLoadedEventStart` for the timestamp) will fire immediately after `domInteractive`.

Value
-----

A `DOMHighResTimeStamp` representing the time immediately before the user agent sets the document's `readyState` to `"interactive"`.

Examples
--------

### Logging DOM interaction time

The `domInteractive` property can be used to log the time when the DOM construction has finished and interaction with it is possible.

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

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    console.log(
      `${entry.name}: domInteractive time: ${entry.domInteractive}ms`,
    );
  });
});

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

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

```js
const entries = performance.getEntriesByType("navigation");
entries.forEach((entry) => {
  console.log(`${entry.name}: domInteractive time: ${entry.domInteractive}ms`);
});
```

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

| Specification |
| --- |
| Navigation Timing Level 2 # dom-performancenavigationtiming-dominteractive |

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

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

See also
--------

* `Document.readyState`


PerformanceNavigationTiming: unloadEventEnd property - Web APIs

PerformanceNavigationTiming: unloadEventEnd property
====================================================

The **`unloadEventEnd`** read-only property returns a `DOMHighResTimeStamp` representing the time immediately after the current document's `unload` event handler completes.

Value
-----

The `unloadEventEnd` property can have the following values:

* A `DOMHighResTimeStamp` representing the time immediately after the current document's `unload` event handler completes.
* `0` if there is no previous document.
* `0` if the previous page was on another origin.
Examples
--------

### Measuring `unload` event handler time

The `unloadEventEnd` property can be used to measure how long it takes process the`unload` event handler.

This is useful to measure the time of long running `unload` event handlers.

```js
window.addEventListener("unload", (event) => {
  // Some long running code
});
```

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

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    const unloadEventTime = entry.unloadEventEnd - entry.unloadEventStart;
    if (unloadEventTime > 0) {
      console.log(
        `${entry.name}: unload event handler time: ${unloadEventTime}ms`,
      );
    }
  });
});

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

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

```js
const entries = performance.getEntriesByType("navigation");
entries.forEach((entry) => {
  const loadEventTime = entry.unloadEventEnd - entry.unloadEventStart;
  if (unloadEventTime > 0) {
    console.log(`${entry.name}:
 load event handler time: ${unloadEventTime}ms`);
  }
});
```

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

| Specification |
| --- |
| Navigation Timing Level 2 # dom-performancenavigationtiming-unloadeventend |

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

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

See also
--------

* `unload` event


PerformanceNavigationTiming: domContentLoadedEventEnd property - Web APIs

PerformanceNavigationTiming: domContentLoadedEventEnd property
==============================================================

The **`domContentLoadedEventEnd`** read-only property returns a `DOMHighResTimeStamp` representing the time immediately after the current document's `DOMContentLoaded` event handler completes.

Typically frameworks and libraries wait for the `DOMContentLoaded` event before starting to run their code. We can use the `domContentLoadedEventEnd` and the `domContentLoadedEventStart` properties to calculate how long this takes to run.

Value
-----

A `DOMHighResTimeStamp` representing the time immediately after the current document's `DOMContentLoaded` event handler completes.

Examples
--------

### Measuring `DOMContentLoaded` event handler time

The `domContentLoadedEventEnd` property can be used to measure how long it takes process the `DOMContentLoaded` event handler.

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

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    const domContentLoadedTime =
      entry.domContentLoadedEventEnd - entry.domContentLoadedEventStart;
    console.log(
      `${entry.name}: DOMContentLoaded processing time: ${domContentLoadedTime}ms`,
    );
  });
});

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

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

```js
const entries = performance.getEntriesByType("navigation");
entries.forEach((entry) => {
  const domContentLoadedTime =
    entry.domContentLoadedEventEnd - entry.domContentLoadedEventStart;
  console.log(
    `${entry.name}: DOMContentLoaded processing time: ${domContentLoadedTime}ms`,
  );
});
```

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

| Specification |
| --- |
| Navigation Timing Level 2 # dom-performancenavigationtiming-domcontentloadedeventend |

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

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

See also
--------

* DOMContentLoaded


PerformanceNavigationTiming: domContentLoadedEventStart property - Web APIs

PerformanceNavigationTiming: domContentLoadedEventStart property
================================================================

The **`domContentLoadedEventStart`** read-only property returns a `DOMHighResTimeStamp` representing the time immediately before the current document's `DOMContentLoaded` event handler starts.

Typically frameworks and libraries wait for the `DOMContentLoaded` event before starting to run their code. We can use the `domContentLoadedEventStart` and the `domContentLoadedEventEnd` properties to calculate how long this takes to run.

Value
-----

A `DOMHighResTimeStamp` representing the time immediately before the current document's `DOMContentLoaded` event handler starts.

Examples
--------

### Measuring `DOMContentLoaded` event handler time

The `domContentLoadedEventStart` property can be used to measure how long it takes process the `DOMContentLoaded` event handler.

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

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    const domContentLoadedTime =
      entry.domContentLoadedEventEnd - entry.domContentLoadedEventStart;
    console.log(
      `${entry.name}: DOMContentLoaded processing time: ${domContentLoadedTime}ms`,
    );
  });
});

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

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

```js
const entries = performance.getEntriesByType("navigation");
entries.forEach((entry) => {
  const domContentLoadedTime =
    entry.domContentLoadedEventEnd - entry.domContentLoadedEventStart;
  console.log(
    `${entry.name}: DOMContentLoaded processing time: ${domContentLoadedTime}ms`,
  );
});
```

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

| Specification |
| --- |
| Navigation Timing Level 2 # dom-performancenavigationtiming-domcontentloadedeventstart |

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

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

See also
--------

* DOMContentLoaded


PerformanceNavigationTiming: loadEventEnd property - Web APIs

PerformanceNavigationTiming: loadEventEnd property
==================================================

The **`loadEventEnd`** read-only property returns a `DOMHighResTimeStamp` representing the time immediately after the current document's `load` event handler completes.

Value
-----

A `DOMHighResTimeStamp` representing the time immediately after the current document's `load` event handler completes.

Examples
--------

### Measuring `load` event handler time

The `loadEventEnd` property can be used to measure how long it takes process the`load` event handler.

This is useful to measure the time of long running `load` event handlers.

```js
window.addEventListener("load", (event) => {
  // Some long running code
});
```

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

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    const loadEventTime = entry.loadEventEnd - entry.loadEventStart;
    if (loadEventTime > 0) {
      console.log(`${entry.name}: load event handler time: ${loadEventTime}ms`);
    }
  });
});

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

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

```js
const entries = performance.getEntriesByType("navigation");
entries.forEach((entry) => {
  const loadEventTime = entry.loadEventEnd - entry.loadEventStart;
  if (loadEventTime > 0) {
    console.log(`${entry.name}:
 load event handler time: ${loadEventTime}ms`);
  }
});
```

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

| Specification |
| --- |
| Navigation Timing Level 2 # dom-performancenavigationtiming-loadeventend |

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

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

See also
--------

* `load` event


PerformanceNavigationTiming: activationStart property - Web APIs

PerformanceNavigationTiming: activationStart property
=====================================================

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

The **`activationStart`** read-only property represents the time between when a document starts prerendering and when it is activated.

Value
-----

A `DOMHighResTimeStamp` representing the duration between document prerendering start and activation in milliseconds.

The value is `0` if the page has not prerendered or is still prerendering.

Examples
--------

### Detecting prerendered pages

When a prerendered document is activated, `activationStart` is set to the current time. The following function can check whether a page is `prerendering` or has already prerendered:

```js
function pagePrerendered() {
  return (
    document.prerendering ||
    self.performance?.getEntriesByType?.("navigation")[0]?.activationStart > 0
  );
}
```

### Measuring user-perceived performance milestones

With prerendered pages, a page may have been created long before it was actually navigated to. When using the Performance API on prerendered pages, it is vital to compare returned values with `activationStart` in order to avoid misleading measurements.

```js
// Time to when activation occurred
let activationStart =
  performance.getEntriesByType("navigation")[0].activationStart;

// Time to first paint
let firstPaint = performance.getEntriesByName("first-paint")[0].startTime;

// Time to first contentful paint
let firstContentfulPaint = performance.getEntriesByName(
  "first-contentful-paint",
)[0].startTime;

console.log("time to first paint: " + (firstPaint - activationStart));
console.log(
  "time to first-contentful-paint: " + (firstContentfulPaint - activationStart),
);
```

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

| Specification |
| --- |
| Prerendering Revamped # dom-performancenavigationtiming-activationstart |

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

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

See also
--------

* Speculation Rules API
* Speculative loading


PerformanceNavigationTiming: loadEventStart property - Web APIs

PerformanceNavigationTiming: loadEventStart property
====================================================

The **`loadEventStart`** read-only property returns a `DOMHighResTimeStamp` representing the time immediately before the current document's `load` event handler starts.

Value
-----

A `DOMHighResTimeStamp` representing the time immediately before the current document's `load` event handler starts.

Examples
--------

### Measuring `load` event handler time

The `loadEventStart` property can be used to measure how long it takes process the`load` event handler.

This is useful to measure the time of long running `load` event handlers.

```js
window.addEventListener("load", (event) => {
  // Some long running code
});
```

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

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    const loadEventTime = entry.loadEventEnd - entry.loadEventStart;
    if (loadEventTime > 0) {
      console.log(`${entry.name}: load event handler time: ${loadEventTime}ms`);
    }
  });
});

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

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

```js
const entries = performance.getEntriesByType("navigation");
entries.forEach((entry) => {
  const loadEventTime = entry.loadEventEnd - entry.loadEventStart;
  if (loadEventTime > 0) {
    console.log(`${entry.name}:
 load event handler time: ${loadEventTime}ms`);
  }
});
```

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

| Specification |
| --- |
| Navigation Timing Level 2 # dom-performancenavigationtiming-loadeventstart |

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

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

See also
--------

* `load` event


PerformanceNavigationTiming: toJSON() method - Web APIs

PerformanceNavigationTiming: toJSON() method
============================================

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

Syntax
------

```js
toJSON()
```

### Parameters

None.

### Return value

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

Examples
--------

### Using the toJSON method

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

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

observer.observe({ entryTypes: ["navigation"] });
```

This would log a JSON object like so:

```json
{
  "name": "https://en.wikipedia.org/wiki/Main\_Page",
  "entryType": "navigation",
  "startTime": 0,
  "duration": 227.60000002384186,
  "initiatorType": "navigation",
  "nextHopProtocol": "h2",
  "renderBlockingStatus": "blocking",
  "workerStart": 0,
  "redirectStart": 4,
  "redirectEnd": 71.40000000596046,
  "fetchStart": 71.40000000596046,
  "domainLookupStart": 71.40000000596046,
  "domainLookupEnd": 71.40000000596046,
  "connectStart": 71.40000000596046,
  "connectEnd": 71.40000000596046,
  "secureConnectionStart": 71.40000000596046,
  "requestStart": 73.7000000178814,
  "responseStart": 102.90000000596046,
  "responseEnd": 105.2000000178814,
  "transferSize": 19464,
  "encodedBodySize": 19164,
  "decodedBodySize": 83352,
  "serverTiming": [
    {
      "name": "cache",
      "duration": 0,
      "description": "hit-front"
    },
    {
      "name": "host",
      "duration": 0,
      "description": "cp3062"
    }
  ],
  "unloadEventStart": 0,
  "unloadEventEnd": 0,
  "domInteractive": 178.10000002384186,
  "domContentLoadedEventStart": 178.2000000178814,
  "domContentLoadedEventEnd": 178.2000000178814,
  "domComplete": 227.60000002384186,
  "loadEventStart": 227.60000002384186,
  "loadEventEnd": 227.60000002384186,
  "type": "navigate",
  "redirectCount": 1,
  "activationStart": 0
}
```

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

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

| Specification |
| --- |
| Navigation Timing Level 2 # dom-performancenavigationtiming-tojson |

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

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

See also
--------

* `JSON`


VRFieldOfView: downDegrees property - Web APIs

VRFieldOfView: downDegrees property
===================================

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

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

The **`downDegrees`** read-only property of the `VRFieldOfView` interface returns the number of degrees downwards that the field of view extends in.

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

Value
-----

A double.

Examples
--------

See `VRFieldOfView` for example code.

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

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

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

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

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

See also
--------

* WebVR API


VRFieldOfView: upDegrees property - Web APIs

VRFieldOfView: upDegrees property
=================================

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

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

The **`upDegrees`** read-only property of the `VRFieldOfView` interface returns the number of degrees upwards that the field of view extends in.

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

Value
-----

A double.

Examples
--------

See `VRFieldOfView` for example code.

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

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

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

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

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

See also
--------

* WebVR API


VRFieldOfView: rightDegrees property - Web APIs

VRFieldOfView: rightDegrees property
====================================

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

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

The **`rightDegrees`** read-only property of the `VRFieldOfView` interface returns the number of degrees to the right that the field of view extends in.

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

Value
-----

A double.

Examples
--------

See `VRFieldOfView` for example code.

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

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

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

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

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

See also
--------

* WebVR API


VRFieldOfView: leftDegrees property - Web APIs

VRFieldOfView: leftDegrees property
===================================

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

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

The **`leftDegrees`** read-only property of the `VRFieldOfView` interface returns the number of degrees to the left that the field of view extends in.

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

Value
-----

A double.

Examples
--------

See `VRFieldOfView` for example code.

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

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

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

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

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

See also
--------

* WebVR API


BarProp: visible property - Web APIs

BarProp: visible property
=========================

The **`visible`** read-only property of the `BarProp` interface returns `true` if the user interface element it represents is visible.

Value
-----

 A `Boolean`, which is true if the top-level window is opened by
 `window.open` with the requesting a popup window.popup\_feature.

**Note:** Historically this represented whether the interface element used is visible
 or not. But for privacy reasons, this no longer represents the actual visibility of each
 interface element.

Examples
--------

The following example prints `true` to the console if the window is not a popup.

```js
console.log(window.locationbar.visible);
```

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

| Specification |
| --- |
| HTML Standard # dom-barprop-visible |

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

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


SpeechSynthesis: cancel() method - Web APIs

SpeechSynthesis: cancel() method
================================

 The **`cancel()`** method of the `SpeechSynthesis`
 interface removes all utterances from the utterance queue.

If an utterance is currently being spoken, speaking will stop immediately.

Syntax
------

```js
cancel()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
const synth = window.speechSynthesis;

const utterance1 = new SpeechSynthesisUtterance(
  "How about we say this now? This is quite a long sentence to say.",
);
const utterance2 = new SpeechSynthesisUtterance(
  "We should say another sentence too, just to be on the safe side.",
);

synth.speak(utterance1);
synth.speak(utterance2);

synth.cancel(); // utterance1 stops being spoken immediately, and both are removed from the queue
```

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

| Specification |
| --- |
| Web Speech API # dom-speechsynthesis-cancel |

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

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

See also
--------

* Web Speech API


SpeechSynthesis: resume() method - Web APIs

SpeechSynthesis: resume() method
================================

 The **`resume()`** method of the `SpeechSynthesis`
 interface puts the `SpeechSynthesis` object into a non-paused state:
 resumes it if it was already paused.

Syntax
------

```js
resume()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
let synth = window.speechSynthesis;

let utterance1 = new SpeechSynthesisUtterance(
  "How about we say this now? This is quite a long sentence to say.",
);
let utterance2 = new SpeechSynthesisUtterance(
  "We should say another sentence too, just to be on the safe side.",
);

synth.speak(utterance1);
synth.speak(utterance2);

synth.pause(); // pauses utterances being spoken
synth.resume(); // resumes speaking
```

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

| Specification |
| --- |
| Web Speech API # dom-speechsynthesis-resume |

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

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

See also
--------

* Web Speech API


SpeechSynthesis: speaking property - Web APIs

SpeechSynthesis: speaking property
==================================

 The **`speaking`** read-only property of the
 `SpeechSynthesis` interface is a boolean value that returns
 `true` if an utterance is currently in the process of being spoken — even
 if `SpeechSynthesis` is in a
 `paused` state.

Value
-----

A boolean value.

Examples
--------

```js
const synth = window.speechSynthesis;

const utterance1 = new SpeechSynthesisUtterance(
  "How about we say this now? This is quite a long sentence to say.",
);
const utterance2 = new SpeechSynthesisUtterance(
  "We should say another sentence too, just to be on the safe side.",
);

synth.speak(utterance1);
synth.speak(utterance2);

const amISpeaking = synth.speaking; // will return true if utterance 1 or utterance 2 are currently being spoken
```

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

| Specification |
| --- |
| Web Speech API # dom-speechsynthesis-speaking |

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

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

See also
--------

* Web Speech API


SpeechSynthesis: pending property - Web APIs

SpeechSynthesis: pending property
=================================

 The **`pending`** read-only property of the
 `SpeechSynthesis` interface is a boolean value that returns
 `true` if the utterance queue contains as-yet-unspoken utterances.

Value
-----

A boolean value.

Examples
--------

```js
const synth = window.speechSynthesis;

const utterance1 = new SpeechSynthesisUtterance(
  "How about we say this now? This is quite a long sentence to say.",
);
const utterance2 = new SpeechSynthesisUtterance(
  "We should say another sentence too, just to be on the safe side.",
);

synth.speak(utterance1);
synth.speak(utterance2);

const amIPending = synth.pending; // will return true if utterance 1 is still being spoken and utterance 2 is in the queue
```

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

| Specification |
| --- |
| Web Speech API # dom-speechsynthesis-pending |

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

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

See also
--------

* Web Speech API


SpeechSynthesis: paused property - Web APIs

SpeechSynthesis: paused property
================================

 The **`paused`** read-only property of the
 `SpeechSynthesis` interface is a boolean value that returns
 `true` if the `SpeechSynthesis` object is in a paused state, or `false` if not.

 It can be set to `paused` even if nothing is
 currently being spoken through it. If
 `utterances` are then added to the utterance
 queue, they will not be spoken until the `SpeechSynthesis` object is
 unpaused, using `SpeechSynthesis.resume()`.

Value
-----

A boolean value.

Examples
--------

```js
const synth = window.speechSynthesis;

synth.pause();

const amIPaused = synth.paused; // will return true
```

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

| Specification |
| --- |
| Web Speech API # dom-speechsynthesis-paused |

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

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

See also
--------

* Web Speech API


SpeechSynthesis: pause() method - Web APIs

SpeechSynthesis: pause() method
===============================

 The **`pause()`** method of the `SpeechSynthesis`
 interface puts the `SpeechSynthesis` object into a paused state.

Syntax
------

```js
pause()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
const synth = window.speechSynthesis;

const utterance1 = new SpeechSynthesisUtterance(
  "How about we say this now? This is quite a long sentence to say.",
);
const utterance2 = new SpeechSynthesisUtterance(
  "We should say another sentence too, just to be on the safe side.",
);

synth.speak(utterance1);
synth.speak(utterance2);

synth.pause(); // pauses utterances being spoken
```

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

| Specification |
| --- |
| Web Speech API # dom-speechsynthesis-pause |

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

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

See also
--------

* Web Speech API


SpeechSynthesis: speak() method - Web APIs

SpeechSynthesis: speak() method
===============================

 The **`speak()`** method of the `SpeechSynthesis`
 interface adds an `utterance` to the utterance
 queue; it will be spoken when any other utterances queued before it have been spoken.

Syntax
------

```js
speak(utterance)
```

### Parameters

`utterance`

A `SpeechSynthesisUtterance` object.

### Return value

None (`undefined`).

Examples
--------

 This snippet is excerpted from our Speech synthesizer demo (see it live). When a form containing the text we want to speak is submitted,
 we (amongst other things) create a new utterance containing this text, then speak it by
 passing it into `speak()` as a parameter.

```js
const synth = window.speechSynthesis;

// ...

inputForm.onsubmit = (event) => {
  event.preventDefault();

  const utterThis = new SpeechSynthesisUtterance(inputTxt.value);
  const selectedOption =
    voiceSelect.selectedOptions[0].getAttribute("data-name");
  for (let i = 0; i < voices.length; i++) {
    if (voices[i].name === selectedOption) {
      utterThis.voice = voices[i];
    }
  }
  synth.speak(utterThis);
  inputTxt.blur();
};
```

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

| Specification |
| --- |
| Web Speech API # dom-speechsynthesis-speak |

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

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

See also
--------

* Web Speech API


SpeechSynthesis: voiceschanged event - Web APIs

SpeechSynthesis: voiceschanged event
====================================

The **`voiceschanged`** event of the Web Speech API is fired when the list of `SpeechSynthesisVoice` objects that would be returned by the `SpeechSynthesis.getVoices()` method has changed (when the `voiceschanged` event fires.)

Syntax
------

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

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

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

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

A generic `Event` with no added properties.

Examples
--------

This could be used to repopulate a list of voices that the user can choose between when the event fires. You can use the `voiceschanged` event in an `addEventListener` method:

```js
const synth = window.speechSynthesis;

synth.addEventListener("voiceschanged", () => {
  const voices = synth.getVoices();
  for (let i = 0; i < voices.length; i++) {
    const option = document.createElement("option");
    option.textContent = `${voices[i].name} (${voices[i].lang})`;
    option.setAttribute("data-lang", voices[i].lang);
    option.setAttribute("data-name", voices[i].name);
    voiceSelect.appendChild(option);
  }
});
```

Or use the `onvoiceschanged` event handler property:

```js
const synth = window.speechSynthesis;
synth.onvoiceschanged = () => {
  const voices = synth.getVoices();
  for (let i = 0; i < voices.length; i++) {
    const option = document.createElement("option");
    option.textContent = `${voices[i].name} (${voices[i].lang})`;
    option.setAttribute("data-lang", voices[i].lang);
    option.setAttribute("data-name", voices[i].name);
    voiceSelect.appendChild(option);
  }
};
```

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

| Specification |
| --- |
| Web Speech API # eventdef-speechsynthesis-voiceschanged |
| Web Speech API # dom-speechsynthesis-onvoiceschanged |

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

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

See also
--------

* Web Speech API


SpeechSynthesis: getVoices() method - Web APIs

SpeechSynthesis: getVoices() method
===================================

 The **`getVoices()`** method of the
 `SpeechSynthesis` interface returns a list of
 `SpeechSynthesisVoice` objects representing all the available voices on the
 current device.

Syntax
------

```js
getVoices()
```

### Parameters

None.

### Return value

A list (array) of `SpeechSynthesisVoice` objects.

Examples
--------

### JavaScript

```js
function populateVoiceList() {
  if (typeof speechSynthesis === "undefined") {
    return;
  }

  const voices = speechSynthesis.getVoices();

  for (let i = 0; i < voices.length; i++) {
    const option = document.createElement("option");
    option.textContent = `${voices[i].name} (${voices[i].lang})`;

    if (voices[i].default) {
      option.textContent += " — DEFAULT";
    }

    option.setAttribute("data-lang", voices[i].lang);
    option.setAttribute("data-name", voices[i].name);
    document.getElementById("voiceSelect").appendChild(option);
  }
}

populateVoiceList();
if (
  typeof speechSynthesis !== "undefined" &&
  speechSynthesis.onvoiceschanged !== undefined
) {
  speechSynthesis.onvoiceschanged = populateVoiceList;
}
```

### HTML

```html
<select id="voiceSelect"></select>
```

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

| Specification |
| --- |
| Web Speech API # dom-speechsynthesis-getvoices |

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

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

See also
--------

* Web Speech API


HTMLFormControlsCollection: namedItem() method - Web APIs

HTMLFormControlsCollection: namedItem() method
==============================================

 The **`HTMLFormControlsCollection.namedItem()`** method returns
 the `RadioNodeList` or the `Element` in the collection whose
 `name` or `id` match the specified name, or `null` if
 no node matches.

 Note that this version of `namedItem()` hides the one inherited from
 `HTMLCollection`. Like that one, in JavaScript, using the array bracket
 syntax with a `String`, like `collection["value"]` is
 equivalent to `collection.namedItem("value")`.

Syntax
------

```js
namedItem(name)
[name]
```

### Parameters

`name`

A string which will be used to match against the `name` or `id` attributes of the controls in this `HTMLFormControlsCollection` object.

### Return value

* A `RadioNodeList`, `Element`, or `null`.
Examples
--------

### Using namedItem()

#### HTML

```html
<form>
  <label for="notes">Notes:</label>
  <input id="notes" name="my-form-control" type="text" />

  <label for="start">Start date:</label>
  <input id="start" name="my-form-control" type="date" />
</form>

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

```
div {
  margin: 1rem 0;
}
```

#### JavaScript

```js
const form = document.querySelector("form");
const items = form.elements.namedItem("my-form-control");

const output = document.querySelector("#output");
const itemIDs = Array.from(items)
  .map((item) => `"${item.id}"`)
  .join(", ");
output.textContent = `My items: ${itemIDs}`;
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-htmlformcontrolscollection-nameditem-dev |

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

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

See also
--------

* `HTMLCollection.namedItem` that it replaces


Notification: click event - Web APIs

Notification: click event
=========================

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

 The **`click`** event of the `Notification`
 interface fires when the user clicks on displayed `Notification`.

 The default behavior is to move the focus to the viewport of the notification's related
 browsing context.
 If you don't want that behavior, call `preventDefault()` on the event object.

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

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

 In the following example, we use an onclick handler to open a webpage in a new tab
 (specified by the inclusion of the `'_blank'` parameter) once a notification
 is clicked:

```js
notification.onclick = (event) => {
  event.preventDefault(); // prevent the browser from focusing the Notification's tab
  window.open("http://www.mozilla.org", "\_blank");
};
```

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-onclick |

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

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

See also
--------

* `Notification`
* Using the Notifications API


Notification: title property - Web APIs

Notification: title property
============================

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

 The **`title`** read-only property of the
 `Notification` interface indicates the title of the notification, as
 specified in the `title` parameter of the
 `Notification()` constructor.

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

Value
-----

A string.

Examples
--------

```js
function spawnNotification(theBody, theIcon, theTitle) {
  const options = {
    body: theBody,
    icon: theIcon,
  };

  const n = new Notification(theTitle, options);

  console.log(n.title);
}
```

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-title |

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

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

See also
--------

* Using the Notifications API


Notification: renotify property - Web APIs

Notification: renotify property
===============================

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

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

 The **`renotify`** read-only property of the
 `Notification` interface specifies whether the user should be notified
 after a new notification replaces an old one, as specified in the `renotify`
 option of the `Notification()` constructor.

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

Value
-----

 A boolean value. `false` is the default; `true` makes
 the notification renotify the user.

Examples
--------

 The following snippet is intended to fire a notification that renotifies the user after
 it has been replaced; a simple `options` object is created, and then the
 notification is fired using the `Notification()` constructor.

```js
const options = {
  body: "Your code submission has received 3 new review comments.",
  renotify: true,
};

const n = new Notification("New review activity", options);

console.log(n.renotify); // "true"
```

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-renotify |

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

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

See also
--------

* Using the Notifications API


Notification: close() method - Web APIs

Notification: close() method
============================

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

 The **`close()`** method of the `Notification` interface is used to
 close/remove a previously displayed notification.

**Note:** This API shouldn't be used just to have the notification
 removed from the screen after a fixed delay since this method will also remove the
 notification from any notification tray, preventing users from interacting with it
 after it was initially shown. A valid use for this API would be to remove a
 notification that is no longer relevant (e.g. the user already read the notification
 on the webpage in the case of a messaging app or the following song is already playing
 in a music app).

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

Syntax
------

```js
close()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

 In the following snippet, we have a simple function that when called creates an
 `options` object and then a new notification. At the end of the function, it
 also calls `close()` inside a
 `addEventListener()` function to remove the
 notification when the relevant content has been read on the webpage.

```js
function spawnNotification(theBody, theIcon, theTitle) {
  const options = {
    body: theBody,
    icon: theIcon,
  };

  const n = new Notification(theTitle, options);
  document.addEventListener("visibilitychange", () => {
    if (document.visibilityState === "visible") {
      // The tab has become visible so clear the now-stale Notification.
      n.close();
    }
  });
}
```

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-close |

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

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

See also
--------

* Using the Notifications API


Notification: image property - Web APIs

Notification: image property
============================

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

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

 The **`image`** read-only property of the
 `Notification` interface contains the URL of an image to be displayed as
 part of the notification, as specified in the `image` option of the
 `Notification()` constructor.

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

Value
-----

A string.

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

| Specification |
| --- |
| Notifications API Standard # image-resource |

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

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

See also
--------

* Using the Notifications API


Notification: silent property - Web APIs

Notification: silent property
=============================

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

 The **`silent`** read-only property of the
 `Notification` interface specifies whether the notification should be
 silent, i.e., no sounds or vibrations should be issued, regardless of the device
 settings. This is specified in the `silent` option of the
 `Notification()` constructor.

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

Value
-----

 A boolean value. `false` is the default; `true` makes
 the notification silent.

Examples
--------

 The following snippet is intended to fire a silent notification; a simple
 `options` object is created, and then the notification is fired using the
 `Notification()` constructor.

```js
const options = {
  body: "Your code submission has received 3 new review comments.",
  silent: true,
};

const n = new Notification("New review activity", options);

console.log(n.silent); // "true"
```

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-silent |

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

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

See also
--------

* Using the Notifications API


Notification: badge property - Web APIs

Notification: badge property
============================

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

 The **`badge`** property of the `Notification`
 interface returns a string containing the URL of an image to represent the notification when there is not enough space to display the notification itself such as for example, the Android Notification Bar. On Android devices, the badge should accommodate devices up to 4x resolution, about 96 by 96 px, and the image will be automatically masked.

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

Value
-----

A string containing a URL.

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-badge |

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

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


Notification: data property - Web APIs

Notification: data property
===========================

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

 The **`data`** read-only property of the
 `Notification` interface returns a structured clone of the notification's
 data, as specified in the `data` option of the
 `Notification()` constructor.

 The notification's data can be any arbitrary data that you want associated with the
 notification.

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

Value
-----

A structured clone.

Examples
--------

 The following snippet fires a notification; a simple `options` object is
 created, then the notification is fired using the `Notification()`
 constructor.

```js
const options = {
  body: "Your code submission has received 3 new review comments.",
  data: {
    url: "https://example.com/review/12345",
    status: "open",
  },
};

const n = new Notification("New review activity", options);

console.log(n.data); // Logs the data object
```

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-data |

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

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

See also
--------

* Using the Notifications API


Notification: error event - Web APIs

Notification: error event
=========================

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

The **`error`** event of the `Notification` interface fires when something goes wrong with a `Notification` (in many cases an error preventing the notification from being displayed.)

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

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

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-onerror |

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

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

See also
--------

* `Notification`
* Using the Notifications API


Notification: dir property - Web APIs

Notification: dir property
==========================

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

The **`dir`** read-only property of the `Notification` interface indicates the text direction of the notification, as specified in the `dir` option of the `Notification()` constructor.

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

Value
-----

A string specifying the text direction. Possible values are:

`auto`

adopts the browser's language setting behavior (the default.)

`ltr`

left to right.

`rtl`

right to left.

**Note:** Most browsers seem to ignore explicit ltr and rtl settings, and just go with the browser-wide setting.

Examples
--------

The following snippet fires a notification; a simple `options` object is created, then the notification is fired using the `Notification()` constructor.

```js
const options = {
  body: "Your code submission has received 3 new review comments.",
  dir: "rtl",
};

const n = new Notification("New review activity", options);

console.log(n.dir); // "rtl"
```

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-dir |

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

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

See also
--------

* Using the Notifications API


Notification: requireInteraction property - Web APIs

Notification: requireInteraction property
=========================================

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

The **`requireInteraction`** read-only property of the `Notification` interface returns a boolean value indicating that a notification should remain active until the user clicks or dismisses it, rather than closing automatically.

**Note:** This can be set when the notification is first created by setting the `requireInteraction` option to `true` in the options object of the `Notification()` constructor.

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

Value
-----

A boolean value.

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-requireinteraction |

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

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

See also
--------

* Using the Notifications API


Notification: tag property - Web APIs

Notification: tag property
==========================

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

 The **`tag`** read-only property of the
 `Notification` interface signifies an identifying tag for the notification,
 as specified in the `tag` option of the
 `Notification()` constructor.

 The idea of notification tags is that more than one notification can share the same
 tag, linking them together. One notification can then be programmatically replaced with
 another to avoid the users' screen being filled up with a huge number of similar
 notifications.

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

Value
-----

A string.

Examples
--------

Our Using the Notifications API article has a good example of tag usage.

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-tag |

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

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

See also
--------

* Using the Notifications API


Notification: close event - Web APIs

Notification: close event
=========================

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

The **`close`** event of the `Notification` interface fires when a `Notification` is closed.

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

Syntax
------

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

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

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

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

A generic `Event`.

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

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

See also
--------

* `Notification`
* Using the Notifications API


Notification: vibrate property - Web APIs

Notification: vibrate property
==============================

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

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

 The **`vibrate`** read-only property of the `Notification`
 interface specifies a vibration pattern
 for the device's vibration hardware to emit when the notification fires. This is
 specified in the `vibrate` option of the
 `Notification()` constructor.

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

Value
-----

A vibration pattern, as specified in the Vibration API spec.

Examples
--------

 The following snippet is intended to create a notification that also triggers a device
 vibration; a simple `options` object is created, and then the notification is
 fired using the `Notification()` constructor.

```js
const options = {
  body: "Your code submission has received 3 new review comments.",
  vibrate: [200, 100, 200],
};

const n = new Notification("New review activity", options);

console.log(n.vibrate); // "[200, 100, 200]"
```

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-vibrate |

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

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

See also
--------

* Using the Notifications API


Notification: actions property - Web APIs

Notification: actions property
==============================

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

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

The **`actions`** read-only property of the `Notification` interface provides the actions available for users to choose from for interacting with the notification.

The actions are set using the `actions` option of the second argument for the `showNotification()` method and `Notification()` constructor.

**Note:** Browsers typically limit the maximum number of actions they will display for a particular notification. Check the static `Notification.maxActions` property to determine the limit.

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

Value
-----

A read-only array of actions. Each element in the array is an object with the following members:

`action`

A string identifying a user action to be displayed on the notification.

`title`

A string containing action text to be shown to the user.

`icon`

A string containing the URL of an icon to display with the action.

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-actions |

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

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

See also
--------

* Using the Notifications API
* `Notification.maxActions`


Notification: body property - Web APIs

Notification: body property
===========================

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

 The **`body`** read-only property of the
 `Notification` interface indicates the body string of the notification, as
 specified in the `body` option of the
 `Notification()` constructor.

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

Value
-----

A string.

Examples
--------

```js
function spawnNotification(theBody, theIcon, theTitle) {
  const options = {
    body: theBody,
    icon: theIcon,
  };
  const n = new Notification(theTitle, options);

  console.log(n.body);
}
```

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-body |

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

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

See also
--------

* Using the Notifications API


Notification: icon property - Web APIs

Notification: icon property
===========================

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

 The **`icon`** read-only property of the
 `Notification` interface contains the URL of an icon to be displayed as
 part of the notification, as specified in the `icon` option of the
 `Notification()` constructor.

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

Value
-----

A string.

Examples
--------

 In our To-do list app (view the app running live), we use the `Notification()`
 constructor to fire a notification, passing it arguments to specify the body, icon and
 title we want.

```js
const notification = new Notification("To do list", {
  body: text,
  icon: img,
});
```

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-icon |

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

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

See also
--------

* Using the Notifications API


Notification: maxActions static property - Web APIs

Notification: maxActions static property
========================================

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

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

 The **`maxActions`** read-only static property of the
 `Notification` interface returns the maximum number of actions supported by
 the device and the User Agent. Effectively, this is the maximum number of elements in
 `Notification.actions` array which will be respected by the User Agent.

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

Value
-----

 An integer number which indicates the largest number of notification
 actions that can be presented to the user by the User Agent and the device.

Examples
--------

The following snippet logs the maximum number of supported actions.

```js
const maxActions = Notification.maxActions;
console.log(
  `This device can display at most ${maxActions} actions on each notification.`,
);
```

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-maxactions |

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

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

See also
--------

* Using the Notifications API
* `Notification.actions`


Notification: requestPermission() static method - Web APIs

Notification: requestPermission() static method
===============================================

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

The **`requestPermission()`** static method of the `Notification` interface requests permission from the user for the current origin to display notifications.

Syntax
------

```js
// The latest spec has updated this method to a promise-based syntax that works like this:
Notification.requestPermission()

// Previously, the syntax was based on a simple callback; this version is now deprecated:
Notification.requestPermission(callback)
```

### Parameters

`callback` Optional
Deprecated

An optional callback function that is called with the permission value. Deprecated in favor of the promise return value.

### Return value

A `Promise` that resolves to a string with the permission picked by the user. Possible values for this string are:

`granted`

The user has explicitly granted permission for the current origin to display system notifications.

`denied`

The user has explicitly denied permission for the current origin to display system notifications.

`default`

The user decision is unknown; in this case the application will act as if permission was `denied`.

Examples
--------

Assume this basic HTML:

```html
<button onclick="notifyMe()">Notify me!</button>
```

It's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification.

```js
function notifyMe() {
  if (!("Notification" in window)) {
    // Check if the browser supports notifications
    alert("This browser does not support desktop notification");
  } else if (Notification.permission === "granted") {
    // Check whether notification permissions have already been granted;
    // if so, create a notification
    const notification = new Notification("Hi there!");
    // …
  } else if (Notification.permission !== "denied") {
    // We need to ask the user for permission
    Notification.requestPermission().then((permission) => {
      // If the user accepts, let's create a notification
      if (permission === "granted") {
        const notification = new Notification("Hi there!");
        // …
      }
    });
  }

  // At last, if the user has denied notifications, and you
  // want to be respectful there is no need to bother them anymore.
}
```

We no longer show a live sample on this page, as Chrome and Firefox no longer allow notification permissions to be requested from cross-origin `<iframe>`s, with other browsers to follow. To see an example in action, check out our To-do list example (also see the app running live).

**Note:** In the above example we spawn notifications in response to a user gesture (clicking a button). This is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture. Firefox is already doing this from version 72, for example.

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-requestpermission |

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

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

See also
--------

* Using the Notifications API


Notification: permission static property - Web APIs

Notification: permission static property
========================================

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

 The **`permission`** read-only static property of the `Notification`
 interface indicates the current permission granted by the user for the current origin to
 display web notifications.

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

Value
-----

A string representing the current permission. The value can be:

`granted`

 The user has explicitly granted permission for the current
 origin to display system notifications.

`denied`

 The user has explicitly denied permission for the current
 origin to display system notifications.

`default`

 The user decision is unknown; in this case the application
 will act as if permission was `denied`.

Examples
--------

 The following snippet could be used if you wanted to first check whether notifications
 are supported, then check if permission has been granted for the current origin to send
 notifications, then request permission if required, before then sending a notification.

```js
function notifyMe() {
  if (!("Notification" in window)) {
    // Check if the browser supports notifications
    alert("This browser does not support desktop notification");
  } else if (Notification.permission === "granted") {
    // Check whether notification permissions have already been granted;
    // if so, create a notification
    const notification = new Notification("Hi there!");
    // …
  } else if (Notification.permission !== "denied") {
    // We need to ask the user for permission
    Notification.requestPermission().then((permission) => {
      // If the user accepts, let's create a notification
      if (permission === "granted") {
        const notification = new Notification("Hi there!");
        // …
      }
    });
  }

  // At last, if the user has denied notifications, and you
  // want to be respectful there is no need to bother them anymore.
}
```

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-permission |

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

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

See also
--------

* Notifications API
* Using the Notifications API
* Permissions API
* Using the Permissions API


Notification: Notification() constructor - Web APIs

Notification: Notification() constructor
========================================

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

 The **`Notification()`** constructor creates a new
 `Notification` object instance, which represents a user notification.

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

Syntax
------

```js
new Notification(title)
new Notification(title, options)
```

### Parameters

`title`

 Defines a title for the notification, which is shown at the top of the notification
 window.

`options` Optional

 An options object containing any custom settings that you want to apply to the
 notification. The possible options are:

`dir` Optional

 The direction in which to display the notification. It
 defaults to `auto`, which just adopts the browser's language setting
 behavior, but you can override that behavior by setting values of `ltr`
 and `rtl` (although most browsers seem to ignore these settings.)

`lang` Optional

 The notification's language, as specified using a
 string representing a language tag
 according to RFC 5646: Tags for Identifying Languages (also known as BCP 47).
 See the Sitepoint ISO 2 letter language codes page for a simple reference. The default is the empty string.

`badge` Optional

 A string containing the URL of the image
 used to represent the notification when there isn't enough space to display the
 notification itself.

`body` Optional

 A string representing the body text of the
 notification, which is displayed below the title.
 The default is the empty string.

`tag` Optional

 A string representing an identifying tag for
 the notification. The default is the empty string.

`icon` Optional

 A string containing the URL of an icon to
 be displayed in the notification.

`image` Optional

 a string containing the URL of an image to
 be displayed in the notification.

`data` Optional

 Arbitrary data that you want associated with the
 notification. This can be of any data type.
 The default is `null`.

`vibrate` Optional

A vibration pattern for the device's vibration hardware to emit with the notification. If specified, `silent` must not be `true`.

`timestamp` Optional

A number representing the time at which a notification is created or applicable (past, present, or future).

`renotify` Optional

A boolean value specifying whether the user should be notified after a new notification replaces an old one. The default is `false`, which means they won't be notified. If `true`, then `tag` also must be set.

`requireInteraction` Optional

 Indicates that a notification should remain
 active until the user clicks or dismisses it, rather than closing automatically.
 The default value is `false`.

`actions` Optional

An array of actions to display in the notification, for which the default is an empty array. Each element in the array can be an object with the following members:

`action`

A string identifying a user action to be displayed on the notification.

`title`

A string containing action text to be shown to the user.

`icon` Optional

A string containing the URL of an icon to display with the action.

 Appropriate responses are built using `event.action` within the
 `notificationclick` event.

`silent` Optional

 A boolean value specifying whether the
 notification is silent (no sounds or vibrations issued), regardless of the device
 settings. The default is `null`. If `true`, then `vibrate` must not be present.

### Return value

An instance of the `Notification` object.

### Exceptions

`TypeError`

Thrown if:

* The constructor is called within the `ServiceWorkerGlobalScope`.
* The `actions` option is specified and is not empty.
* The `silent` option is `true` and the `vibrate` option is specified.
* The `renotify` option is `true` but the `tag` option is empty.

`DataCloneError` `DOMException`

Thrown if serializing the `data` option failed for some reason.

Examples
--------

 In our
 `Emogotchi demo`
 (see source code), we run a
 `spawnNotification()` function when we want to trigger a notification. The
 function is passed parameters to specify the body, icon, and title we want, and then it
 creates the necessary `options` object and triggers the notification by using
 the `Notification()` constructor.

```js
function spawnNotification(body, icon, title) {
  const notification = new Notification(title, { body, icon });
}
```

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-notification |

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

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

### Chrome notes

Starting in Chrome 49, notifications don't work in incognito mode.

 Chrome for Android will throw a `TypeError` when calling the
 `Notification` constructor. It only supports creating
 notifications from a service worker. See the
 Chromium issue tracker for more details.

See also
--------

* Using the Notifications API