为什么这个try-catch语句不起作用



我目前正在制作一个网页。

在一个功能中,我播放一个音频项目。然而,如果用户没有与页面交互,Chrome会阻止它,因此它会给我通常的错误消息play() failed because the user didn't interact with the document first。对此,我想捕捉错误消息:

audio = document.getElementById("audio");
try{
audio.play();
} 
catch(error){
//I am currently doing nothing
}
<audio id="audio" controls>
<source src="https://dl.last.fm/static/1618838835/126178029/27849967d1ce2a81d9bf47d1e8a9eb69e11a012ae93b6113edddcfb91ab488c6/Death+Grips+-+Guillotine.mp3" type="audio/mp3">
</audio>

不知怎么的,Chrome仍然显示错误消息,我不明白。有人能向我解释一下这是怎么可能的吗?

.play方法返回一个Promise,因此您可以await它来捕获错误。

audio = document.getElementById("audio");
(async ()=>{
try{
await audio.play();
} catch(e){
//console.log(e);
}
})();
<audio id="audio" controls>
<source src="https://dl.last.fm/static/1618838835/126178029/27849967d1ce2a81d9bf47d1e8a9eb69e11a012ae93b6113edddcfb91ab488c6/Death+Grips+-+Guillotine.mp3" type="audio/mp3">
</audio>

最新更新