自 2017 年 4 月起,Android O 版 Google Chrome 支援子母畫面功能。
這可讓使用者在未被其他視窗封鎖的小型重疊視窗中播放 <video>
元素,以便他們邊觀看其他事時觀看。
運作方式如下:開啟 Chrome,前往含有影片的網站,並以全螢幕模式播放。接著按下主螢幕按鈕,即可前往 Android 主畫面,正在播放影片,影片就會自動轉換為子母畫面。這樣就大功告成了!很酷吧?
不過,如果是電腦版呢?如果網站想要控管這項體驗 該怎麼做?
好消息是,子母畫面 Web API 規格正如我們所說的草案,這項規格的目的是向 API 公開下列屬性,藉此允許網站啟動及控制這項行為:
- 影片進入及離開子母畫面模式時通知網站。
- 允許網站透過使用者手勢觸發影片元素的子母畫面。
- 允許網站退出子母畫面。
- 允許網站檢查子母畫面是否能觸發。
看起來會像這樣:
<video id="video" src="https://example.com/file.mp4"></video>
<button id="pipButton"></button>
<script>
// Hide button if Picture-in-Picture is not supported.
pipButton.hidden = !document.pictureInPictureEnabled;
pipButton.addEventListener('click', function() {
// If there is no element in Picture-in-Picture yet, let's request Picture
// In Picture for the video, otherwise leave it.
if (!document.pictureInPictureElement) {
video.requestPictureInPicture()
.catch(error => {
// Video failed to enter Picture-in-Picture mode.
});
} else {
document.exitPictureInPicture()
.catch(error => {
// Video failed to leave Picture-in-Picture mode.
});
}
});
</script>
意見回饋
你覺得呢?請提交意見回饋,並在子母畫面 WICG 存放區中回報問題。我們很期待能聽到您的想法!
禁止 Android 的預設 PIP 行為
您現在可以回應大小調整事件,並偵測視窗大小何時有顯著變化,防止影片在 Chrome 中使用 Android 的預設子母畫面行為 (請參閱以下程式碼)。我們不建議您將其做為永久解決方案,但在實作 Web API 之前,請先提供暫時選項。
// See whether resize is small enough to be PiP. It's a hack, but it'll
// work for now.
window.addEventListener('resize', function() {
if (!document.fullscreenElement) {
return;
}
var minimumScreenSize = 0.33;
var screenArea = screen.width * screen.height;
var windowArea = window.outerHeight * window.outerWidth;
// If the size of the window relative to the screen is less than a third,
// let's assume we're in PiP and exit fullscreen to prevent Auto PiP.
if ((windowArea / screenArea) < minimumScreenSize) {
document.exitFullscreen();
}
});