YouTube API - addEventListener not working



我试图跟踪我网站上YouTube视频中的任何事件。为什么这不起作用?HTML:

<div>
     <iframe id="video-block" width="560" height="315" src="//www.youtube.com/embed/123456?enablejsapi=1 " frameborder="0" allowfullscreen ></iframe>
</div>

JS:

    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    function onYouTubeIframeAPIReady( ) {
        alert("1");
        ytplayer = new YT.Player('video-chia');
        ytplayer.addEventListener('onStateChange', function(e) {
            alert('State change');
        });
    }

我以前也这样做过。通过,我实现了略有不同的状态更改

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', {
      videoId: 'M7lc1UVf-VE',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }
  function onPlayerReady(event) {
    event.target.playVideo();
  }
  var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }

相关内容

  • 没有找到相关文章

最新更新