7

I'd like to use JavaScript to enable PiP on Youtube videos. I am able to do so on html <video>s but it seems impossible to do so on Youtube <iframe>s. Has someone any lead on this?

Harry
  • 321
  • 2
  • 12

4 Answers4

7

Users may be able to right click twice (to bring up the html5 menu) and select Picture in Picture, but it seems to be impossible to trigger it programmatically from outside the iframe due to the same origin policy for iframes. I don't imagine that the &origin= parameter in the iframe URL actually changes the headers sent from youtube, it didn't seem to work in my testing. SecurityError: Blocked a frame with origin from accessing a cross-origin frame

The youtube iframe api gets around this by using postMessage, however there are no messages implemented at the moment to execute video.requestPictureInPicture(). There seems to be a togglePictureInPicture function defined inside the player base.js script but this doesn't seem to be exposed through the message passing API

Mahir Ahmed
  • 71
  • 1
  • 4
3

I always use the next line in the console, on the youtube page:

document.getElementsByTagName('video');

This will show a HTML Collection, open it and right click on the first position of the collection, store it as global variable, this will generate something like temp1. Then you have to write the next line:

temp1.requestPictureInPicture();

And that's it.

  • It would mean a lot to me if you could please elaborate how it can be done programtically from the text editor. This feature could drastically reduce the server load, and improve UX for my project. – Varun Jun 22 '21 at 10:56
3

You cannot enable PiP programatically using Youtube's iframe embed. The only option is to get the URL directly to Google's streaming servers or stream the video data yourself. Either way you need a stream URL to set as the src for a video element, then call video.requestPictureInPicture() on the video.

https://r4---sn-4g5ednls.googlevideo.com/videoplayback?expire=1627319351&ei=15...

Thats what a stream URL for a video hosted by google looks like. A guy name Levi wrote a library to retrieve this URL for a given Youtube video. But the library makes request to his proxy server yt2html.com in order to retrieve this URL.

I go in more detail on the issues with YT PiP in this blog post.

Spankied
  • 1,626
  • 13
  • 21
-4

Here is a test case from the developers: https://beaufortfrancois.github.io/sandbox/media/iframe-video.html with PiP

There are lots of examples in the documentation:

Read more about that topic: https://developers.google.com/youtube/iframe_api_reference
and about PiP-Api:
Picture-in-Picture Web API Spec: https://wicg.github.io/picture-in-picture , https://levelup.gitconnected.com/pip-videos-in-a-floating-window-452e775555fe?gi=21f55e7bf6fa

Codebreaker007
  • 2,911
  • 1
  • 10
  • 22
  • 3
    Thank you but Youtube videos are not native html videos with native controls as in your example. – Harry Mar 27 '20 at 10:32