AuthenticatorAttestationResponse: getPublicKey() method - Web APIs

AuthenticatorAttestationResponse: getPublicKey() method
=======================================================

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

The **`getPublicKey()`** method of the `AuthenticatorAttestationResponse` interface returns an `ArrayBuffer` containing the DER `SubjectPublicKeyInfo` of the new credential (see Subject Public Key Info), or `null` if this is not available.

This is a convenience function, created to allow easy access to the public key. This key will need to be stored in order to verify future authentication operations (i.e., using `navigator.credentials.get()`).

Syntax
------

```js
getPublicKey()
```

### Parameters

None.

### Return value

An `ArrayBuffer` containing the DER `SubjectPublicKeyInfo` of the new credential (see Subject Public Key Info), or `null` if this is not available.

Examples
--------

See Creating a public key credential using the WebAuthn API for a detailed example.

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

| Specification |
| --- |
| Web Authentication: An API for accessing Public Key Credentials - Level 3 # dom-authenticatorattestationresponse-getpublickey |

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

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


PushSubscription: toJSON() method - Web APIs

PushSubscription: toJSON() method
=================================

 The `toJSON()` method of the `PushSubscription` interface is a
 standard serializer: it returns a JSON representation of the subscription properties,
 providing a useful shortcut.

Syntax
------

```js
toJSON()
```

### Parameters

None.

### Return value

 A JSON object. It contains the subscription endpoint, `expirationTime` and public keys, as an
 `endpoint` member, an `expirationTime` member and a `keys` member.

Examples
--------

```js
navigator.serviceWorker.ready.then((reg) => {
  reg.pushManager.getSubscription().then((subscription) => {
    const mySubscription = subscription.toJSON();
    // do something with subscription details
  });
});
```

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

| Specification |
| --- |
| Push API # dom-pushsubscription-tojson |

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

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


PushSubscription: getKey() method - Web APIs

PushSubscription: getKey() method
=================================

 The `getKey()` method of the `PushSubscription` interface
 returns an `ArrayBuffer` representing a client public key, which can then
 be sent to a server and used in encrypting push message data.

Syntax
------

```js
getKey(name)
```

### Parameters

`name`

 A string representing the encryption method used to generate a
 client key. The value can be:

`p256dh`

 An Elliptic curve Diffie–Hellman public key on the P-256 curve (that is, the NIST
 secp256r1 elliptic curve). The resulting key is an uncompressed point in ANSI
 X9.62 format.

`auth`

An authentication secret, as described in Message Encryption for Web Push.

### Return value

An `ArrayBuffer` or `null` if no public key can be found.

Examples
--------

```js
reg.pushManager.getSubscription().then((subscription) => {
  // Enable any UI which subscribes / unsubscribes from
  // push messages.

  subBtn.disabled = false;

  if (!subscription) {
    console.log("Not yet subscribed to Push");
    // We aren't subscribed to push, so set UI
    // to allow the user to enable push
    return;
  }

  // Set your UI to show they have subscribed for
  // push messages
  subBtn.textContent = "Unsubscribe from Push Messaging";
  isPushEnabled = true;

  // initialize status, which includes setting UI elements for subscribed status
  // and updating Subscribers list via push
  const endpoint = subscription.endpoint;
  const key = subscription.getKey("p256dh");
  const auth = subscription.getKey("auth");

  // ...
});
```

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

| Specification |
| --- |
| Push API # dom-pushsubscription-getkey |

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

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


PushSubscription: unsubscribe() method - Web APIs

PushSubscription: unsubscribe() method
======================================

 The `unsubscribe()` method of the `PushSubscription` interface
 returns a `Promise` that resolves to a boolean value when the
 current subscription is successfully unsubscribed.

Syntax
------

```js
unsubscribe()
```

### Parameters

None.

### Return value

 A `Promise` that resolves to a boolean value when the current
 subscription is successfully unsubscribed.

Examples
--------

```js
navigator.serviceWorker.ready.then((reg) => {
  reg.pushManager.getSubscription().then((subscription) => {
    subscription
      .unsubscribe()
      .then((successful) => {
        // You've successfully unsubscribed
      })
      .catch((e) => {
        // Unsubscribing failed
      });
  });
});
```

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

| Specification |
| --- |
| Push API # dom-pushsubscription-unsubscribe |

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

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

See also
--------

* `PushManager.getSubscription`


PushSubscription: endpoint property - Web APIs

PushSubscription: endpoint property
===================================

 The **`endpoint`** read-only property of the
 `PushSubscription` interface returns a string containing
 the endpoint associated with the push subscription.

 The endpoint takes the form of a custom URL pointing to a push server, which can be
 used to send a push message to the particular service worker instance that subscribed to
 the push service. For this reason, it is a good idea to keep your endpoint a secret, so
 others do not hijack it and abuse the push functionality.

Value
-----

A string.

Examples
--------

```js
navigator.serviceWorker.ready.then((reg) => {
  reg.pushManager.subscribe({ userVisibleOnly: true }).then((subscription) => {
    console.log(subscription.endpoint);

    // At this point you would most likely send the subscription
    // endpoint to your server, save it, then use it to send a
    // push message at a later date
  });
});
```

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

| Specification |
| --- |
| Push API # dom-pushsubscription-endpoint |

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

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


PushSubscription: options property - Web APIs

PushSubscription: options property
==================================

 The **`options`** read-only property
 of the `PushSubscription` interface is an object containing the options
 used to create the subscription.

Value
-----

An read-only `PushSubscriptionOptions` object containing the following values:

`userVisibleOnly`

 A boolean, indicating that the returned push
 subscription will only be used for messages whose effect is made visible to the user.

`applicationServerKey`

 A public key your push server will use to send
 messages to client apps via a push server. This value is part of a signing key pair
 generated by your application server, and usable with elliptic curve digital signature
 (ECDSA), over the P-256 curve.

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

| Specification |
| --- |
| Push API # dom-pushsubscription-options |

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

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


PushSubscription: expirationTime property - Web APIs

PushSubscription: expirationTime property
=========================================

 The **`expirationTime`** read-only property of the
 `PushSubscription` interface returns a `DOMHighResTimeStamp`
 of the subscription expiration time associated with the push subscription, if there is
 one, or `null` otherwise.

Value
-----

A `DOMHighResTimeStamp` or `null`.

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

| Specification |
| --- |
| Push API # dom-pushsubscription-expirationtime |

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

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


PushSubscription: subscriptionId property - Web APIs

PushSubscription: subscriptionId property
=========================================

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

 The **`subscriptionId`** read-only property of the
 `PushSubscription` interface returns a string containing
 the subscription ID associated with the push subscription.

**Warning:** Instead of this feature, use the `PushSubscription.endpoint` property on the same interface.

Value
-----

A string.

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

This feature was removed from the Push API specification. It is no longer on track to become a standard.

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

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


PerformanceServerTiming: name property - Web APIs

PerformanceServerTiming: name property
======================================

 The **`name`** read-only property returns a
 string value of the server-specified metric name.

Value
-----

A string.

Examples
--------

### Logging server timing entries

Server timing metrics require the server to send the `Server-Timing` header. For example:

```http
Server-Timing: cache;desc="Cache Read";dur=23.2
```

The `serverTiming` entries can live on `navigation` and `resource` entries.

Example using a `PerformanceObserver`, which notifies of new `navigation` and `resource` 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) => {
    entry.serverTiming.forEach((serverEntry) => {
      console.log(
        `${serverEntry.name} (${serverEntry.description}) duration: ${serverEntry.duration}`,
      );
      // Logs "cache (Cache Read) duration: 23.2"
    });
  });
});

["navigation", "resource"].forEach((type) =>
  observer.observe({ type, buffered: true }),
);
```

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

```js
for (const entryType of ["navigation", "resource"]) {
  for (const { name: url, serverTiming } of performance.getEntriesByType(
    entryType,
  )) {
    if (serverTiming) {
      for (const { name, description, duration } of serverTiming) {
        console.log(`${name} (${description}) duration: ${duration}`);
        // Logs "cache (Cache Read) duration: 23.2"
      }
    }
  }
}
```

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

| Specification |
| --- |
| Server Timing # dom-performanceservertiming-name |

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

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

See also
--------

* `PerformanceServerTiming`
* `Server-Timing`


PerformanceServerTiming: duration property - Web APIs

PerformanceServerTiming: duration property
==========================================

The **`duration`** read-only property returns a double that contains the server-specified metric duration, or the value `0.0`.

Value
-----

A number.

Examples
--------

### Logging server timing entries

Server timing metrics require the server to send the `Server-Timing` header. For example:

```http
Server-Timing: cache;desc="Cache Read";dur=23.2
```

The `serverTiming` entries can live on `navigation` and `resource` entries.

Example using a `PerformanceObserver`, which notifies of new `navigation` and `resource` 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) => {
    entry.serverTiming.forEach((serverEntry) => {
      console.log(
        `${serverEntry.name} (${serverEntry.description}) duration: ${serverEntry.duration}`,
      );
      // Logs "cache (Cache Read) duration: 23.2"
    });
  });
});

["navigation", "resource"].forEach((type) =>
  observer.observe({ type, buffered: true }),
);
```

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

