Sub topic 12
Handling the play() promise
This chapter assumes you know basic HTML, how to select elements and attach event listeners in JavaScript, and how promises and async/await work. It also assumes you have read the chapter on why autoplay is restricted.
What play() returns
HTMLMediaElement.play() returns a promise. The promise resolves when playback has started. It rejects when playback cannot start.
Older code called video.play() and ignored the result. That works until a browser blocks playback. A rejected promise that nobody handles produces an "Uncaught (in promise)" error in the console, and your interface can end up out of sync with the real playback state.
Why it rejects
The two rejection causes you will meet most often are:
NotAllowedError: the browser's autoplay policy blocked playback, usually because the user has not interacted with the page yet and the media is not muted.NotSupportedError: the browser cannot play the source, for example an unsupported format or a failed load.
A third case is AbortError. It happens when another load() or pause() call interrupts the pending play(). This is usually harmless, so you should not show an error message for it.
Handling the rejection
Wrap the call in try/catch and branch on the error name. Update your interface only after you know what happened.
const video = document.querySelector('video');
const button = document.querySelector('#toggle');
async function startPlayback() {
try {
await video.play();
button.textContent = 'Pause';
} catch (err) {
if (err.name === 'NotAllowedError') {
button.textContent = 'Play';
console.warn('Autoplay blocked. Waiting for a user click.');
} else if (err.name === 'AbortError') {
// Playback was interrupted by pause() or load(). Nothing to report.
} else {
console.error('Playback failed:', err.name);
}
}
}
button.addEventListener('click', () => {
if (video.paused) {
startPlayback();
} else {
video.pause();
button.textContent = 'Play';
}
});A call to play() inside a click handler counts as a user gesture, so it normally succeeds even when a scripted call on page load would be blocked.
Common errors
- Not catching the promise. Always use
awaitinsidetry/catch, or add.catch(). - Changing the button label before
play()resolves. If the call is rejected, the label says "Pause" while the video is stopped. - Treating every rejection as a failure.
AbortErroris a normal result of quick user actions. - Assuming
play()works on load. Test with a fresh page where the user has not clicked anything.
Exercise
A page calls await video.play() on load, inside try/catch. The catch block receives an error named NotAllowedError. What caused it, and what should the page do?
Show answer
The browser's autoplay policy blocked unmuted playback because the user had not interacted with the page. The page should leave the interface in the "paused" state, show a play button, and call play() again from the click handler. It could also mute the video if silent playback is acceptable.