从 2017 年 4 月开始,Android O 版的 Chrome 支持画中画功能。它允许用户在不受其他窗口阻止的小叠加窗口中播放 <video>
元素,以便他们可以在执行其他操作的同时观看。
具体方法如下:打开 Chrome,访问包含视频的网站,然后全屏播放。接着,按主屏幕按钮转到 Android 主屏幕,正在播放的视频将自动转换为画中画模式。就这些了!很酷吧?
是的,但是,桌面平台呢?如果网站想要控制这种体验,该怎么办?
好消息是,正如我们所说,Picture-in-Picture 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 的默认画中画行为
目前,您可以通过响应调整大小事件并检测窗口大小何时发生显著变化来阻止视频在 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();
}
});