```js
for (const entryType of ["navigation", "resource"]) {
  for (const { name: url, serverTiming } of performance.getEntriesByType(
    entryType,
  )) {
    if (serverTiming) {
      for (const { name, description, duration } of serverTiming) {
        console.log(`${name} (${description}) duration: ${duration}`);
        // Logs "cache (Cache Read) duration: 23.2"
      }
    }
  }
}
```

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

| Specification |
| --- |
| Server Timing # dom-performanceservertiming-duration |

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

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

See also
--------

* `PerformanceServerTiming`
* `Server-Timing`


PerformanceServerTiming: description property - Web APIs

PerformanceServerTiming: description property
=============================================

 The **`description`** read-only property returns a
 string value of the server-specified metric description, or an empty
 string.

Value
-----

A string.

Examples
--------

### Logging server timing entries

Server timing metrics require the server to send the `Server-Timing` header. For example:

```http
Server-Timing: cache;desc="Cache Read";dur=23.2
```

The `serverTiming` entries can live on `navigation` and `resource` entries.

Example using a `PerformanceObserver`, which notifies of new `navigation` and `resource` 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) => {
    entry.serverTiming.forEach((serverEntry) => {
      console.log(
        `${serverEntry.name} (${serverEntry.description}) duration: ${serverEntry.duration}`,
      );
      // Logs "cache (Cache Read) duration: 23.2"
    });
  });
});

["navigation", "resource"].forEach((type) =>
  observer.observe({ type, buffered: true }),
);
```

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

```js
for (const entryType of ["navigation", "resource"]) {
  for (const { name: url, serverTiming } of performance.getEntriesByType(
    entryType,
  )) {
    if (serverTiming) {
      for (const { name, description, duration } of serverTiming) {
        console.log(`${name} (${description}) duration: ${duration}`);
        // Logs "cache (Cache Read) duration: 23.2"
      }
    }
  }
}
```

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

| Specification |
| --- |
| Server Timing # dom-performanceservertiming-description |

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

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

See also
--------

* `PerformanceServerTiming`
* `Server-Timing`


PerformanceServerTiming: toJSON() method - Web APIs

PerformanceServerTiming: toJSON() method
========================================

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

Syntax
------

```js
toJSON()
```

### Parameters

None.

### Return value

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

Examples
--------

### Logging server timing entries

Server timing metrics require the server to send the `Server-Timing` header. For example:

```http
Server-Timing: cache;desc="Cache Read";dur=23.2
```

The `serverTiming` entries can live on `navigation` and `resource` entries.

Example using a `PerformanceObserver`, which notifies of new `navigation` and `resource` 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) => {
    entry.serverTiming.forEach((serverEntry) => {
      console.log(serverEntry.toJSON());
    });
  });
});

["navigation", "resource"].forEach((type) =>
  observer.observe({ type, buffered: true }),
);
```

This would log a JSON object like so:

```json
{
  "name": "cache",
  "duration": 23.2,
  "description": "Cache Read"
}
```

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

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

| Specification |
| --- |
| Server Timing # dom-performanceservertiming-tojson |

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

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


HTMLOutputElement: labels property - Web APIs

HTMLOutputElement: labels property
==================================

 The **`HTMLOutputElement.labels`** read-only property returns a
 `NodeList` of the `<label>` elements associated with the
 `<output>` element.

Value
-----

 A `NodeList` containing the `<label>` elements associated
 with the `<output>` element.

Examples
--------

### HTML

```html
<label id="label1" for="test">Label 1</label>
<output id="test">Output</output>
<label id="label2" for="test">Label 2</label>
```

### JavaScript

```js
window.addEventListener("DOMContentLoaded", () => {
  const output = document.getElementById("test");
  for (const label of output.labels) {
    console.log(label.textContent); // "Label 1" and "Label 2"
  }
});
```

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

| Specification |
| --- |
| HTML Standard # dom-lfe-labels-dev |

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

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


GPUInternalError: GPUInternalError() constructor - Web APIs

GPUInternalError: GPUInternalError() constructor
================================================

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

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

Syntax
------

```js
new GPUInternalError(message)
```

### Parameters

`message`

A string providing a human-readable message that explains why the error occurred.

Examples
--------

A developer would not manually use the constructor to create a `GPUInternalError` object. The user agent uses this constructor to create an appropriate object when an internal error is surfaced by `GPUDevice.popErrorScope` or the `uncapturederror` event.

See the main `GPUInternalError` page for an example involving a `GPUInternalError` object instance.

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

| Specification |
| --- |
| WebGPU # dom-gpuinternalerror-gpuinternalerror |

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

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

See also
--------

* The WebGPU API
* WebGPU Error Handling best practices


HTMLMediaElement: buffered property - Web APIs

HTMLMediaElement: buffered property
===================================

The **`buffered`** read-only property of `HTMLMediaElement` objects returns a new static normalized `TimeRanges` object that represents the ranges of the media resource, if any, that the user agent has buffered at the moment the `buffered` property is accessed.

Value
-----

A new static normalized TimeRanges object that represents the ranges of the media resource, if any, that the user agent has buffered at the moment the `buffered` property is accessed.

Examples
--------

```js
const obj = document.createElement("video");
console.log(obj.buffered); // TimeRanges { length: 0 }
```

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

| Specification |
| --- |
| HTML Standard # dom-media-buffered-dev |
| Media Source Extensions™ # htmlmediaelement-extensions |

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

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

See also
--------

* `HTMLMediaElement`: Interface used to define the `HTMLMediaElement.buffered` property


HTMLMediaElement: mediaGroup property - Web APIs

HTMLMediaElement: mediaGroup 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 **`HTMLMediaElement.mediaGroup`** property reflects the `mediaGroup` HTML attribute, which indicates the name of the group of elements it belongs to. A group of media elements shares a common `controller`.

Value
-----

A string.

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

In 2016, the whole Media Controller feature was removed from the HTML specification. It is no longer on track to become a standard.

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

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

See also
--------

* `HTMLMediaElement`: Interface used to define the `HTMLMediaElement.mediaGroup` property


HTMLMediaElement: controlsList property - Web APIs

HTMLMediaElement: controlsList property
=======================================

 The **`controlsList`** property of the
 `HTMLMediaElement` interface returns a DOMTokenList that helps the user
 agent select what controls to show on the media element whenever the user agent shows
 its own set of controls. The DOMTokenList takes one or more of three possible values:
 `nodownload`, `nofullscreen`, and `noremoteplayback`.

Value
-----

A `DOMTokenList`.

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

| Specification |
| --- |
| Unknown specification # solution-outline |

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

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

See also
--------

* Chrome HTMLMediaElement controlsList Sample


HTMLMediaElement: abort event - Web APIs

HTMLMediaElement: abort event
=============================

The **`abort`** event is fired when the resource was not fully loaded, but not as the result of an error.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

```js
const video = document.querySelector("video");
const videoSrc = "https://example.org/path/to/video.webm";

video.addEventListener("abort", () => {
  console.log(`Abort loading: ${videoSrc}`);
});

const source = document.createElement("source");
source.setAttribute("src", videoSrc);
source.setAttribute("type", "video/webm");

video.appendChild(source);
```

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

| Specification |
| --- |
| HTML Standard # event-media-abort |
| HTML Standard # handler-onabort |

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

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

See also
--------

* `HTMLAudioElement`
* `HTMLVideoElement`
* `<audio>`
* `<video>`


HTMLMediaElement: preservesPitch property - Web APIs

HTMLMediaElement: preservesPitch property
=========================================

The **`HTMLMediaElement.preservesPitch`** property determines whether or not the browser should adjust the pitch of the audio to compensate for changes to the playback rate made by setting `HTMLMediaElement.playbackRate`.

Value
-----

A boolean value defaulting to `true`.

Examples
--------

### Setting the preservesPitch property

In this example, we have an `<audio>` element, a range control that adjusts the playback rate, and a checkbox that sets `preservesPitch`.

Try playing the audio, then adjusting the playback rate, then enabling and disabling the checkbox.

```html
<audio
 controls
 src="https://mdn.github.io/webaudio-examples/audio-basics/outfoxing.mp3"></audio>

<div>
  <label for="rate">Adjust playback rate:</label>
  <input id="rate" type="range" min="0.25" max="3" step="0.05" value="1" />
</div>

<div>
  <label for="pitch">Preserve pitch:</label>
  <input type="checkbox" id="pitch" name="pitch" checked />
</div>
```

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

