Execute JavaScript function when YouTube video is

2019-09-19 20:55发布

问题:

I'm embedding a youtube video on my page using the following code:

<iframe width="400" height="300" id="newvid" src="http://www.youtube.com/embed/url?modestbranding=1&showinfo=0&feature=player_embedded&fs=0&iv_load_policy=3&rel=0" frameborder="0"></iframe>

I'm trying to use the Youtube API, so a javascript function will be executed once user is playing the video, but the following code doesn't work, as I don't see any alert showing when clicking the video:

<script src="https://www.youtube.com/iframe_api"></script>
<script>
      var player;

      function onYouTubeIframeAPIReady() {
        player = new YT.Player('newvid', {
          events: {
            'onStateChange': function(event) {
              if (event.data == YT.PlayerState.PLAYING) {
                  myFunction();
              }
            }
          }
        });
      }
</script>

<script>
function myFunction() {
    alert("I am an alert box!");
}
</script>  

回答1:

It should be set up with a div container rather than selecting the iFrame. (This may not run correctly in the snippet container, however please try in your code).

<div id="newvid"></div>

<script src="https://www.youtube.com/iframe_api"></script>
<script>
      var player;

      function onYouTubeIframeAPIReady() {
        player = new YT.Player('newvid', {
          height: '300',
          width: '400',
          videoId: 'SwxdBiazu8M', // Example video ID
          events: {
            'onStateChange': function(event) {
              if (event.data == YT.PlayerState.PLAYING) {
                  myFunction();
              }
            }
          }
        });
      }
</script>

<script>
function myFunction() {
    alert("I am an alert box!");
}
</script>



回答2:

Below code demonstrates and executes JS function using enablejsapi in iframe -

<!doctype html>
<html>
<body>
<iframe id="ytplayer" type="text/html" width="640" height="390" src="https://www.youtube.com/embed/YtF6p_w-cSc?autoplay=1&controls=0&enablejsapi=1" frameborder="0"></iframe>

<script>
  // Load 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);

  // Replace the 'ytplayer' element with an <iframe> and
  // YouTube player after the API code downloads.
  var player;
  function onYouTubePlayerAPIReady() {  
    player = new YT.Player('ytplayer', {
      height: '390',
      width: '640',      
      events: {
            'onStateChange': function(event) {
              if (event.data == YT.PlayerState.PLAYING) {
                  myFunction();
              }
            }
          }  
    });           
  }

  function myFunction() {
    alert("I am an alert box!");
}
</script>
</body>
</html>

Here's JSFiddle

As per the above code JS function will be called once the playerstate is PLAYING. Hope this will help you and you are looking for the same. Also, please let me know if you have any questions.

Thanks..!