Sub topic 8
Why autoplay is restricted
This chapter assumes you know the video element's basic attributes, JavaScript event listeners, and promises with async/await.
The problem autoplay causes
A page that starts playing sound without warning startles users, uses mobile data, and drains batteries. Autoplaying ads made this common, so browsers now block most autoplay. The autoplay attribute is a request, and the browser may refuse it.
What browsers usually allow
Rules differ between browsers and change over time. These patterns are common:
- Muted video may autoplay. Video with sound usually may not.
- Playback is allowed after the user has interacted with the page, for example by clicking or tapping.
- Some browsers also consider the user's history with the site, or whether the tab is visible.
- iOS Safari requires
playsinlinefor inline autoplay. Without it, the video may open full screen.
The pattern that works
Decorative background video is the standard case. Mute it, loop it, and mark it inline:
<video autoplay muted loop playsinline src="background.mp4"></video>Leave out controls only when the video is purely decorative. Anything with meaningful content needs controls, and it needs captions too, which later chapters cover.
Handling a blocked request
The autoplay attribute fails silently. When you call play() from JavaScript, the browser reports a block through the returned promise, which rejects with a NotAllowedError. Catch it and give the user a way to start playback:
const video = document.querySelector('video');
const startButton = document.querySelector('#start');
async function tryAutoplay() {
try {
await video.play();
startButton.hidden = true;
} catch (err) {
if (err.name === 'NotAllowedError') {
startButton.hidden = false;
} else {
console.error('Playback failed:', err.name);
}
}
}
startButton.addEventListener('click', () => video.play());
tryAutoplay();The button's click counts as a user gesture, so the second play() call is allowed.
Common mistakes
- Expecting
autoplayalone to work on a video with sound. It will be blocked in most browsers. - Calling
play()without handling the rejection. This produces an unhandled promise error and leaves the video stopped with no explanation. - Testing only in your own browser. A site you visit often can earn autoplay permission that new visitors lack.
- Muting a video with real content and hoping users notice. Show an unmute control instead.
Exercise
A tutorial video has sound and the page calls video.play() on load. In a fresh browser profile, the video does not start and the console shows a NotAllowedError. What are two valid ways to fix this?
Show answer
Catch the rejected promise and show a play button, whose click handler calls play() again because a click is a user gesture. Alternatively, start the video muted so autoplay is allowed, and provide a control for the user to unmute it.