Picture In Picture API

If you are a software engineer, you must have heard of the term "No code is the best code". It simply means that if you can make a feature work without any code, it is a good way of implementing that feature. In my experience, I have tried to push towards features that can be done with just CSS and html rather than using JavaScript as well. One of the most common examples of this is the use of tabs in a web page. You can achieve a tabbed layout with just css and html without any javascript events and handlers. This way you can not only create a feature that uses less code, you are also creating a feature that needs zero to very less maintenance.

In this article, I would like to cover one of these no cost- low maintenance features that is available on Chrome. This feature is called Picture In Picture API.

What is Picture in Picture API?

Picture in Picture api lets a developer create a floating video that can be placed on top of all the other content inside a web page.

Try looking at the demo below

See the Pen Picture In Picture API by Prateek Jadhwani (@prateekjadhwani) on CodePen.

If you click on the button "Request Picture in Picture", you will be able to see the video move from its original location to the bottom right corner of the screen.

I am requesting Picture in Picture with the help of the following code:

document.querySelector('video').requestPictureInPicture();

If you want you can call this code on the scroll event to make something like how news site show their floating videos.

One thing to keep in mind is that I did not write any extra code to achieve this feature. I simply called an api and the browser did it for me.

But What If I Need Customization?

There are a lot of ways you can customize Picture in Picture feature.

Feature Support

You can check if the browser supports Picture in Picture API by using the following code:

if (!document.pictureInPictureElement) {
  // handle errors
}

Listening for events

You can even listen to events triggered by the api. For example, you can listen for when the video enters Picture in Picture mode or when it leaves.

document.querySelector('video')
  .addEventListener('enterpictureinpicture', () => {
    // Do stuff when video enters Picture in Picture
  })

or

document.querySelector('video')
  .addEventListener('leavepictureinpicture', () => {
    // Do stuff when video leaves Picture in Picture
  })

Look and Feel

You can also change the css associated with the video using the :picture-in-picture pseudo class. Although this feature is available in chrome 76 and above.

video:picture-in-picture {
  border: 20px solid blue;
}

Summary

With the above description and code samples, you should be able to see the future aspect of Picture in Picture. If you are from a software / technology company who needs to show product or article videos, this might be a better route as it saves a lot of time in coding and maintenance.

References

comments powered by Disqus