```js
const audio = document.querySelector("audio");
document.getElementById("rate").addEventListener("change", (e) => {
  audio.playbackRate = e.target.value;
});
document.getElementById("pitch").addEventListener("change", (e) => {
  audio.preservesPitch = e.target.checked;
});
```

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

| Specification |
| --- |
| HTML Standard # dom-media-preservespitch-dev |

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

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

See also
--------

* `HTMLMediaElement.playbackRate`
* Web Audio playbackRate explained


HTMLMediaElement: remote property - Web APIs

HTMLMediaElement: remote property
=================================

The **`remote`** read-only property of the `HTMLMediaElement` interface returns the `RemotePlayback` object associated with the media element. The `RemotePlayback` object allow the control of remote devices playing the media.

Value
-----

The associated `RemotePlayback` object.

Example
-------

```js
const el = document.createElement("audio");
const remotePlayback = el.remote;

remotePlayback.watchAvailability((availability) => {
  // Do something when the availability changes
});
```

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

| Specification |
| --- |
| Remote Playback API # dom-htmlmediaelement-remote |

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

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


HTMLMediaElement: pause event - Web APIs

HTMLMediaElement: pause event
=============================

The `pause` event is sent when a request to pause an activity is handled and the activity has entered its paused state, most commonly after the media has been paused through a call to the element's `pause()` method.

The event is sent once the `pause()` method returns and after the media element's `paused` property has been changed to `true`.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

These examples add an event listener for the HTMLMediaElement's `pause` event, then post a message when that event handler has reacted to the event firing.

Using `addEventListener()`:

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

video.addEventListener("pause", (event) => {
  console.log(
    "The Boolean paused property is now 'true'. Either the pause() method was called or the autoplay attribute was toggled.",
  );
});
```

Using the `onpause` event handler property:

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

video.onpause = (event) => {
  console.log(
    "The Boolean paused property is now 'true'. Either the pause() method was called or the autoplay attribute was toggled.",
  );
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-pause |
| HTML Standard # handler-onpause |

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

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

Related Events
--------------

* The HTMLMediaElement `playing` event
* The HTMLMediaElement `waiting` event
* The HTMLMediaElement `seeking` event
* The HTMLMediaElement `seeked` event
* The HTMLMediaElement `ended` event
* The HTMLMediaElement `loadedmetadata` event
* The HTMLMediaElement `loadeddata` event
* The HTMLMediaElement `canplay` event
* The HTMLMediaElement `canplaythrough` event
* The HTMLMediaElement `durationchange` event
* The HTMLMediaElement `timeupdate` event
* The HTMLMediaElement `play` event
* The HTMLMediaElement `pause` event
* The HTMLMediaElement `ratechange` event
* The HTMLMediaElement `volumechange` event
* The HTMLMediaElement `suspend` event
* The HTMLMediaElement `emptied` event
* The HTMLMediaElement `stalled` event
See also
--------

* `HTMLAudioElement`
* `HTMLVideoElement`
* `<audio>`
* `<video>`
* `SpeechSynthesisUtterance`


HTMLMediaElement: crossOrigin property - Web APIs

HTMLMediaElement: crossOrigin property
======================================

The **`HTMLMediaElement.crossOrigin`** property is the CORS setting for this media element. See CORS settings attributes for details.

Value
-----

A string of a keyword specifying the CORS mode to use when fetching the resource. Possible values are:

`anonymous` or the empty string (`""`)

Requests sent by the `HTMLMediaElement` will use the `cors` mode and the `same-origin` credentials mode. This means that CORS is enabled and credentials are sent *if* the resource is fetched from the same origin from which the document was loaded.

`use-credentials`

Requests sent by the `HTMLMediaElement` will use the `cors` mode and the `include` credentials mode. All resources requests by the element will use CORS, regardless of what domain the fetch is from.

If the `crossOrigin` property is specified with any other value, it is the same as specifing as the `anonymous`.

If the `crossOrigin` property is not specified, the resource is fetched without CORS (the `no-cors` mode and the `same-origin` credentials mode).

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

| Specification |
| --- |
| HTML Standard # dom-media-crossorigin |

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

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

See also
--------

* `HTMLImageElement.crossOrigin`
* `HTMLLinkElement.crossOrigin`
* `HTMLScriptElement.crossOrigin`


HTMLMediaElement: controls property - Web APIs

HTMLMediaElement: controls property
===================================

 The **`HTMLMediaElement.controls`** property reflects the
 `controls` HTML attribute, which controls whether user
 interface controls for playing the media item will be displayed.

Value
-----

 A boolean value. A value of `true` means controls will be
 displayed.

Examples
--------

```js
const obj = document.createElement("video");
obj.controls = true;
```

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

| Specification |
| --- |
| HTML Standard # dom-media-controls |

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

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

See also
--------

* `HTMLMediaElement`: Interface used to define the `HTMLMediaElement.controls` property


HTMLMediaElement: loop property - Web APIs

HTMLMediaElement: loop property
===============================

The **`HTMLMediaElement.loop`** property reflects the `loop` HTML attribute, which controls whether the media element should start over when it reaches the end.

Value
-----

A boolean value.

Examples
--------

```js
const obj = document.createElement("video");
obj.loop = true; // true
```

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

| Specification |
| --- |
| HTML Standard # dom-media-loop |

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

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

See also
--------

* `HTMLMediaElement`: Interface used to define the `HTMLMediaElement.loop` property


HTMLMediaElement: seekable property - Web APIs

HTMLMediaElement: seekable property
===================================

The **`seekable`** read-only property of `HTMLMediaElement` objects returns a new static normalized `TimeRanges` object that represents the ranges of the media resource, if any, that the user agent is able to seek to at the time `seekable` property is accessed.

Value
-----

A new static normalized TimeRanges object that represents the ranges of the media resource, if any, that the user agent is able to seek to at the time `seekable` property is accessed.

Examples
--------

```js
const video = document.querySelector("video");
const timeRangesObject = video.seekable;
const timeRanges = [];
//Go through the object and output an array
for (let count = 0; count < timeRangesObject.length; count++) {
  timeRanges.push([timeRangesObject.start(count), timeRangesObject.end(count)]);
}
```

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

| Specification |
| --- |
| HTML Standard # dom-media-seekable-dev |
| Media Source Extensions™ # htmlmediaelement-extensions |

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

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

See also
--------

* `HTMLMediaElement`: Interface used to define the `HTMLMediaElement.seekable` property
* Media Source API
* Media buffering, seeking, and time ranges


HTMLMediaElement: audioTracks property - Web APIs

HTMLMediaElement: audioTracks property
======================================

 The read-only **`audioTracks`**
 property on `HTMLMediaElement` objects returns
 an `AudioTrackList` object listing all of the `AudioTrack`
 objects representing the media element's audio tracks.

 The media element may be
 either an `<audio>` element or a `<video>` element.

 The returned list is *live*; that is, as tracks are added to and removed from
 the media element, the list's contents change dynamically. Once you have a reference to
 the list, you can monitor it for changes to detect when new audio tracks are added or
 existing ones removed. See AudioTrackList events
 to learn more about watching for changes to a media element's track list.

Value
-----

 An `AudioTrackList` object representing the list of audio tracks included
 in the media element. The list of tracks can be accessed using array notation, or using
 the object's `getTrackById()` method.

 Each track is represented by an `AudioTrack` object which provides
 information about the track.

Examples
--------

In this example, all of the audio tracks on a given element are muted.

### HTML

The HTML establishes the element itself.

```html
<video id="video" src="somevideo.mp4"></video>
```

### JavaScript

The JavaScript code handles muting the video element's audio tracks.

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

for (let i = 0; i < video.audioTracks.length; i += 1) {
  video.audioTracks[i].enabled = false;
}
```

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

| Specification |
| --- |
| HTML Standard # dom-media-audiotracks-dev |

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

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

See also
--------

* `HTMLMediaElement`: Interface used to define the `HTMLMediaElement.audioTracks` property
* `<audio>`, `<video>`
* `AudioTrack`, `AudioTrackList`


HTMLMediaElement: playing event - Web APIs

HTMLMediaElement: playing event
===============================

The `playing` event is fired after playback is first started, and whenever it is restarted. For example it is fired when playback resumes after having been paused or delayed due to lack of data.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

These examples add an event listener for the HTMLMediaElement's `playing` event, then post a message when that event handler has reacted to the event firing.

Using `addEventListener()`:

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

