The JavaScript Picture-in-Picture (PiP) API is a browser API that allows users to view a video in a small floating window (also known as a “picture-in-picture” window).
At the same time, they continue to interact with the webpage or application.
This can be useful for video conferencing, watching video content while multitasking, or enabling users to watch a video while using other apps or features on their devices.
Demo Video
Check If Browser Supports PiP API
To use the PiP API, you must first check if the current browser supports it. You can do this by checking if the PictureInPictureWindow
object is available:
1 2 3 4 5 6 |
if ('PictureInPictureWindow' in window) { // The PiP API is supported } else { // The PiP API is not supported } |
Implementation of JS PiP API
Once you have determined that the PiP API is supported, you can use the requestPictureInPicture()
method to enter picture-in-picture mode for a video element:
1 2 3 4 5 6 7 8 9 10 |
const videoElement = document.querySelector('video'); videoElement.requestPictureInPicture() .then(pipWindow => { // The video has entered picture-in-picture mode }) .catch(error => { // There was an error entering picture-in-picture mode }); |
To exit picture-in-picture mode, you can use the exitPictureInPicture()
method:
1 2 3 4 5 6 7 8 |
videoElement.exitPictureInPicture() .then(() => { // The video has exited picture-in-picture mode }) .catch(error => { // There was an error exiting picture-in-picture mode }); |
You can also use the pictureInPictureElement
property of the document
object to check if a video element is currently in picture-in-picture mode:
1 2 3 4 5 6 |
if (document.pictureInPictureElement === videoElement) { // The video element is in picture-in-picture mode } else { // The video element is not in picture-in-picture mode } |
Live Example of JavaScript Picture-in-Picture Mode
See the Pen Live Example of JavaScript Picture-in-Picture Mode by Bikash Panda (@phpcodertech) on CodePen.
For more information and a complete list of methods and properties available in the PiP API, you can refer to the MDN documentation and the Web Platform API Reference.
To use the PiP API, you will need to ensure that your browser supports it. Currently, the PiP API is supported by the following browsers:
- Chrome 70 or later
- Firefox 71 or later
- Safari 14 or later
- Microsoft Edge 85 or later
Also, Read:
- Send Mail Attachments with PHP Mail()
- PHP trim() Function With Multiple Examples
- PHP str_replace Function | Complete Guide
One Reply to “JavaScript Picture-in-Picture API (PiP In JS)”