How to fire function on Embedded YouTube iFrame

2019-03-01 13:09发布

问题:

Trying to fire a function at the end of an embedded YouTube iFrame's end. Just need to know how to find the end - after that I am good.

回答1:

Hard to tell from your question, but it sounds like you want to trigger an event when the youtube video is ending. You can setup an event handler using the sample code below.

player = new YT.Player('player', {
  height: '390',
  width: '640',
  videoId: 'someVideoID',
  events: {
    'onStateChange': onPlayerStateChange
  }
});

Most of that is just template code for setting up a new Youtube Player, but the important part is the events, in which you register an event handler to fire for onStateChange, which will run the method onPlayerStateChange.

Then from there you could have a function along these lines:

function onPlayerStateChange(event) {
  if (event.data === 0) {
    doSomeAction();
  }
}

event.data is going to be the action that just occurred, and according to the API docs, the value 0 means that the video has ended. From there you can perform some action, as shown by the doSomeAction(); method.



回答2:

Here is the answer I came up with to use on an IFrame... The jQuery function is one that I wrote for my project - you can switch it out for what you need. To note: your YouTube video has to have "enablejsapi=1" added to the url.

<div class="video-holderYT">
        <iframe width="480" id="ytplayer" height="270" class="videoImageYT" src="http://www.youtube.com/embed/YourVideoIDHere?rel=0&amp;autoplay=0&amp;modestbranding=1&amp;showinfo=0&amp;autohide=1&version=3&enablejsapi=1&playerapiid=ytplayer" frameborder="0" allowfullscreen=""></iframe>
</div>

  <script src="/jquery-1.7.2.min.js"></script>
  <script type="text/javascript">
  var player;
 function onYouTubePlayerAPIReady() {
  player = new YT.Player('ytplayer', {
    events: {
        'onStateChange': ShowMe
       }
    });
 }

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

    function ShowMe() {

    var sStatus;
    sStatus = player.getPlayerState();

      if (sStatus == -1) alert("Video has not started.");
      else if (sStatus == 0) {  $('#ytplayer').replaceWith('<a href="page/" target="_blank"><img class="special_hover" src="image" alt="" /></a>')
   //change above function to react to when the player stops.
  }
     else if (sStatus == 1) { } //Video is playing
     else if (sStatus == 2) {}  //Video is paused
     else if (sStatus == 3) { } //video is buffering 
     else if (sStatus == 5) { } //Video is cued.
   }

  </script>