TL;DR
video.play()is a request, and the browser can say no. We'll reproduce the rejection, build a three-step fallback (sound, muted, play button), and write a Playwright test that sees what a first-time visitor sees. Tested on Playwright 1.63.0 with Chromium 153.
What we're building 🎥
A hero video that tries to play with sound, settles for muted playback with a "Tap to unmute" button when the browser refuses, and shows a plain play button if even that fails. Then a test that proves it, without the test harness quietly handing us a user gesture.
You need Node 22, Playwright, and FFmpeg to make a test clip:
npm i -D playwright
ffmpeg -f lavfi -i testsrc2=size=1280x720:rate=30:duration=10 \
-f lavfi -i sine=frequency=440:duration=10 \
-c:v libvpx-vp9 -b:v 1M -c:a libopus clip.webm
💡 Tip: Playwright's bundled Chromium has no H.264 or AAC decoder. Use VP9 and Opus in WebM for test fixtures or your test will fail for the wrong reason.
Serve the folder with any static server on port 8080 (npx serve -l 8080 works).
1. Reproduce the rejection
Start with the naive page. Playback is started by the page itself, with no interaction:
<!-- selfplay.html -->
<!doctype html>
<video id="v" src="clip.webm" playsinline></video>
<script>
const v = document.getElementById('v');
v.muted = new URLSearchParams(location.search).has('muted');
window.result = null;
v.play()
.then(() => { window.result = { ok: true, muted: v.muted }; })
.catch((e) => { window.result = { ok: false, name: e.name, message: e.message }; });
</script>
Load it in headless Chromium and read window.result:
in-page play(), unmuted: {"ok":false,"name":"NotAllowedError","message":"play() failed because the user didn't interact with the document first. https://goo.gl/xX8pDD"}
in-page play(), muted: {"ok":true,"muted":true}
That is the whole policy in two lines. Muted is allowed, audible is not, and the refusal arrives as a rejected promise named NotAllowedError.
2. Know the rules you are coding against
From the Chrome autoplay policy, the MDN autoplay guide, and WebKit's video policies for iOS:
| Situation | What happens |
|---|---|
| Muted video, or no audio track | Allowed to autoplay in Chrome, Safari and Firefox |
| Audible video, no interaction yet |
play() rejects with NotAllowedError
|
| Audible video after a click or tap on the page | Allowed |
| Chrome desktop, site with a high Media Engagement Index | Audible autoplay allowed |
<video autoplay> attribute is blocked |
Nothing fires. No event, no error |
| iOS Safari, unmuting without a gesture | Playback pauses |
iPhone without playsinline
|
Video wants fullscreen; MDN lists playsinline as required for autoplay in Safari |
| Cross-origin iframe | Needs allow="autoplay" from the parent |
Two of these explain most bug reports:
-
"Works on my machine." Chrome's Media Engagement Index counts plays longer than seven seconds with unmuted audio in an active tab, on a video larger than 200x140 px. You have done that on your own site many times. New visitors have not. Check yours at
about://media-engagement. -
The silent attribute. I left an unmuted
<video autoplay>alone for one second and read its state:{"paused":true,"currentTime":0,"error":null}. There is nothing to catch. If your UI needs to know the outcome, callplay()yourself.
3. Write the fallback 🛠️
// autoplay.js
export async function startPlayback(video) {
try {
await video.play(); // 1. ask for sound
return 'playing';
} catch (err) {
if (err.name !== 'NotAllowedError') throw err;
}
video.muted = true;
try {
await video.play(); // 2. settle for silence
return 'playing-muted';
} catch {
return 'blocked'; // 3. wait for a real gesture
}
}
Only NotAllowedError triggers the fallback. A NotSupportedError (bad source, missing codec) is a different problem and muting will not fix it, so we rethrow.
4. Wire the UI to events, not to intent
<!-- hero.html -->
<!doctype html>
<video id="hero" src="clip.webm" playsinline loop></video>
<button id="unmute" hidden>🔊 Tap to unmute</button>
<button id="play" hidden>▶ Play</button>
<script type="module">
import { startPlayback } from './autoplay.js';
const video = document.getElementById('hero');
const unmute = document.getElementById('unmute');
const play = document.getElementById('play');
// UI state follows what the element reports, never what we asked for.
video.addEventListener('playing', () => { document.body.dataset.video = 'playing'; });
video.addEventListener('pause', () => { document.body.dataset.video = 'paused'; });
const outcome = await startPlayback(video);
document.body.dataset.autoplay = outcome;
unmute.hidden = outcome !== 'playing-muted';
play.hidden = outcome !== 'blocked';
// Unmute synchronously inside the click handler so the gesture still counts.
unmute.addEventListener('click', () => { video.muted = false; unmute.hidden = true; });
play.addEventListener('click', () => { video.muted = false; video.play(); play.hidden = true; });
</script>
Things to notice:
- The play/pause icon in a real player should be driven by
playingandpauseevents. Setting "playing" when you callplay()is how you end up with a pause icon over a frozen frame. -
video.muted = falseruns directly in the handler. Don'tawaitanything before it. - We write the outcome to
data-autoplayon<body>. That gives CSS and tests something to read.
5. The test that lies
Here is the obvious Playwright test, and it is wrong:
// naive.mjs
const result = await page.evaluate(async () => {
const v = document.querySelector('video');
try { await v.play(); return 'played, muted=' + v.muted; }
catch (e) { return e.name; }
});
console.log(result);
played, muted=false
Unmuted playback, no rejection, with the same default policy that rejected our inline script in step 1.
⚠️ Note: Code you run through
page.evaluate()behaves as if a user gesture is active. Anyplay()you trigger from the test harness skips the autoplay policy. It can never show you what a cold visitor sees.
6. The test that tells the truth
Let the page start itself, and only observe:
// autoplay.test.mjs
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
const cases = [
{ name: 'cold visitor (default policy)', args: [], expect: 'playing-muted' },
{ name: 'policy disabled', args: ['--autoplay-policy=no-user-gesture-required'], expect: 'playing' },
];
for (const c of cases) {
const browser = await chromium.launch({ args: c.args });
const page = await browser.newPage();
await page.goto('http://localhost:8080/hero.html');
// Observe only. The page started playback by itself.
await page.waitForSelector('body[data-autoplay]');
const outcome = await page.getAttribute('body', 'data-autoplay');
const state = await page.getAttribute('body', 'data-video');
const unmuteVisible = await page.isVisible('#unmute');
console.log(`${c.name}: autoplay=${outcome} video=${state} unmuteButton=${unmuteVisible}`);
assert.equal(outcome, c.expect);
if (outcome === 'playing-muted') {
await page.click('#unmute'); // a real, trusted click
const after = await page.evaluate(() => {
const v = document.getElementById('hero');
return { muted: v.muted, paused: v.paused };
});
console.log(' after click:', JSON.stringify(after));
assert.deepEqual(after, { muted: false, paused: false });
}
await browser.close();
}
console.log('ok');
$ node autoplay.test.mjs
cold visitor (default policy): autoplay=playing-muted video=playing unmuteButton=true
after click: {"muted":false,"paused":false}
policy disabled: autoplay=playing video=playing unmuteButton=false
ok
Reading state through page.evaluate() is fine. Starting playback through it is not. page.click() is the right way to unmute, because it dispatches a trusted input event, the same as a person would.
The --autoplay-policy=no-user-gesture-required flag comes from Chrome's own docs and is handy for the "returning, engaged user" case.
Things to know before you ship
- Don't unmute from a timer. On iOS, WebKit pauses a muted autoplaying video that becomes audible without a gesture.
-
Offscreen video. WebKit only plays
autoplay-attribute videos while visible and pauses them when scrolled away. Don't fight it. Pair muted autoplay with anIntersectionObserverif you need consistent behavior elsewhere. -
navigator.getAutoplayPolicy()returnsallowed,allowed-mutedordisallowed. MDN marks it experimental, and in my Chromium 153 runtypeof navigator.getAutoplayPolicywasundefined. Feature-detect it and keep the promise fallback. -
Web Audio is covered too. An
AudioContextcreated before a gesture startssuspended. Callresume()from a click. - This run was Chromium only. I did not rerun Safari or Firefox for this post. The table above is from their documentation, so test on real devices before you rely on the iOS rows.
What's next
- Add the cold-visitor test to CI and assert your page never ends in a state outside
playing,playing-mutedorblocked. - If your video lives in a cross-origin iframe (embeds, ad slots), read the
Permissions-Policy: autoplaysection of the MDN guide next. That is the next wall you will hit.
Top comments (0)