Picture-in-Picture API
The Picture-in-Picture (PiP) API is a web API that allows developers to create a floating, always-on-top video window, separate from the main browser window. This is especially useful for enhancing user experience on media-heavy websites like video streaming platforms, video conferencing apps, or tutorials.
🧠 What is Picture-in-Picture?
Picture-in-Picture is a browser feature that allows users to continue watching a video in a small overlay window while interacting with other content. This window remains visible above other windows and can be repositioned by the user.
For example, YouTube and Google Meet both utilize PiP so users can multitask while still seeing the video feed.
🛠️ How to Use the PiP API
Here’s a step-by-step guide to implementing PiP on an HTML5 video element.
1. Basic HTML
<video id="video" controls>
<source src="sample.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<button id="pipButton">Toggle PiP</button>
2. JavaScript to Toggle PiP
const video = document.getElementById('video');
const button = document.getElementById('pipButton');
button.addEventListener('click', async () => {
try {
if (document.pictureInPictureElement) {
await document.exitPictureInPicture();
} else {
// Ensure video is playing first
if (video !== document.pictureInPictureElement) {
await video.requestPictureInPicture();
}
}
} catch (error) {
console.error('PiP toggle failed:', error);
}
});
Use event listeners to react to PiP changes:
video.addEventListener('enterpictureinpicture', () => {
console.log('Entered Picture-in-Picture');
});
video.addEventListener('leavepictureinpicture', () => {
console.log('Exited Picture-in-Picture');
});