最近在做線上教育的前端項(xiàng)目,遇到了用iframe加載帶有media(mp3、mp4)文件的課件無(wú)法自動(dòng)播放的問(wèn)題,特此記錄一下解決的方案。針對(duì)的是Chrome瀏覽器。
首先明確無(wú)法自動(dòng)播放是瀏覽器策略限制,貼出chrome的原文
Chrome's autoplay policies are simple:
1 、Muted autoplay is always allowed. 靜音的能自動(dòng)播放
2、 Autoplay with sound is allowed if: 帶聲音自動(dòng)播放(以下滿足其一即可)
* User has interacted with the domain (click, tap, etc.).要有交互動(dòng)作
* On desktop, the user's [Media Engagement Index] threshold has been crossed, meaning the user has previously played video with sound. (類(lèi)似于有各種條件算積分,積分夠了就能自動(dòng)播放,chrome://media-engagement/ 這個(gè)可以看分?jǐn)?shù))
3、The user has [added the site to their home screen]) on mobile or [installed the PWA] on desktop. 用戶(hù)在移動(dòng)端添加到主屏幕或者在桌面安裝了PWA應(yīng)用
4、Top frames can [delegate autoplay permission] to their iframes to allow autoplay with sound.(頂級(jí)frame可以授權(quán)給iframe加載的內(nèi)容)
iframe主要是利用的第4點(diǎn)
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、主頁(yè)面有用戶(hù)interaction,iframe標(biāo)簽添加屬性allow="autoplay",這樣主頁(yè)面可以授權(quán)給iframe引用的內(nèi)容,就可以自動(dòng)播放。
單頁(yè)面應(yīng)用只需要這個(gè)瀏覽器tab頁(yè)簽有交互即可,授權(quán)可以一直存在,但是刷新瀏覽器后授權(quán)需要重新獲取,這個(gè)對(duì)于線上教育項(xiàng)目不是一個(gè)太好的方案,但勝在簡(jiǎn)單。
2、主頁(yè)面與iframe加載資源同域名。
這個(gè)需要部署得當(dāng),稍顯麻煩,但是效果最好。