YouTube API onPlayerReady is Never Getting Called

孤者浪人 提交于 2020-02-07 14:55:48

问题


Follow this tutorial, I have been trying to integrate the YouTube API into my website. Specifically, when a button is pressed I want to play a video hosted on YouTube in fullscreen mode. Unfortunately, I can't even get the code given in that tutorial to work.

I'm using Slim for markup so I added an empty div with the ID of player as the tutorial suggests

.body  
  .player

I then added this javascript at the end of my markup

  $(document).ready(
    function() {
      loadYoutubeAPI();
    });

Which should start the chain of calling these functions

function loadYoutubeAPI() {
    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', {
        height: '390',
        width: '640',
        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();
}

However, the chain of calls stops before onPlayerReady fires and I can't figure out why.


回答1:


From what I can see, it seems as though your issue may be in the player div seems to be of the class player and from what I can see in the tutorial, its looking for an div with player id. so something like the following may work:

.body
    #player

I am not 100% familiar with Slim so you may need to mark this up differently.



来源:https://stackoverflow.com/questions/40163343/youtube-api-onplayerready-is-never-getting-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!