Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YouTube Player API detect fullscreen exit

So basically there is a button which when clicked opens and play a video in fullscreen. I want to stop the video when user exit fullscreen but can't catch that event.

By now I user this as starting http://codepen.io/bfred-it/pen/GgOvLM

Can someone direct me to a possible solution.

HTML:

<script src="https://www.youtube.com/iframe_api"></script>
<button>play fullscreen</button><br>
<div id="player"></div>

JS:

var player, iframe;
var $ = document.querySelector.bind(document);

// init player
function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    height: '200',
    width: '300',
    videoId: 'dQw4w9WgXcQ',
    events: {
      'onReady': onPlayerReady
    }
  });
}

// when ready, wait for clicks
function onPlayerReady(event) {
  var player = event.target;
  iframe = $('#player');
  setupListener(); 
}

function setupListener (){
$('button').addEventListener('click', playFullscreen);
}

function playFullscreen (){
  player.playVideo();//won't work on mobile

  var requestFullScreen = iframe.requestFullScreen || iframe.mozRequestFullScreen || iframe.webkitRequestFullScreen;
  if (requestFullScreen) {
    requestFullScreen.bind(iframe)();
  }
}
like image 722
Gardelin Avatar asked Apr 10 '17 10:04

Gardelin


1 Answers

You can detect when the browser full screen change and then stop the video

document.addEventListener("fullscreenchange", function() {
  if (!document.fullscreenElement) player.stopVideo();
}, false);

document.addEventListener("msfullscreenchange", function() {
  if (!document.msFullscreenElement) player.stopVideo();
}, false);

document.addEventListener("mozfullscreenchange", function() {
  if (!document.mozFullScreen) player.stopVideo();
}, false);

document.addEventListener("webkitfullscreenchange", function() {
  if (!document.webkitIsFullScreen) player.stopVideo();
}, false);
like image 69
Vladu Ionut Avatar answered Oct 21 '22 18:10

Vladu Ionut