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)

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

TheCSSPaintingAPIenablesdynamicimagegenerationinCSSusingJavaScript.1.DeveloperscreateaPaintWorkletclasswithapaint()method.2.TheyregisteritviaregisterPaint().3.ThecustompaintfunctionisthenusedinCSSpropertieslikebackground-image.Thisallowsfordynamicvis

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.
