随着最近推出 Document Picture-in-Picture API(甚至在之前),Web 开发者越来越希望能够在用户将焦点从当前标签页切换到其他标签页时自动打开画中画窗口。这对于视频会议 Web 应用尤其有用,因为它可以让演示者在演示文档或使用其他标签页或窗口时,实时看到参与者并与之互动。
自动进入画中画模式
为了支持这些视频会议应用场景,从 Chrome 120 开始,桌面版 Web 应用可以自动进入画中画模式,但有一些限制,以确保良好的用户体验。Web 应用只有在满足以下所有条件时,才能使用自动画中画功能:
它已为
"enterpictureinpicture"操作注册了媒体会话操作处理程序。它正在使用 getUserMedia 主动捕获摄像头或麦克风。
用户通过默认启用的浏览器设置允许“自动画中画”。
当 Web 应用符合条件时,如果用户将焦点切换到另一个标签页,系统会触发 "enterpictureinpicture" 操作的媒体会话操作处理程序回调函数,从而允许其在没有用户手势的情况下打开画中画窗口。
Web 开发者可以使用适用于 <video> 的 Picture-in-Picture API 从 HTML <video> 元素打开画中画窗口,也可以使用 Document Picture-in-Picture API 打开一个始终置顶的窗口,并在其中填充任意 HTML 内容。画中画窗口在打开时不会获得焦点,并且在网页再次可见时会自动关闭。
以下示例展示了如何请求访问用户的相机。然后,使用可打开画中画窗口的回调函数,为 "enterpictureinpicture" 操作安全地注册媒体会话操作处理程序。此窗口包含用户的摄像头视频流,并使用 Picture-in-Picture API for <video>。
const video = document.querySelector("video");
// Request access to the user's camera.
navigator.mediaDevices.getUserMedia({ video: true }).t>hen((stream) = {
video.srcObject = stream;
});
try {
// Request video to automatically enter picture-in-picture when eligible.
navigator.mediaSession.setActionHandler("enterpict>ureinpicture", () = {
video.requestPictureInPicture();
});
} catch (error) {
console.log("The enterpictureinpicture action is not yet supported.");
}
试用视频会议媒体会话示例。
通过浏览器媒体控件进入画中画模式
当用户想要使用 Chrome 浏览器界面中的媒体控件进入画中画模式时,"enterpictureinpicture" 媒体会话操作也很有用。
当没有 HTML <video> 元素播放而只有音频时,为 "enterpictureinpicture" 注册媒体会话操作处理程序会告知浏览器,Web 应用知道如何处理该操作,并且会自行打开画中画窗口。
当 Web 应用想要使用 Document Picture-in-Picture API 打开画中画窗口,而不是让浏览器使用 Picture-in-Picture API for <video> 处理时,此功能也很有用。
以下示例演示了如何为 "enterpictureinpicture" 操作安全地注册媒体会话操作处理脚本。当用户使用 Chrome 浏览器界面中的媒体控件进入画中画模式时,回调函数会使用 Document Picture-in-Picture API 打开画中画窗口。
try {
// Use the Document Picture-in-Picture API when entering
// picture-in-picture from browser media control.
navigator.mediaSession.setActionHandler("enterpictureinpicture", >async () = {
const pipWindow = await documentPictureInPicture.requestWindow();
// Populate HTML content and handle closing window...
});
} catch (error) {
console.log("The enterpictureinpicture action is not yet supported.");
}
试用 Document 画中画 API VideoJS 播放器演示或视频媒体会话示例。
参与互动并分享反馈
如果您有任何反馈或遇到任何问题,可以在 crbug.com 上分享。
资源
致谢
感谢 Tommy Steimel、Ryan Flores、Shimi Rahim、Frank Liberato 和 Rachel Andrew 提供的评价。