Rails& Youtube API:加载iframe的问题

时间:2016-02-13 00:46:15

标签: javascript ruby-on-rails iframe youtube

我正在尝试将Youtube Iframe API实现到我的Rails应用中。我试图复制Youtube Iframe API instructions page上的确切示例。

  1. 创建了一个yt_player.js文件:

    $(function() {
    
       alert('this gets called')
    
       // 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() {
        alert('this does not get called')
        player = new YT.Player('player-wrapper', {
          height: '390',
          width: '640',
          videoId: 'M7lc1UVf-VE',
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      }
      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
        event.target.playVideo();
      }
    
      // 5. The API calls this function when the player's state changes.
      //    The function indicates that when playing a video (state=1),
      //    the player should play for six seconds and then stop.
      var done = false;
      function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING && !done) {
          setTimeout(stopVideo, 6000);
          done = true;
        }
      }
      function stopVideo() {
        player.stopVideo();
      }
    });
    
  2. 我的观点:

    <div id="player-wrapper"></div>
    

    我希望这可以工作但是没有加载视频。控制台中没有显示错误。

    我做错了什么?

1 个答案:

答案 0 :(得分:1)

首先,当您在浏览器控制台中办理登机手续时,我非常确定您的window.playerwindow.onYouTubeIframeAPIReadyundefined

原因是youtube iframe api的工作方式,必须全局定义上述变量。

请检查此document

他们说:

  

onYouTubeIframeAPIReady函数将在播放器API代码下载后立即执行。代码的这一部分定义了一个全局变量,player,它指向您正在嵌入的视频播放器,然后该函数构造视频播放器对象。

所以更改将是:(全局定义youtube变量和回调)

// Your current code
window.player = null; // <-- change here
window.onYouTubeIframeAPIReady = function() {  // <-- change here
  alert('this does not get called')
  player = new YT.Player('player-wrapper', {
    height: '390',
    width: '640',
    videoId: 'M7lc1UVf-VE',
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}

window.onPlayerReady = function(event) {  // <-- change here
  event.target.playVideo();
}

window.done = false;  // <-- change here
window.onPlayerStateChange = function(event) {  // <-- change here
  if (event.data == YT.PlayerState.PLAYING && !done) {
    setTimeout(stopVideo, 6000);
    done = true;
  }
}
window.stopVideo = function() {  // <-- change here
  player.stopVideo();
}