打开控制台,偶尔会看到该报错导致无法播放,“Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.”, 有时候刷新后又是正常的。查阅文档发现这是Chrome的自动播放策略改变了。

如下文档叙述: Chrome's autoplay policies are simple:

  1. Muted autoplay is always allowed.
  2. Autoplay with sound is allowed if: User has interacted with the domain (click, tap, etc.).
  3. On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously play video with sound.
  4. On mobile, the user has added the site to his or her home screen.
  5. Top frames can delegate autoplay permission to their iframes to allow autoplay with sound.

我这里的处理方式是设置video元素的muted属性为true, 也就是静音,然后在整个video的父级div元素上面添加鼠标mouseover事件,一旦触发了mouseover事件,就把muted设为false,取消静音,目前看这个方案是可行的,没有报错再发生。

参考文档:

1.https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

2.https://stackoverflow.com/questions/49930680/how-to-handle-uncaught-in-promise-domexception-play-failed-because-the-use