Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine type of leaving picture in picture mode?

Picture in picture vide mode has two leaving actions "Close" and "Back to tab"

img

Both of them produce leavepictureinpicture event.

Is there any way how to determine what button was triggered this event?

Event bodies seems to be totally same. But from user point of view I would expect close player when I press "close" and back video when I press "Back to tab"

like image 523
gotbahn Avatar asked Nov 24 '25 19:11

gotbahn


1 Answers

The difference between both buttons is that the "close" button will pause the video, while the "Back to tab" one will continue the playback.

This is handled by the browser, so you don't really have to detect which button has been clicked, the default behavior should be fine.
But if you really wish to know this, then you can check if at the moment the event fires the video was playing, then wait just an event loop iteration to let the browser pause the video, then check if it is now paused.

if(document.pictureInPictureEnabled) {
  btn.onclick = e => {
    vid.requestPictureInPicture()
  };
  vid.onleavepictureinpicture = e => {
    const was_playing = !vid.paused;
    setTimeout(() => {
      if( !vid.paused ) {
        console.log("came Back to Tab");
      }
      else if( was_playing ) {
        console.log("clicked the close button");
      }
      else {
        console.log("was already paused, no way to know");
      }
    }, 0 );
  };
}
else document.body.textContent = "your browser doesn't support the Picture in Picture API";
<button id="btn">
enter PIP
</button>
<video src="https://storage.googleapis.com/media-session/caminandes/short.mp4" controls id="vid" muted></video>

However, if the video was paused before they got "Back to tab", then you apparently have no way to know where they did click.

like image 129
Kaiido Avatar answered Nov 27 '25 09:11

Kaiido



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!