Safari浏览器兼容问题:play()执行报错

613 阅读1分钟

在最近做webrtc项目中,遇到一个很奇怪的问题,在ios设备上的safari浏览器上,运行如下图所示代码会报错:

image.png

报错信息如下:

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

在查阅一番资料后得出原因:

当用户交互和音频播放之间存在异步操作时,就会报这个错误。

最终解决方案:

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
    });
}

相关问题的issues