问题描述:
在新版本的谷歌浏览器(Chrome)中javaScript的play()函数无法播放视频了。
提示:”Uncaught (in promise) DOMException: play() failed because the user didn’t interact with the document first.”
字面的大概意思就是用户没有与网页有很好的沟通。
我猜测应该是为了避免视频自动播放给用户带来不好的体验而禁止视频自动播放。
后寻找谷歌开发者文档找到了一些信息:
Autoplay Policy Changes
Chrome’s autoplay policies are simple:
- Muted autoplay is always allowed.
- Autoplay with sound is allowed if:
- User has interacted with the domain (click, tap, etc.).
- On desktop, the user’s Media Engagement Index threshold has been crossed,
meaning the user has previously play video with sound. - On mobile, the user has added the site to his or her home screen.
- Top frames can delegate autoplay permission to their iframes to
allow autoplay with sound.
解决方法
对video标签写muted。即默认对视频进行静音。可以通过点击某个按钮打开音频。这样就有了与用户很好的“沟通”。
<video id="video" muted autoplay> <button id="unmuteButton"></button> <script> unmuteButton.addEventListener('click', function() { video.muted = false; }); </script>
评论区
发表新的留言
您可以留言提出您的疑问或建议。
您的留言得到回复时,会通过您填写的邮箱提醒您。