最近在做线上教育的前端项目,遇到了用iframe加载带有media(mp3、mp4)文件的课件无法自动播放的问题,特此记录一下解决的方案。针对的是Chrome浏览器。
首先明确无法自动播放是浏览器策略限制,贴出chrome的原文
Chrome's autoplay policies are simple:
1 、Muted autoplay is always allowed. 静音的能自动播放
2、 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 played video with sound. (类似于有各种条件算积分,积分够了就能自动播放,chrome://media-engagement/ 这个可以看分数)
3、The user has [added the site to their home screen]) on mobile or [installed the PWA] on desktop. 用户在移动端添加到主屏幕或者在桌面安装了PWA应用
4、Top frames can [delegate autoplay permission] to their iframes to allow autoplay with sound.(顶级frame可以授权给iframe加载的内容)
iframe主要是利用的第4点
A feature policy allows developers to selectively enable and disable use of various browser features and APIs. Once an origin has received autoplay permission, it can delegate that permission to cross-origin iframes with a new feature policy for autoplay. Note that autoplay is allowed by default on same-origin iframes.
两种方式:
1、主页面有用户interaction,iframe标签添加属性allow="autoplay",这样主页面可以授权给iframe引用的内容,就可以自动播放。
单页面应用只需要这个浏览器tab页签有交互即可,授权可以一直存在,但是刷新浏览器后授权需要重新获取,这个对于线上教育项目不是一个太好的方案,但胜在简单。
2、主页面与iframe加载资源同域名。
这个需要部署得当,稍显麻烦,但是效果最好。