safari 禁止视频自动播放的错误捕捉

最近做页面的时候要加一个自动播放的视频作为背景。很理所当然的我写了如下的代码:

1
<video autoplay loop src="..."></video>

autoplay 表示自动播放。
在ie8以上的浏览器都是可以的,但是在Safari 11 中却出现了报错。

Unhandled Promise Rejection: NotAllowedError (DOM Exception 35): The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

我本来想用try...catch捕捉这个错误,结果捉不到。

在github上找到了一个解决方法:

1
2
3
4
5
6
7
8
9
10
var promise = document.querySelector('video').play();

if (promise !== undefined) {
promise.catch(error => {
// Auto-play was prevented
// Show a UI element to let the user manually start playback
}).then(() => {
// Auto-play started
});
}
0%