繁体   English   中英

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

[英]Why does this try catch statement not work?

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

在一个 function 我播放音频项目。 但是,如果用户没有与页面交互,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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM