An Introduction to the Picture-in-Picture Web API

In 2016, Safari browser was released with macOS Sierra, introducing the picture-in-picture feature for the first time. This feature allows the user to pop up the video into a small floating window that is always on top of other windows, allowing the user to continue watching the video while performing other operations. This idea originates from television, for example, users may want to continue watching popular sports events while browsing program lists or other channels.
Not long after, Android 8.0 was released, supporting the picture-in-picture function through a native API. Although this feature is not yet supported on the Chrome desktop version, Chrome on Android can play videos in picture-in-picture mode through this API.
This prompted the development of a standard Picture-in-Picture Web API, enabling the website to initiate and control this behavior.
At the time of writing, only Chrome (version 70 and above) and Edge (version 76 and above) support this feature. Firefox, Safari, and Opera all use proprietary APIs to implement their capabilities.
This browser supports data from Caniuse, which contains more details. The number indicates that the browser supports this feature in this and later versions.
Desktop
Mobile/tablet
How to use the picture-in-picture API
Let's start by adding videos to the web page.
<video controls="" src="video.mp4"></video>
In Chrome, there are already toggle buttons for entering and exiting Picture-in-Picture mode.
To test Firefox implementation, you need to first enable the media.videocontrols.picture-in-picture.enabled flag in about:config and then right-click on the video to find the picture-in-picture option.
While this works, in many cases you want your video controls to be consistent across browsers and you may want to control which videos can go into picture-in-picture mode and which videos can't.
We can use the Picture-in-Picture Web API to replace the default method in the browser to enter Picture-in-Picture mode with our own methods. For example, let's add a button and click it to enable it:
<button id="pipButton" class="hidden" disabled>Enter picture-in-picture mode</button>
Then select the video and button in JavaScript:
const video = document.getElementById('video');
const pipButton = document.getElementById('pipButton');
By default, the button is hidden and disabled because we need to know if the Picture-in-Picture API is supported and enabled in the user's browser before displaying it. This is a progressive form of enhancement that helps avoid corrupted experiences in browsers that do not support this feature.
We can check if the API is supported and enable the button as follows:
if ('pictureInPictureEnabled' in document) {
pipButton.classList.remove('hidden')
pipButton.disabled = false;
}
Enter picture-in-picture mode
Assume that our JavaScript has determined that the browser has enabled picture-in-picture support. When clicking the button with #pipButton, let's call requestPictureInPicture() on the video element. This method returns a promise that, by default, when parsing, places the video in a mini window in the lower right corner of the screen, although the user can move it.
if ('pictureInPictureEnabled' in document) {
pipButton.classList.remove('hidden')
pipButton.disabled = false;
pipButton.addEventListener('click', () => {
video.requestPictureInPicture();
});
}
We cannot keep the above code as is because requestPictureInPicture() returns a promise and if, for example, the video metadata has not loaded or the disablePictureInPicture property is present on the video, the promise may be rejected.
Let's add a catch block to catch this potential error and let the user know what's going on:
pipButton.addEventListener('click', () => {
video
.requestPictureInPicture()
.catch(error => {
// Error handling});
});
Exit picture-in-picture mode
The browser considerately provides a close button in the Picture-in-Picture window, which can be clicked to close the window. However, we can also provide another way to exit the picture-in-picture mode. For example, we can make clicking our #pipButton close any active picture-in-picture window.
pipButton.addEventListener('click', () => {
if (document.pictureInPictureElement) {
document
.exitPictureInPicture()
.catch(error => {
// Error handling})
} else {
// Request Picture in Picture}
});
Another situation where you might want to close the Picture-in-Picture window is when the video enters full screen mode. Chrome already does this automatically without writing any code.
Picture-in-picture events
The browser allows us to detect when a video enters or leaves P-in-Picture mode. Since P-P mode has many ways to enter or exit, it is best to rely on event detection to update media controls.
These events are enterpictureinpicture and leavepictureinpicture, as the name implies, which are fired when the video enters or exits the picture-in-picture mode, respectively.
In our example, we need to update the #pipButton tag based on whether the video is currently in P-P mode.
Here is the code that helps us achieve this:
video.addEventListener('enterpictureinpicture', () => {
pipButton.textContent = 'Exit Picture-in-Picture Mode';
});
video.addEventListener('leavepictureinpicture', () => {
pipButton.textContent = 'Enter Picture-in-Picture Mode';
});
Here is a demonstration:
Customize picture-in-picture window
The browser displays the play/pause button in the Picture-in-Picture window by default unless the video is playing a MediaStream object (generated by a virtual video source, such as a camera, a video recording device, a screen sharing service, or other hardware sources).
You can also add controls to go directly from the Picture-in-Picture window to the previous or next track:
navigator.mediaSession.setActionHandler('previoustrack', () => {
// Go to the previous track});
navigator.mediaSession.setActionHandler('nexttrack', () => {
// Go to the next track});
Show webcam feed in picture-in-picture window
Video conferencing web applications can benefit from placing webcam feeds in picture-in-picture mode when users switch between applications and other browser tabs or windows.
Here is an example:
Disable Picture-in-Picture on Video
If you don't want the video to pop up in the Picture In Picture window, you can add the disabledPictureInPicture property to it, as shown below:
<video controls="" disablepictureinpicture="" src="video.mp4"></video>
Summarize
For now, that's all you need to know about the Picture-in-Picture Web API now! Currently, the API only supports<video></video> element, but it is also intended to extend to other elements.
Although browser support is now jagged, you can still use it as a way to progressively enhance the website video experience.
Further reading
- Picture-in-picture API specifications
- Watch videos using picture-in-picture
- Picture-in-picture example (Google Chrome on GitHub)
The output maintains the original image and its format. The text has been paraphrased and reorganized for improved flow and clarity while retaining the original meaning. Technical terms are kept consistent.
The above is the detailed content of An Introduction to the Picture-in-Picture Web API. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
How to use vw and vh units in CSS
Aug 07, 2025 pm 11:44 PM
vw and vh units achieve responsive design by associating element sizes with viewport width and height; 1vw is equal to 1% of viewport width, and 1vh is equal to 1% of viewport height; commonly used in full screen area, responsive fonts and elastic spacing; 1. Use 100vh or better 100dvh in the full screen area to avoid the influence of the mobile browser address bar; 2. Responsive fonts can be limited with 5vw and combined with clamp (1.5rem, 3vw, 3rem) to limit the minimum and maximum size; 3. Elastic spacing such as width:80vw, margin:5vhauto, padding:2vh3vw, can make the layout adaptable; pay attention to mobile device compatibility, accessibility and fixed width content conflicts, and it is recommended to give priority to using dvh first;
What is the CSS aspect-ratio property and how to use it?
Aug 04, 2025 pm 04:38 PM
Theaspect-ratioCSSpropertydefinesthewidth-to-heightratioofanelement,ensuringconsistentproportionsinresponsivedesigns.1.Itisapplieddirectlytoelementslikeimages,videos,orcontainersusingsyntaxsuchasaspect-ratio:16/9.2.Commonusecasesincludemaintainingres
How to use the CSS :empty pseudo-class?
Aug 05, 2025 am 09:48 AM
The:emptypseudo-classselectselementswithnochildrenorcontent,includingspacesorcomments,soonlytrulyemptyelementslikematchit;1.Itcanhideemptycontainersbyusing:empty{display:none;}tocleanuplayouts;2.Itallowsaddingplaceholderstylingvia::beforeor::after,wh
How to create a vertical line with CSS
Aug 11, 2025 pm 12:49 PM
Use a div with border to quickly create vertical lines, and define styles and heights by setting border-left and height; 2. Use ::before or ::after pseudo-elements to add vertical lines without additional HTML tags, suitable for decorative separation; 3. In Flexbox layout, by setting the width and background color of the divider class, adaptive vertical dividers between elastic containers can be achieved; 4. In CSSGrid, insert vertical lines as independent columns (such as autowidth columns) into grid layout, which is suitable for responsive design; the most appropriate method should be selected according to the specific layout needs to ensure that the structure is simple and easy to maintain.
What are CSS pseudo-classes and how to use them?
Aug 06, 2025 pm 01:06 PM
CSS pseudo-class is a keyword used to define the special state of an element. It can dynamically apply styles based on user interaction or document location; 1.:hover is triggered when the mouse is hovered, such as button:hover changes the button color; 2.:focus takes effect when the element gets focus, improving form accessibility; 3.:nth-child() selects elements by position, supporting odd, even or formulas such as 2n 1; 4.:first-child and :last-child select the first and last child elements respectively; 5.:not() excludes elements that match the specified conditions; 6.:visited and:link set styles based on the link access status, but:visited is restricted by privacy.
How to use the filter property in CSS
Aug 11, 2025 pm 05:29 PM
TheCSSfilterpropertyallowsvisualeffectslikeblur,brightness,andgrayscaletobeapplieddirectlytoHTMLelements.1)Usethesyntaxfilter:filter-function(value)toapplyeffects.2)Combinemultiplefilterswithspaceseparation,e.g.,blur(2px)brightness(70%).3)Commonfunct
How to create a dotted border in CSS
Aug 15, 2025 am 04:56 AM
Use CSS to create dotted borders, just set the border attribute to dotted. For example, "border:3pxdotted#000" can add a 3-pixel-wide black dot border to the element. By adjusting the border-width, the size of the point can be changed. The wider borders produce larger points. You can set dotted borders for a certain side, such as "border-top:2pxdottedred". Dotted borders are suitable for block-level elements such as div and input. They are often used in focus states or editable areas to improve accessibility. Pay attention to color contrast. At the same time, different from dashed's short-line style, dotted presents a circular dot shape. This feature is widely used in all mainstream browsers.
How to create a glassmorphism effect with CSS
Aug 22, 2025 am 07:54 AM
To create a glass mimicry effect of CSS, you need to use backdrop-filter to achieve background blur, set a translucent background such as rgba(255,255,255,0.1), add subtle borders and shadows to enhance the sense of hierarchy, and ensure that there is enough visual content behind the elements; 1. Use backdrop-filter:blur(10px) to blur the background content; 2. Use rgba or hsla to define the transparent background to control the degree of transparency; 3. Add 1pxsolidrgba(255,255,255,0.3) borders and box-shadow to enhance the three-dimensionality; 4. Ensure that the container has rich backgrounds such as pictures or textures to present a blurred penetration effect; 5. It is compatible with old browsers


