Youtube video in html (detect if the video was played)

Viewed 624

I would like to detect if a user has played up to 90% of a YouTube video on my website, and then do something with that result. How would I achieve this with JS?

This is the basic setup:

<iframe src={`https://www.youtube.com/embed/${youtubeid}`}></iframe>

Using : https://www.npmjs.com/package/react-youtube

1 Answers

In order to be able to embed a YouTube video so that you can monitor the duration of the video that has been played, you'll want to use youtube's api: https://developers.google.com/youtube/iframe_api_reference

The code below triggers a simple javascript alert when the video reached 90% completion.

After setting things up, we use player.getDuration() to check how long the video is. We take that number times .9 to get the 90% mark and store that variable as videoPlayedTarget.

Next, we set up a function waitForTimer and checkTime, which we use to check youtube's api via player.getCurrentTime(). I've set it up to check every second while the video is playing, but you may want to adjust the interval depending on how sensitive you want it to be.

Once the timer has been reached, an alert is triggered alert("Target reached"), but you can replace that alert with any other javascript you would like to execute when the trigger is reached.

<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');

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

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: '10GyNomO-Q0',
      playerVars: {
        'playsinline': 1
      },
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  var videoPlayedTarget;
  function onPlayerReady(event) {
    // get duration (in seconds) of the video
    // divide by .9 to get 90% completion rate
    videoPlayedTarget = player.getDuration() * .9;
    event.target.playVideo();
  }

  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      // start waiting for timer to hit target
      waitForTimer();
    }
  }

  var done = false;
  function waitForTimer() {
    setInterval(checkTime, 1000);
  }

  function checkTime() {
    if( !done && player.getCurrentTime() > videoPlayedTarget) {
      alert("Target reached");
      done = true;
    }
  }

</script>
</body>
</html>

Related