iframe加載多媒體內(nèi)容自動(dòng)播放受瀏覽器限制

最近在做線上教育的前端項(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),稍顯麻煩,但是效果最好。

這里不討論Chrome企業(yè)版,企業(yè)版另有規(guī)則

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容