简体   繁体   English

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

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

I am currently making a webpage.我目前正在制作一个网页。

In one function I play an audio item.在一个 function 我播放音频项目。 However Chrome is blocking this if the user hasn't interacted with the page so it gave me the usual error message play() failed because the user didn't interact with the document first .但是,如果用户没有与页面交互,Chrome 会阻止这一点,所以它给了我通常的错误消息play() failed because the user didn't interact with the document first In reaction to that I wanted to catch the error message:对此,我想捕获错误消息:

 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>

Somehow Chrome still shows the error message which I don't understand.不知何故,Chrome 仍然显示我不明白的错误消息。 Can someone explain to me how this is even possible?有人可以向我解释这怎么可能?

The .play method returns a Promise , so you can await it to catch the error. .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