当我尝试在用户与页面进行交互之前运行Audio.play()时,它将引发错误:
Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first
如何捕获异常,以免乱扔控制台日志?我想尝试以编程方式加载音频并清除错误,但是默认的JavaScript try / catch不能成功应用。
最佳答案
来自this post:
In general, the advice for web authors when calling HTMLMediaElement.play(), is to not assume that calls to play() will always succeed, and to always handle the promise returned by play() being rejected.
因为play()返回一个promise,所以我们可以链接.catch()调用来处理错误:
Audio.play().catch(error => {
// Autoplay was blocked. Do something
})
关于javascript - 如何捕获自动播放的DOMException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64434981/