Mr.Ra
Mr.Ra

Reputation: 31

How to create fullscreen youtube embeded video clicking youtube's ytp-large-play-button class?

I want to play fullscreen video automatically when users click the ytp-large-play-button class's svg or embeded youtube video. How can i do that in jquery? i don't want to click 'fullscreen'. sorry for my english.

Upvotes: 0

Views: 1248

Answers (1)

Neil
Neil

Reputation: 14321

Browser designers, like Google, Mozilla, etc., have become increasingly paranoid when it comes to security, which makes sense; however, it forces me to engage in creative programming to get things to work how they should.

There are two major security issues you are overlooking:

  1. YouTube embeds (which it's technically an iframe not an embed tag) don't support cross-origin. Meaning I cannot, baring hacking your webbrowser, create a click event inside an their iFrame.
  2. Full-screen must be triggered by a trusted event. A trusted event has to be initiated by the user, like click.

We can get around both of these restrictions by creating an overlapping div (#wrapper) that is completely transparent and sits on top of the player (iframe#ytplayer). We can listen to the click event on the overlapping div and then request full-screen from the (trusted) click event. We can also play the video by using YouTube's API.

Working codepen: https://codepen.io/anon/pen/dmGgmx

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.youtube.com/player_api"></script>
<div class="container">
  <div id="wrapper"></div>
  <div id="ytplayer"></div>
</div>

CSS

.container {
  position:relative;
  overflow:hidden;
  display:inline-block;
}

#wrapper {
  z-index:1;
  cursor:pointer;
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100%;
}

JavaScript:

var player;
function onYouTubePlayerAPIReady() {
  player = new YT.Player('ytplayer', {
    height: '360',
    width: '640',
    videoId: 'M7lc1UVf-VE',
    events: {
      'onReady': onReady
    }
  });
}

function onReady() {
  $("#wrapper").click(function () {
    var iframe = $("#ytplayer")[0];
    player.playVideo();
    $(this).remove();
    var requestFullScreen = iframe.requestFullScreen || iframe.mozRequestFullScreen || iframe.webkitRequestFullScreen;
    if (requestFullScreen) {
      requestFullScreen.bind(iframe)();
    }
  });
}

Upvotes: 1

Related Questions