Sub topic 12
Handling the play() promise
This chapter assumes you can select elements in JavaScript, attach event listeners, and use promises with async/await. It also assumes you know the autoplay rules from the earlier chapter on browser restrictions. Here the focus is on what play() returns and how to react when it fails.
What play() returns
HTMLMediaElement.play() returns a Promise. The promise resolves when playback has started. It rejects when the browser cannot or will not start playback. Before this behavior was standardized, play() returned nothing and failures were silent. Current browsers all return a promise, but older embedded browsers may not. A defensive check costs one line.
Two points about what the promise means:
- It resolves when playback begins, not when the media ends. To react to the end, listen for the
endedevent. - It tells you about the request you just made. It does not track the element's state afterward. If the user pauses a second later, the promise has already resolved.
If you call play() and ignore the promise, a rejection becomes an unhandled promise rejection. The browser reports it in the console as an error such as "Uncaught (in promise) NotAllowedError". The page keeps working, but the video does not play and your code never learns why.
The rejection reasons
The rejection value is a DOMException. Its name property tells you the cause.
| `err.name` | Typical cause | Reasonable response |
|---|---|---|
| `NotAllowedError` | Autoplay policy blocked playback, or the user agent denied permission | Show a play button and wait for a click |
| `NotSupportedError` | No usable source: unsupported format, bad URL, or a failed network request | Show fallback content or a download link |
| `AbortError` | Another action interrupted the request, such as `pause()` or a new `load()` | Usually ignore it |
Branch on err.name, not on the message text. Message text varies between browsers and languages.
Handling the promise in practice
The basic pattern wraps the call in try/catch. The helper below returns a short status string, so callers can decide what to show.
async function tryPlay(media) {
try {
const result = media.play();
if (result !== undefined) {
await result;
}
return 'playing';
} catch (err) {
if (err.name === 'NotAllowedError') return 'blocked';
if (err.name === 'NotSupportedError') return 'unsupported';
if (err.name === 'AbortError') return 'interrupted';
throw err;
}
}The result !== undefined guard covers old browsers that return nothing. The final throw err is deliberate. An unexpected error should not be swallowed, because that hides real bugs.
A fallback for blocked autoplay
When a page tries to start a video on load, the policy often blocks it. The usual fix is to reveal a visible play button. The markup below is one working arrangement.
<video id="hero" src="clip.mp4" playsinline controls></video>
<button id="start" hidden>Play video</button>
<script>
const video = document.querySelector('#hero');
const start = document.querySelector('#start');
async function tryPlay(media) {
try {
const result = media.play();
if (result !== undefined) await result;
return 'playing';
} catch (err) {
if (err.name === 'NotAllowedError') return 'blocked';
if (err.name === 'AbortError') return 'interrupted';
return 'unsupported';
}
}
tryPlay(video).then((status) => {
if (status === 'blocked') {
start.hidden = false;
}
});
start.addEventListener('click', async () => {
const status = await tryPlay(video);
if (status === 'playing') start.hidden = true;
});
</script>The click handler works because a click is a user gesture. Browsers allow play() to succeed when it runs as a direct result of one.
Retrying muted
Browsers are more permissive toward muted playback. If sound is not essential, you can retry once with the audio off.
async function playWithMutedFallback(media) {
try {
await media.play();
return 'playing';
} catch (err) {
if (err.name !== 'NotAllowedError') throw err;
media.muted = true;
try {
await media.play();
return 'playing-muted';
} catch (retryErr) {
if (retryErr.name === 'NotAllowedError') return 'blocked';
throw retryErr;
}
}
}If you start playback muted this way, show the user that the video is muted and give them a way to unmute. Otherwise they may think the audio is broken.
How the pieces fit together
Edge cases
The play() then pause() race
play() is asynchronous. The browser may need time to load data before it starts. If your code calls pause() before the promise settles, the pending promise rejects with AbortError. This is expected, not a failure. It is common in toggle buttons when a user double-clicks.
A simple defense is to remember the pending promise and wait for it before pausing.
const video = document.querySelector('video');
const button = document.querySelector('#toggle');
let pending = null;
button.addEventListener('click', async () => {
if (video.paused) {
pending = video.play();
try {
await pending;
} catch (err) {
if (err.name !== 'AbortError') {
console.error('play() failed:', err.name);
}
}
} else {
if (pending) {
try { await pending; } catch { /* already handled above */ }
}
video.pause();
}
});Changing the source mid-request
Setting src or calling load() while a play() promise is pending also produces AbortError. If you build a playlist, expect this when users skip tracks quickly. Treat it as a signal that a newer request has replaced the old one.
The autoplay attribute has no promise
The autoplay attribute starts playback without any script, so there is no promise to inspect. If the browser blocks it, nothing is reported. To detect blocked playback, either call play() yourself or check video.paused after the loadedmetadata event. A blocked autoplay leaves paused as true.
Resolved does not mean audible or visible
A resolved promise means the element is playing. It does not mean the user can see it or hear it. The element may be muted, the volume may be zero, or the tab may be hidden. Browsers may also pause media in background tabs, which you can observe through the pause event.
Updating the interface from events
Do not rely only on the promise to keep your button label correct. The user can also pause with the built-in controls, a keyboard media key, or system controls. Listen to play and pause events and set the UI from those. The promise is best for handling the failure case of your own request.
Common errors
- Calling
play()with nocatchand noawait, which produces unhandled rejections. - Treating every rejection as an autoplay problem.
NotSupportedErrormeans the source is the problem, and a play button will not fix it. - Logging
err.messageand branching on it instead of branching onerr.name. - Setting the button to "Pause" before the promise resolves, then leaving it wrong when the call fails.
- Assuming the promise resolves when the media finishes.
Exercise
A user clicks a "Play" button, and your handler calls await video.play(). The console shows AbortError. Name one likely cause and say whether you should show an error message to the user.
Show answer
A likely cause is that something interrupted the pending request, for example code called video.pause() or changed src or called load() before playback began, such as from a double-click or a fast track skip. You usually should not show an error. AbortError means a newer action replaced the request, so ignore it and let the newer action decide the state.
Exercise
Write the catch logic that shows a play button on NotAllowedError, shows a download link on NotSupportedError, and rethrows any other error. Why branch on err.name instead of err.message?
Show answer
Example: catch (err) { if (err.name === 'NotAllowedError') { showPlayButton(); } else if (err.name === 'NotSupportedError') { showDownloadLink(); } else { throw err; } }. The name is a standardized identifier, while the message text differs between browsers and languages and can change without notice.