← 中文资源

简体中文版本

play() 被打断时以 DOMException 拒绝

媒体元素的 play() 返回 promise:自动播放被策略拦截抛 NotAllowedError,播放请求被 pause 或 load 打断抛 AbortError,按 name 分流后其余错误继续上抛,重试逻辑因此有据可依。

阅读英文原文

实现说明

await 标出每个异步边界——没有 fire-and-forget。守卫条件成立时抛出 Error,而不是返回一个假值。 video 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 用到了 document,需要在浏览器环境运行,Node 里直接跑会缺 API。
  • 守卫 !video 成立时借助提前的 throw 直接离开。
  • 每一步打印都带着自己的标签:playback started、play interrupted:、autoplay blocked until user gesture。

常见问题

坏输入有失败路径吗?

校验先行——Error 标记失败(位于 !video),不会先做一半再失败。

「play() 被打断时以 DOMException 拒绝」能在裸 Node.js 里跑吗?

不能——document 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。

核心语句

if (!video) throw new Error('video element missing');
await video.play();
throw error;

代码示例

const video = document.querySelector<HTMLVideoElement>('video');
if (!video) throw new Error('video element missing');

// play() returns a promise: autoplay blocks and interruptions both reject it
try {
  await video.play();
  console.log('playback started');
} catch (error) {
  if (error instanceof DOMException && error.name === 'AbortError') {
    // a pause() or load() call interrupted this request - retry later
    console.log('play interrupted:', error.name);
  } else if (error instanceof DOMException && error.name === 'NotAllowedError') {
    console.log('autoplay blocked until user gesture');
  } else {
    throw error;
  }
}