video.addEventListener("playing", (event) => {
  console.log("Video is no longer paused");
});
```

Using the `onplaying` event handler property:

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

video.onplaying = (event) => {
  console.log("Video is no longer paused.");
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-playing |
| HTML Standard # handler-onplaying |

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

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

Related Events
--------------

* The HTMLMediaElement `playing` event
* The HTMLMediaElement `waiting` event
* The HTMLMediaElement `seeking` event
* The HTMLMediaElement `seeked` event
* The HTMLMediaElement `ended` event
* The HTMLMediaElement `loadedmetadata` event
* The HTMLMediaElement `loadeddata` event
* The HTMLMediaElement `canplay` event
* The HTMLMediaElement `canplaythrough` event
* The HTMLMediaElement `durationchange` event
* The HTMLMediaElement `timeupdate` event
* The HTMLMediaElement `play` event
* The HTMLMediaElement `pause` event
* The HTMLMediaElement `ratechange` event
* The HTMLMediaElement `volumechange` event
* The HTMLMediaElement `suspend` event
* The HTMLMediaElement `emptied` event
* The HTMLMediaElement `stalled` event
See also
--------

* `HTMLAudioElement`
* `HTMLVideoElement`
* `<audio>`
* `<video>`


HTMLMediaElement: canPlayType() method - Web APIs

HTMLMediaElement: canPlayType() method
======================================

The `HTMLMediaElement` method **`canPlayType()`** reports how likely it is that the current browser will be able to play media of a given MIME type.

Syntax
------

```js
canPlayType(type)
```

### Parameters

`type`

A string specifying the MIME type of the media and (optionally) a `codecs` parameter containing a comma-separated list of the supported codecs.

### Return value

 A string indicating how likely it is that the media can be played.
 The string will be one of the following values:

`""` (empty string)

The media cannot be played on the current device.

`probably`

The media is probably playable on this device.

`maybe`

There is not enough information to determine whether the media can play (until playback is actually attempted).

Examples
--------

```js
let obj = document.createElement("video");
console.log(obj.canPlayType("video/mp4")); // "maybe"
```

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

| Specification |
| --- |
| HTML Standard # dom-navigator-canplaytype-dev |

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

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

See also
--------

* `HTMLMediaElement`: Interface used to define the `HTMLMediaElement.canPlayType()` method
* `MediaCapabilities`
* Handling media support issues in web content
* Media type and format guide
* Codecs in common media types


HTMLMediaElement: fastSeek() method - Web APIs

HTMLMediaElement: fastSeek() method
===================================

 The **`HTMLMediaElement.fastSeek()`** method quickly seeks the
 media to the new time with precision tradeoff.

**Note:** If you need to seek with precision, you should set `HTMLMediaElement.currentTime`
 instead.

Syntax
------

```js
fastSeek(time)
```

### Parameters

`time`

A double.

### Return value

None (`undefined`).

Examples
--------

This example quickly seeks to 20-second position of the video element.

```js
let myVideo = document.getElementById("myVideoElement");

myVideo.fastSeek(20);
```

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

| Specification |
| --- |
| HTML Standard # dom-media-fastseek-dev |

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

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

See also
--------

* HTMLMediaElement.currentTime
 for seeking without precision tradeoff


HTMLMediaElement: load() method - Web APIs

HTMLMediaElement: load() method
===============================

 The `HTMLMediaElement` method
 **`load()`** resets the media element to its initial state and
 begins the process of selecting a media source and loading the media in preparation
 for playback to begin at the beginning.

 The amount of media data that is
 prefetched is determined by the value of the element's `preload` attribute.

 This method is generally only useful when you've made dynamic changes to the set of
 sources available for the media element, either by changing the element's
 `src` attribute or by adding or removing
 `<source>` elements nested within the media element itself.
 `load()` will reset the element and rescan the available sources, thereby
 causing the changes to take effect.

Syntax
------

```js
load()
```

### Parameters

None.

### Return value

None (`undefined`).

Usage notes
-----------

 Calling `load()` aborts all ongoing operations involving this media element,
 then begins the process of selecting and loading an appropriate media resource given the
 options specified in the `<audio>` or `<video>` element
 and its `src` attribute or child `<source>`
 element(s). This is described in more detail in the
 Video and audio content page.

 The process of aborting any ongoing activities will cause any outstanding
 `Promise`s returned by `play()` being
 fulfilled or rejected as appropriate based on their status before the loading of new
 media can begin. Pending play promises are aborted with an `"AbortError"`
`DOMException`.

 Appropriate events will be sent to the media element itself as the load process
 proceeds:

* If the element is already in the process of loading media, that load process is
 aborted and the **`abort`** event is sent.
* If the element has already been initialized with media, the
 **`emptied`** event is sent.
* If resetting the playback position to the beginning of the media actually changes
 the playback position (that is, it was not already at the beginning), a
 **`timeupdate`** event is sent.
* Once media has been selected and loading is ready to begin, the
 **`loadstart`** event is delivered.
* From this point onward, events are sent just like any media load.
Examples
--------

 This example finds a `<video>` element in the document and resets it by
 calling `load()`.

```js
const mediaElem = document.querySelector("video");
mediaElem.load();
```

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

| Specification |
| --- |
| HTML Standard # dom-media-load-dev |

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

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


HTMLMediaElement: defaultMuted property - Web APIs

HTMLMediaElement: defaultMuted property
=======================================

The **`HTMLMediaElement.defaultMuted`** property reflects the `muted` HTML attribute, which indicates whether the media element's audio output should be muted by default. This property has no dynamic effect. To mute and unmute the audio output, use the `muted` property.

Value
-----

A boolean value. A value of `true` means that the audio output will be muted by default.

Examples
--------

```js
const videoEle = document.createElement("video");
videoEle.defaultMuted = true;
console.log(videoEle.outerHTML); // <video muted=""></video>
```

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

| Specification |
| --- |
| HTML Standard # dom-media-defaultmuted |

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

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

See also
--------

* `HTMLMediaElement`: Interface used to define the `HTMLMediaElement.defaultMuted` property
* `HTMLMediaElement.muted`
* `HTMLMediaElement.volume`


HTMLMediaElement: loadstart event - Web APIs

HTMLMediaElement: loadstart event
=================================

The **`loadstart`** event is fired when the browser has started to load a resource.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

### Live example

#### HTML

```html
<div class="example">
  <button type="button">Load video</button>
  <video controls width="250"></video>

  <div class="event-log">
    <label for="eventLog">Event log:</label>
    <textarea readonly class="event-log-contents" id="eventLog"></textarea>
  </div>
</div>
```

```
.event-log-contents {
  width: 18rem;
  height: 5rem;
  border: 1px solid black;
  margin: 0.2rem;
  padding: 0.2rem;
}

.example {
  display: grid;
  grid-template-areas:
    "button log"
    "video log";
}

button {
  grid-area: button;
  width: 10rem;
  margin: 0.5rem 0;
}

video {
  grid-area: video;
}

.event-log {
  grid-area: log;
}

.event-log > label {
  display: block;
}
```

#### JavaScript

```js
const loadVideo = document.querySelector("button");
const video = document.querySelector("video");
const eventLog = document.querySelector(".event-log-contents");
let source = null;

function handleEvent(event) {
  eventLog.textContent += `${event.type}\n`;
}

video.addEventListener("loadstart", handleEvent);
video.addEventListener("progress", handleEvent);
video.addEventListener("canplay", handleEvent);
video.addEventListener("canplaythrough", handleEvent);

loadVideo.addEventListener("click", () => {
  if (source) {
    document.location.reload();
  } else {
    loadVideo.textContent = "Reset example";
    source = document.createElement("source");
    source.setAttribute(
      "src",
      "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm",
    );
    source.setAttribute("type", "video/webm");

    video.appendChild(source);
  }
});
```

#### Result

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

| Specification |
| --- |
| HTML Standard # event-media-loadstart |
| HTML Standard # handler-onloadstart |

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

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

See also
--------

* `HTMLAudioElement`
* `HTMLVideoElement`
* `<audio>`
* `<video>`


HTMLMediaElement: setMediaKeys() method - Web APIs

HTMLMediaElement: setMediaKeys() method
=======================================

 The **`setMediaKeys()`** method of the
 `HTMLMediaElement` interface returns a `Promise` that resolves
 to the passed `MediaKeys`, which are those used to decrypt media during
 playback.

Syntax
------

```js
setMediaKeys(mediaKeys)
```

### Parameters

`mediaKeys`

 A reference to a `MediaKeys` object that the
 `HTMLMediaElement` can use for decryption of media data during playback.

### Return value

A `Promise` that resolves to the passed instance of `MediaKeys`.

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

| Specification |
| --- |
| Encrypted Media Extensions # dom-htmlmediaelement-setmediakeys |

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

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


HTMLMediaElement: volumechange event - Web APIs

HTMLMediaElement: volumechange event
====================================

The `volumechange` event is fired when either the `volume` attribute or the `muted` attribute has changed.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

These examples add an event listener for the HTMLMediaElement's `volumechange` event, then post a message when that event handler has reacted to the event firing.

Using `addEventListener()`:

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

video.addEventListener("volumechange", (event) => {
  console.log("The volume changed.");
});
```

