Search code examples
javascriptyoutubeyoutube-apihtml5-video

How can I prevent a user from fast-forwarding/scrubbing/skipping ahead in an embedded YouTube video?


I'd like to present an embedded HTML YouTube video to a user, and prevent them from fast-forwarding or skipping to the end of the video. I can get most of the way there by using YouTube's API to remove the player controls (see code snippet), however on iOS it's still possible to get the video to run in the native player (along with its scrub controls) by pinching-to-zoom. Is there any easy way of doing this?

I should note, I've also tried using a .m4v video as a file instead which gives more options in HTML5, but that's not an ideal solution for me right now (bandwidth and download issues).

var tag = document.createElement('script');

      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '390',
          width: '640',
          videoId: 'KjLYjf4B7xQ',
          events: {
            'onReady': onPlayerReady
          },
         playerVars: {rel: 0, 
                      showinfo: 0, 
                      controls: 0, 
                      disablekb: 1,
                      modestbranding: 1,
                      cc_load_policy: 1,
                      playsinline: 1}
        });
      }

      function onPlayerReady(event) {
        event.target.playVideo();
      }
<div id="player"></div>

(I tried getting this to run as a snippet but there were cross-origin errors.)

Any help is appreciated. Thanks!

Edit: in addition to Mauricio's answer I also had to add a button to start the video, because the user can't click inside the video to start it. Something like this:

  function onPlayerReady(event) {
    event.target.playVideo();

    var playButton = document.getElementById("play-button");
    playButton.addEventListener("click", function() {
       player.playVideo();
    });
  }

And for the button:

<button id="play-button">Play Video</button>

Solution

  • If you need disable the user interactions with the video, you can add a css style to the div that contains the iframe.

    In this case, add the following css style:

    pointer-events: none
    

    So, the CSS would be as follows:

    #player {
      pointer-events: none;
    }