Using the `onvolumechange` event handler property:

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

video.onvolumechange = (event) => {
  console.log("The volume changed.");
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-volumechange |
| HTML Standard # handler-onvolumechange |

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

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

Related Events
--------------

* The HTMLMediaElement `playing` event
* The HTMLMediaElement `waiting` event
* The HTMLMediaElement `seeking` event
* The HTMLMediaElement `seeked` event
* The HTMLMediaElement `ended` event
* The HTMLMediaElement `loadedmetadata` event
* The HTMLMediaElement `loadeddata` event
* The HTMLMediaElement `canplay` event
* The HTMLMediaElement `canplaythrough` event
* The HTMLMediaElement `durationchange` event
* The HTMLMediaElement `timeupdate` event
* The HTMLMediaElement `play` event
* The HTMLMediaElement `pause` event
* The HTMLMediaElement `ratechange` event
* The HTMLMediaElement `volumechange` event
* The HTMLMediaElement `suspend` event
* The HTMLMediaElement `emptied` event
* The HTMLMediaElement `stalled` event
See also
--------

* `HTMLAudioElement`
* `HTMLVideoElement`
* `<audio>`
* `<video>`


HTMLMediaElement: error property - Web APIs

HTMLMediaElement: error property
================================

 The **`HTMLMediaElement.error`** property is the
 `MediaError` object for the most recent error, or `null` if
 there has not been an error. When an `error` event is received by the
 element, you can determine details about what happened by examining this object.

Value
-----

 A `MediaError` object describing the most recent error to occur on the
 media element or `null` if no errors have occurred.

Examples
--------

 This example establishes a video element and adds an error handler to it; the error
 handler logs the details to console.

```js
const videoElement = document.createElement("video");
videoElement.onerror = () => {
  console.error(
    `Error ${videoElement.error.code}; details: ${videoElement.error.message}`,
  );
};
videoElement.src = "https://example.com/bogusvideo.mp4";
```

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

| Specification |
| --- |
| HTML Standard # dom-media-error-dev |

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

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

See also
--------

* `HTMLMediaElement`: Interface used to define the `HTMLMediaElement.error` property
* `<audio>` and `<video>`


HTMLMediaElement: loadeddata event - Web APIs

HTMLMediaElement: loadeddata event
==================================

The **`loadeddata`** event is fired when the frame at the current playback position of the media has finished loading; often the first frame.

**Note:** This event will not fire in mobile/tablet devices if data-saver is on in browser settings.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

These examples add an event listener for the HTMLMediaElement's `loadeddata` event, then post a message when that event handler has reacted to the event firing.

Using `addEventListener()`:

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

video.addEventListener("loadeddata", (event) => {
  console.log(
    "Yay! The readyState just increased to " +
      "HAVE\_CURRENT\_DATA or greater for the first time.",
  );
});
```

Using the `onloadeddata` event handler property:

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

video.onloadeddata = (event) => {
  console.log(
    "Yay! The readyState just increased to " +
      "HAVE\_CURRENT\_DATA or greater for the first time.",
  );
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-loadeddata |
| HTML Standard # handler-onloadeddata |

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

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

Related Events
--------------

* The HTMLMediaElement `playing` event
* The HTMLMediaElement `waiting` event
* The HTMLMediaElement `seeking` event
* The HTMLMediaElement `seeked` event
* The HTMLMediaElement `ended` event
* The HTMLMediaElement `loadedmetadata` event
* The HTMLMediaElement `loadeddata` event
* The HTMLMediaElement `canplay` event
* The HTMLMediaElement `canplaythrough` event
* The HTMLMediaElement `durationchange` event
* The HTMLMediaElement `timeupdate` event
* The HTMLMediaElement `play` event
* The HTMLMediaElement `pause` event
* The HTMLMediaElement `ratechange` event
* The HTMLMediaElement `volumechange` event
* The HTMLMediaElement `suspend` event
* The HTMLMediaElement `emptied` event
* The HTMLMediaElement `stalled` event
See also
--------

* `HTMLAudioElement`
* `HTMLVideoElement`
* `<audio>`
* `<video>`


HTMLMediaElement: duration property - Web APIs

HTMLMediaElement: duration property
===================================

 The *read-only* `HTMLMediaElement`
 property **`duration`** indicates the length of the element's
 media in seconds.

Value
-----

 A double-precision floating-point value indicating the duration of the media in
 seconds. If no media data is available, the value `NaN` is returned. If the
 element's media doesn't have a known duration—such as for live media streams—the value
 of `duration` is `+Infinity`.

Examples
--------

```js
const obj = document.createElement("video");
console.log(obj.duration); // NaN
```

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

| Specification |
| --- |
| HTML Standard # dom-media-duration-dev |

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

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

See also
--------

* Web media technologies
* `HTMLMediaElement.currentTime`: The current playback position of the
 media
* The `<audio>` and `<video>` elements


HTMLMediaElement: canplaythrough event - Web APIs

HTMLMediaElement: canplaythrough event
======================================

The `canplaythrough` event is fired when the user agent can play the media, and estimates that enough data has been loaded to play the media up to its end without having to stop for further buffering of content.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

These examples add an event listener for the HTMLMediaElement's `canplaythrough` event, then post a message when that event handler has reacted to the event firing.

Using `addEventListener()`:

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

video.addEventListener("canplaythrough", (event) => {
  console.log(
    "I think I can play through the entire video without having to stop to buffer.",
  );
});
```

Using the `oncanplaythrough` event handler property:

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

video.oncanplaythrough = (event) => {
  console.log(
    "I think I can play through the entire video without having to stop to buffer.",
  );
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-canplaythrough |
| HTML Standard # handler-oncanplaythrough |

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

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

Related Events
--------------

* The HTMLMediaElement `playing` event
* The HTMLMediaElement `waiting` event
* The HTMLMediaElement `seeking` event
* The HTMLMediaElement `seeked` event
* The HTMLMediaElement `ended` event
* The HTMLMediaElement `loadedmetadata` event
* The HTMLMediaElement `loadeddata` event
* The HTMLMediaElement `canplay` event
* The HTMLMediaElement `canplaythrough` event
* The HTMLMediaElement `durationchange` event
* The HTMLMediaElement `timeupdate` event
* The HTMLMediaElement `play` event
* The HTMLMediaElement `pause` event
* The HTMLMediaElement `ratechange` event
* The HTMLMediaElement `volumechange` event
* The HTMLMediaElement `suspend` event
* The HTMLMediaElement `emptied` event
* The HTMLMediaElement `stalled` event
See also
--------

* `HTMLAudioElement`
* `HTMLVideoElement`
* `<audio>`
* `<video>`


HTMLMediaElement: play event - Web APIs

HTMLMediaElement: play event
============================

The `play` event is fired when the `paused` property is changed from `true` to `false`, as a result of the `play` method, or the `autoplay` attribute.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

These examples add an event listener for the HTMLMediaElement's `play` event, then post a message when that event handler has reacted to the event firing.

Using `addEventListener()`:

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

video.addEventListener("play", (event) => {
  console.log(
    "The Boolean paused property is now 'false'. Either the play() method was called or the autoplay attribute was toggled.",
  );
});
```

Using the `onplay` event handler property:

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

video.onplay = (event) => {
  console.log(
    "The Boolean paused property is now 'false'. Either the play() method was called or the autoplay attribute was toggled.",
  );
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-play |
| HTML Standard # handler-onplay |

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

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

Related Events
--------------

* The HTMLMediaElement `playing` event
* The HTMLMediaElement `waiting` event
* The HTMLMediaElement `seeking` event
* The HTMLMediaElement `seeked` event
* The HTMLMediaElement `ended` event
* The HTMLMediaElement `loadedmetadata` event
* The HTMLMediaElement `loadeddata` event
* The HTMLMediaElement `canplay` event
* The HTMLMediaElement `canplaythrough` event
* The HTMLMediaElement `durationchange` event
* The HTMLMediaElement `timeupdate` event
* The HTMLMediaElement `play` event
* The HTMLMediaElement `pause` event
* The HTMLMediaElement `ratechange` event
* The HTMLMediaElement `volumechange` event
* The HTMLMediaElement `suspend` event
* The HTMLMediaElement `emptied` event
* The HTMLMediaElement `stalled` event
See also
--------

* `HTMLAudioElement`
* `HTMLVideoElement`
* `<audio>`
* `<video>`


HTMLMediaElement: ratechange event - Web APIs

HTMLMediaElement: ratechange event
==================================

The `ratechange` event is fired when the playback rate has changed.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

These examples add an event listener for the HTMLMediaElement's `ratechange` event, then post a message when that event handler has reacted to the event firing.

Using `addEventListener()`:

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

video.addEventListener("ratechange", (event) => {
  console.log("The playback rate changed.");
});
```

Using the `onratechange` event handler property:

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

video.onratechange = (event) => {
  console.log("The playback rate changed.");
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-ratechange |
| HTML Standard # handler-onratechange |

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

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

Related Events
--------------

* The HTMLMediaElement `playing` event
* The HTMLMediaElement `waiting` event
* The HTMLMediaElement `seeking` event
* The HTMLMediaElement `seeked` event
* The HTMLMediaElement `ended` event
* The HTMLMediaElement `loadedmetadata` event
* The HTMLMediaElement `loadeddata` event
* The HTMLMediaElement `canplay` event
* The HTMLMediaElement `canplaythrough` event
* The HTMLMediaElement `durationchange` event
* The HTMLMediaElement `timeupdate` event
* The HTMLMediaElement `play` event
* The HTMLMediaElement `pause` event
* The HTMLMediaElement `ratechange` event
* The HTMLMediaElement `volumechange` event
* The HTMLMediaElement `suspend` event
* The HTMLMediaElement `emptied` event
* The HTMLMediaElement `stalled` event
See also
--------

* `HTMLAudioElement`
* `HTMLVideoElement`
* `<audio>`
* `<video>`


HTMLMediaElement: seeked event - Web APIs

HTMLMediaElement: seeked event
==============================

The `seeked` event is fired when a seek operation completed, the current playback position has changed, and the Boolean `seeking` attribute is changed to `false`.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

These examples add an event listener for the HTMLMediaElement's `seeked` event, then post a message when that event handler has reacted to the event firing.

Using `addEventListener()`:

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

video.addEventListener("seeked", (event) => {
  console.log("Video found the playback position it was looking for.");
});
```

Using the `onseeked` event handler property:

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

video.onseeked = (event) => {
  console.log("Video found the playback position it was looking for.");
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-seeked |
| HTML Standard # handler-onseeked |

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

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

Related Events
--------------

* The HTMLMediaElement `playing` event
* The HTMLMediaElement `waiting` event
* The HTMLMediaElement `seeking` event
* The HTMLMediaElement `seeked` event
* The HTMLMediaElement `ended` event
* The HTMLMediaElement `loadedmetadata` event
* The HTMLMediaElement `loadeddata` event
* The HTMLMediaElement `canplay` event
* The HTMLMediaElement `canplaythrough` event
* The HTMLMediaElement `durationchange` event
* The HTMLMediaElement `timeupdate` event
* The HTMLMediaElement `play` event
* The HTMLMediaElement `pause` event
* The HTMLMediaElement `ratechange` event
* The HTMLMediaElement `volumechange` event
* The HTMLMediaElement `suspend` event
* The HTMLMediaElement `emptied` event
* The HTMLMediaElement `stalled` event
See also
--------

* `HTMLAudioElement`
* `HTMLVideoElement`
* `<audio>`
* `<video>`


HTMLMediaElement: networkState property - Web APIs

HTMLMediaElement: networkState property
=======================================

 The
 **`HTMLMediaElement.networkState`** property indicates the
 current state of the fetching of media over the network.

Value
-----

An `unsigned short`. Possible values are:

| Constant | Value | Description |
| --- | --- | --- |
| `NETWORK_EMPTY` | 0 | There is no data yet. Also, `readyState` is `HAVE_NOTHING`. |
| `NETWORK_IDLE` | 1 | HTMLMediaElement is active and has selected a resource, but is not using the network. |
| `NETWORK_LOADING` | 2 | The browser is downloading HTMLMediaElement data. |
| `NETWORK_NO_SOURCE` | 3 | No HTMLMediaElement src found. |

Examples
--------

 This example will listen for the audio element to begin playing and then check if it is
 still loading data.

```html
<audio id="example" preload="auto">
  <source src="sound.ogg" type="audio/ogg" />
</audio>
```

```js
const obj = document.getElementById("example");

obj.addEventListener("playing", () => {
  if (obj.networkState === 2) {
    // Still loading…
  }
});
```

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

| Specification |
| --- |
| HTML Standard # dom-media-networkstate-dev |

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

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

See also
--------

* `HTMLMediaElement`: Interface used to define the `HTMLMediaElement.networkState` property


HTMLMediaElement: currentTime property - Web APIs

HTMLMediaElement: currentTime property
======================================

 The `HTMLMediaElement` interface's
 **`currentTime`** property specifies the current playback time
 in seconds.

 Changing the value of `currentTime` seeks the media to
 the new time.

Value
-----

 A double-precision floating-point value indicating the current playback time in
 seconds.

 If the media is not yet playing, the value of `currentTime` indicates the
 time position within the media at which playback will begin once the
 `play()` method is called.

 Setting `currentTime` to a new value seeks the media to the given time, if
 the media is available.

 For media without a known duration—such as media being streamed live—it's possible that
 the browser may not be able to obtain parts of the media that have expired from the
 media buffer. Also, media whose timeline doesn't begin at 0 seconds cannot be seeked to
 a time before its timeline's earliest time.

 The length of the media in seconds can be determined using the
 `duration` property.

Examples
--------

```js
const video = document.createElement("video");
console.log(video.currentTime);
```

Usage notes
-----------

### Reduced time precision

 To offer protection against timing attacks and fingerprinting, browsers may round or
 otherwise adjust the value returned by `currentTime`.

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

| Specification |
| --- |
| HTML Standard # dom-media-currenttime-dev |

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

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

See also
--------

* `HTMLMediaElement`: Interface used to define the `HTMLMediaElement.currentTime` property
* `HTMLMediaElement.fastSeek()`: Another way to set the time
* `HTMLMediaElement.duration`: The duration of the media in seconds


HTMLMediaElement: loadedmetadata event - Web APIs

HTMLMediaElement: loadedmetadata event
======================================

The `loadedmetadata` event is fired when the metadata has been loaded.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

These examples add an event listener for the HTMLMediaElement's `loadedmetadata` event, then post a message when that event handler has reacted to the event firing.

Using `addEventListener()`:

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

video.addEventListener("loadedmetadata", (event) => {
  console.log(
    "The duration and dimensions of the media and tracks are now known.",
  );
});
```

Using the `onloadedmetadata` event handler property:

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

video.onloadedmetadata = (event) => {
  console.log(
    "The duration and dimensions of the media and tracks are now known.",
  );
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-loadedmetadata |
| HTML Standard # handler-onloadedmetadata |

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

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

Related Events
--------------

* The HTMLMediaElement `playing` event
* The HTMLMediaElement `waiting` event
* The HTMLMediaElement `seeking` event
* The HTMLMediaElement `seeked` event
* The HTMLMediaElement `ended` event
* The HTMLMediaElement `loadedmetadata` event
* The HTMLMediaElement `loadeddata` event
* The HTMLMediaElement `canplay` event
* The HTMLMediaElement `canplaythrough` event
* The HTMLMediaElement `durationchange` event
* The HTMLMediaElement `timeupdate` event
* The HTMLMediaElement `play` event
* The HTMLMediaElement `pause` event
* The HTMLMediaElement `ratechange` event
* The HTMLMediaElement `volumechange` event
* The HTMLMediaElement `suspend` event
* The HTMLMediaElement `emptied` event
* The HTMLMediaElement `stalled` event
See also
--------

* `HTMLAudioElement`
* `HTMLVideoElement`
* `<audio>`
* `<video>`


HTMLMediaElement: paused property - Web APIs

HTMLMediaElement: paused property
=================================

 The read-only **`HTMLMediaElement.paused`** property
 tells whether the media element is paused.

Value
-----

 A boolean value. `true` is paused and `false` is not
 paused.

Examples
--------

```js
const obj = document.createElement("video");
console.log(obj.paused); // true
```

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

| Specification |
| --- |
| HTML Standard # dom-media-paused-dev |

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

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

See also
--------

* `HTMLMediaElement`: Interface used to define the `HTMLMediaElement.paused` property


HTMLMediaElement: canplay event - Web APIs

HTMLMediaElement: canplay event
===============================

The `canplay` event is fired when the user agent can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

These examples add an event listener for the HTMLMediaElement's `canplay` event, then post a message when that event handler has reacted to the event firing.

Using `addEventListener()`:

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

video.addEventListener("canplay", (event) => {
  console.log("Video can start, but not sure it will play through.");
});
```

Using the `oncanplay` event handler property:

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

video.oncanplay = (event) => {
  console.log("Video can start, but not sure it will play through.");
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-canplay |
| HTML Standard # handler-oncanplay |

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

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

Related Events
--------------

* The HTMLMediaElement `playing` event
* The HTMLMediaElement `waiting` event
* The HTMLMediaElement `seeking` event
* The HTMLMediaElement `seeked` event
* The HTMLMediaElement `ended` event
* The HTMLMediaElement `loadedmetadata` event
* The HTMLMediaElement `loadeddata` event
* The HTMLMediaElement `canplay` event
* The HTMLMediaElement `canplaythrough` event
* The HTMLMediaElement `durationchange` event
* The HTMLMediaElement `timeupdate` event
* The HTMLMediaElement `play` event
* The HTMLMediaElement `pause` event
* The HTMLMediaElement `ratechange` event
* The HTMLMediaElement `volumechange` event
* The HTMLMediaElement `suspend` event
* The HTMLMediaElement `emptied` event
* The HTMLMediaElement `stalled` event
See also
--------

* `HTMLAudioElement`
* `HTMLVideoElement`
* `<audio>`
* `<video>`


HTMLMediaElement: sinkId property - Web APIs

HTMLMediaElement: sinkId property
=================================

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

The **`HTMLMediaElement.sinkId`** read-only property of the Audio Output Devices API returns a string that is the unique ID of the device to be used for playing audio output.

 This ID should be one of the `MediaDeviceInfo.deviceId` values returned from `MediaDevices.enumerateDevices()`, `id-multimedia`, or `id-communications`.
 If the user agent default device is being used, it returns an empty string.

Value
-----

A string indicating the current audio output device, or the empty string if the default user agent output device is being used.

Security requirements
---------------------

Access to the property is subject to the following constraints:

* The property must be called in a secure context.
Specifications
--------------

| Specification |
| --- |
| Audio Output Devices API # dom-htmlmediaelement-sinkid |

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

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

See also
--------

* `MediaDevices.selectAudioOutput()`
* `HTMLMediaElement.setSinkId()`


HTMLMediaElement: controller property - Web APIs

HTMLMediaElement: controller 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 **`HTMLMediaElement.controller`** property represents the media controller assigned to the element.

Value
-----

A `MediaController` object or `null` if no media controller is assigned to the element. The default is `null`.

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

In 2016, the whole Media Controller feature was removed from the HTML specification. It is no longer on track to become a standard.

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

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


HTMLMediaElement: textTracks property - Web APIs

HTMLMediaElement: textTracks property
=====================================

 The read-only **`textTracks`**
 property on `HTMLMediaElement` objects returns a
 `TextTrackList` object listing all of the `TextTrack`
 objects representing the media element's text tracks, in the same order as in
 the list of text tracks.

 You can detect when tracks are added to and removed from an
 `<audio>` or
 `<video>` element
 using the `addtrack` and `removetrack` events. However, these
 events aren't sent directly to the media element itself. Instead, they're sent to the
 track list object of the `HTMLMediaElement`
 that corresponds to the type of track that was added to the element

 The returned list is *live*; that is, as tracks are added to and removed from
 the media element, the list's contents change dynamically. Once you have a reference to
 the list, you can monitor it for changes to detect when new text tracks are added or
 existing ones removed.

 See TextTrackList events to learn
 more about watching for changes to a media element's track list.

Value
-----

 A `TextTrackList` object representing the list of text tracks included in the media element. The list of tracks can be accessed using `textTracks[n]` to get the n-th text track from the object's list of text tracks, or using the `textTracks`.`getTrackById()`
 method.

 Each track is represented by a `TextTrack` object which provides
 information about the track.

Examples
--------

 We start with a
 `<video>` that has
 several `<track>`
 children

```html
<video controls poster="/images/sample.gif">
  <source src="sample.mp4" type="video/mp4" />
  <source src="sample.ogv" type="video/ogv" />
  <track kind="captions" src="sampleCaptions.vtt" srclang="en" />
  <track kind="descriptions" src="sampleDescriptions.vtt" srclang="en" />
  <track kind="chapters" src="sampleChapters.vtt" srclang="en" />
  <track kind="subtitles" src="sampleSubtitles\_de.vtt" srclang="de" />
  <track kind="subtitles" src="sampleSubtitles\_en.vtt" srclang="en" />
  <track kind="subtitles" src="sampleSubtitles\_ja.vtt" srclang="ja" />
  <track kind="subtitles" src="sampleSubtitles\_oz.vtt" srclang="oz" />
  <track kind="metadata" src="keyStage1.vtt" srclang="en" label="Key Stage 1" />
  <track kind="metadata" src="keyStage2.vtt" srclang="en" label="Key Stage 2" />
  <track kind="metadata" src="keyStage3.vtt" srclang="en" label="Key Stage 3" />
</video>
```

 The `HTMLMediaElement.textTracks` returns a
 `textTracksList` through which we can iterate. Here we print all the properties
 of each English track to the console.

```js
const tracks = document.querySelector("video").textTracks;

for (const track of tracks) {
  if (track.language === "en") {
    console.dir(track);
  }
}
```

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

| Specification |
| --- |
| HTML Standard # dom-media-texttracks-dev |

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

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

See also
--------

* `HTMLMediaElement`: Interface used to define the `HTMLMediaElement.textTracks` property
* `<audio>`, `<video>`
* `AudioTrack`, `AudioTrackList`
* `VideoTrack`, `VideoTrackList`
* `addtrack`,
 `change`,
 `removetrack`: AudioTrackList events
* `addtrack`,
 `change`,
 `removetrack`: VideoTrackList events


HTMLMediaElement: durationchange event - Web APIs

HTMLMediaElement: durationchange event
======================================

The `durationchange` event is fired when the `duration` attribute has been updated.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

These examples add an event listener for the HTMLMediaElement's `durationchange` event, then post a message when that event handler has reacted to the event firing.

Using `addEventListener()`:

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

video.addEventListener("durationchange", (event) => {
  console.log("Not sure why, but the duration of the video has changed.");
});
```

Using the `ondurationchange` event handler property:

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

video.ondurationchange = (event) => {
  console.log("Not sure why, but the duration of the video has changed.");
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-durationchange |
| HTML Standard # handler-ondurationchange |

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

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

Related Events
--------------

* The HTMLMediaElement `playing` event
* The HTMLMediaElement `waiting` event
* The HTMLMediaElement `seeking` event
* The HTMLMediaElement `seeked` event
* The HTMLMediaElement `ended` event
* The HTMLMediaElement `loadedmetadata` event
* The HTMLMediaElement `loadeddata` event
* The HTMLMediaElement `canplay` event
* The HTMLMediaElement `canplaythrough` event
* The HTMLMediaElement `durationchange` event
* The HTMLMediaElement `timeupdate` event
* The HTMLMediaElement `play` event
* The HTMLMediaElement `pause` event
* The HTMLMediaElement `ratechange` event
* The HTMLMediaElement `volumechange` event
* The HTMLMediaElement `suspend` event
* The HTMLMediaElement `emptied` event
* The HTMLMediaElement `stalled` event
See also
--------

* `HTMLAudioElement`
* `HTMLVideoElement`
* `<audio>`
* `<video>`


HTMLMediaElement: progress event - Web APIs

HTMLMediaElement: progress event
================================

The **`progress`** event is fired periodically as the browser loads a resource.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

### Live example

#### HTML

```html
<div class="example">
  <button type="button">Load video</button>
  <video controls width="250"></video>

  <div class="event-log">
    <label for="eventLog">Event log:</label>
    <textarea readonly class="event-log-contents" id="eventLog"></textarea>
  </div>
</div>
```

```
.event-log-contents {
  width: 18rem;
  height: 5rem;
  border: 1px solid black;
  margin: 0.2rem;
  padding: 0.2rem;
}

.example {
  display: grid;
  grid-template-areas:
    "button log"
    "video log";
}

button {
  grid-area: button;
  width: 10rem;
  margin: 0.5rem 0;
}

video {
  grid-area: video;
}

.event-log {
  grid-area: log;
}

.event-log > label {
  display: block;
}
```

#### JavaScript

```js
const loadVideo = document.querySelector("button");
const video = document.querySelector("video");
const eventLog = document.querySelector(".event-log-contents");
let source = null;

function handleEvent(event) {
  eventLog.textContent += `${event.type}\n`;
}

video.addEventListener("loadstart", handleEvent);
video.addEventListener("progress", handleEvent);
video.addEventListener("canplay", handleEvent);
video.addEventListener("canplaythrough", handleEvent);

loadVideo.addEventListener("click", () => {
  if (source) {
    document.location.reload();
  } else {
    loadVideo.textContent = "Reset example";
    source = document.createElement("source");
    source.setAttribute(
      "src",
      "https://mdn.github.io/learning-area/html/multimedia-and-embedding/video-and-audio-content/rabbit320.mp4",
    );
    source.setAttribute("type", "video/mp4");

    video.appendChild(source);
  }
});
```

#### Result

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

| Specification |
| --- |
| HTML Standard # event-media-progress |
| HTML Standard # handler-onprogress |

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

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

See also
--------

* `HTMLAudioElement`
* `HTMLVideoElement`
* `<audio>`
* `<video>`


HTMLMediaElement: suspend event - Web APIs

HTMLMediaElement: suspend event
===============================

The `suspend` event is fired when media data loading has been suspended.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

These examples add an event listener for the HTMLMediaElement's `suspend` event, then post a message when that event handler has reacted to the event firing.

Using `addEventListener()`:

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

video.addEventListener("suspend", (event) => {
  console.log("Data loading has been suspended.");
});
```

Using the `onsuspend` event handler property:

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

video.onsuspend = (event) => {
  console.log("Data loading has been suspended.");
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-suspend |
| HTML Standard # handler-onsuspend |

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

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

Related Events
--------------

* The HTMLMediaElement `playing` event
* The HTMLMediaElement `waiting` event
* The HTMLMediaElement `seeking` event
* The HTMLMediaElement `seeked` event
* The HTMLMediaElement `ended` event
* The HTMLMediaElement `loadedmetadata` event
* The HTMLMediaElement `loadeddata` event
* The HTMLMediaElement `canplay` event
* The HTMLMediaElement `canplaythrough` event
* The HTMLMediaElement `durationchange` event
* The HTMLMediaElement `timeupdate` event
* The HTMLMediaElement `play` event
* The HTMLMediaElement `pause` event
* The HTMLMediaElement `ratechange` event
* The HTMLMediaElement `volumechange` event
* The HTMLMediaElement `suspend` event
* The HTMLMediaElement `emptied` event
* The HTMLMediaElement `stalled` event
See also
--------

* `HTMLAudioElement`
* `HTMLVideoElement`
* `<audio>`
* `<video>`
* Web Audio API


HTMLMediaElement: mediaKeys property - Web APIs

HTMLMediaElement: mediaKeys property
====================================

The read-only **`HTMLMediaElement.mediaKeys`** property returns a `MediaKeys` object, that is a set of keys that the element can use for decryption of media data during playback.

Value
-----

A `MediaKeys` object, or `null` if no key is available.

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

| Specification |
| --- |
| Encrypted Media Extensions # dom-htmlmediaelement-mediakeys |

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

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

See also
--------

* `MediaKeys`


HTMLMediaElement: readyState property - Web APIs

HTMLMediaElement: readyState property
=====================================

 The **`HTMLMediaElement.readyState`** property indicates the
 readiness state of the media.

Value
-----

An `unsigned short`. Possible values are:

| Constant | Value | Description |
| --- | --- | --- |
| `HAVE_NOTHING` | 0 | No information is available about the media resource. |
| `HAVE_METADATA` | 1 |
 Enough of the media resource has been retrieved that the metadata
 attributes are initialized. Seeking will no longer raise an exception.
  |
| `HAVE_CURRENT_DATA` | 2 |
 Data is available for the current playback position, but not enough to
 actually play more than one frame.
  |
| `HAVE_FUTURE_DATA` | 3 |
 Data for the current playback position as well as for at least a little
 bit of time into the future is available (in other words, at least two
 frames of video, for example).
  |
| `HAVE_ENOUGH_DATA` | 4 |
 Enough data is available—and the download rate is high enough—that the
 media can be played through to the end without interruption.
  |

Examples
--------

 This example will listen for audio data to be loaded for the element `example`. It will
 then check if at least the current playback position has been loaded. If it has, the
 audio will play.

```html
<audio id="example" preload="auto">
  <source src="sound.ogg" type="audio/ogg" />
</audio>
```

```js
const obj = document.getElementById("example");

obj.addEventListener("loadeddata", () => {
  if (obj.readyState >= 2) {
    obj.play();
  }
});
```

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

| Specification |
| --- |
| HTML Standard # dom-media-readystate-dev |

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

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

See also
--------

* `HTMLMediaElement`: Interface used to define the `HTMLMediaElement.readyState` property


HTMLMediaElement: error event - Web APIs

HTMLMediaElement: error event
=============================

The **`error`** event is fired when the resource could not be loaded due to an error (for example, a network connectivity problem).

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

```js
const video = document.querySelector("video");
const videoSrc = "https://path/to/video.webm";

video.addEventListener("error", () => {
  console.error(`Error loading: ${videoSrc}`);
});

video.setAttribute("src", videoSrc);
```

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

| Specification |
| --- |
| HTML Standard # event-media-error |
| HTML Standard # handler-window-onmessageerror |

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

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

See also
--------

* `HTMLAudioElement`
* `HTMLVideoElement`
* `<audio>`
* `<video>`


HTMLMediaElement: waiting event - Web APIs

HTMLMediaElement: waiting event
===============================

The `waiting` event is fired when playback has stopped because of a temporary lack of data.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

These examples add an event listener for the HTMLMediaElement's `waiting` event, then post a message when that event handler has reacted to the event firing.

Using `addEventListener()`:

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

video.addEventListener("waiting", (event) => {
  console.log("Video is waiting for more data.");
});
```

Using the `onwaiting` event handler property:

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

video.onwaiting = (event) => {
  console.log("Video is waiting for more data.");
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-waiting |
| HTML Standard # handler-onwaiting |

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

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

Related Events
--------------

* The HTMLMediaElement `playing` event
* The HTMLMediaElement `waiting` event
* The HTMLMediaElement `seeking` event
* The HTMLMediaElement `seeked` event
* The HTMLMediaElement `ended` event
* The HTMLMediaElement `loadedmetadata` event
* The HTMLMediaElement `loadeddata` event
* The HTMLMediaElement `canplay` event
* The HTMLMediaElement `canplaythrough` event
* The HTMLMediaElement `durationchange` event
* The HTMLMediaElement `timeupdate` event
* The HTMLMediaElement `play` event
* The HTMLMediaElement `pause` event
* The HTMLMediaElement `ratechange` event
* The HTMLMediaElement `volumechange` event
* The HTMLMediaElement `suspend` event
* The HTMLMediaElement `emptied` event
* The HTMLMediaElement `stalled` event
See also
--------

* `HTMLAudioElement`
* `HTMLVideoElement`
* `<audio>`
* `<video>`


HTMLMediaElement: src property - Web APIs

HTMLMediaElement: src property
==============================

 The **`HTMLMediaElement.src`** property reflects the value of
 the HTML media element's `src` attribute, which indicates the URL of a media
 resource to use in the element.

**Note:** The best way to know the URL of the media resource currently
 in active use in this element is to look at the value of the
 `currentSrc` attribute, which also takes
 into account selection of a best or preferred media resource from a list provided in
 an `HTMLSourceElement` (which represents a `<source>`
 element).

Value
-----

 A string object containing the URL of a media resource to use in the
 element; this property reflects the value of the HTML element's `src`
 attribute.

Examples
--------

```js
const obj = document.createElement("video");
console.log(obj.src); // ""
```

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

| Specification |
| --- |
| HTML Standard # dom-media-src |

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

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

See also
--------

* `HTMLMediaElement`: Interface used to define the `HTMLMediaElement.src` property


HTMLMediaElement: autoplay property - Web APIs

HTMLMediaElement: autoplay property
===================================

 The **`HTMLMediaElement.autoplay`**
 property reflects the `autoplay` HTML attribute, indicating
 whether playback should automatically begin as soon as enough media is available to do
 so without interruption.

 A media element whose source is a `MediaStream` and whose
 `autoplay` property is `true` will begin playback when it becomes
 active (that is, when `MediaStream.active` becomes `true`).

**Note:** Sites which automatically play audio (or videos with an audio
 track) can be an unpleasant experience for users, so it should be avoided when
 possible. If you must offer autoplay functionality, you should make it opt-in
 (requiring a user to specifically enable it). However, autoplay can be useful when
 creating media elements whose source will be set at a later time, under user control.

 For a much more in-depth look at autoplay, autoplay blocking, and how to respond when
 autoplay is blocked by the user's browser, see our article Autoplay guide for media and Web Audio APIs.

Value
-----

 A boolean value which is `true` if the media element will
 begin playback as soon as enough content has loaded to allow it to do so without
 interruption.

**Note:** Some browsers offer users the ability to override
 `autoplay` in order to prevent disruptive audio or video from playing
 without permission or in the background. Do not rely on `autoplay` actually
 starting playback and instead use `play`
 event.

Examples
--------

```html
<video id="video" controls>
  <source
 src="https://player.vimeo.com/external/250688977.sd.mp4?s=d14b1f1a971dde13c79d6e436b88a6a928dfe26b&profile\_id=165" />
</video>
```

```js
// Disable autoplay (recommended)
// false is the default value
document.querySelector("#video").autoplay = false;
```

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

| Specification |
| --- |
| HTML Standard # dom-media-autoplay |

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

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

See also
--------

* `HTMLMediaElement`: Interface used to define the `HTMLMediaElement.autoplay` property
* `<audio>`, `<video>`