ReferenceError:YouTube未定义/ YouTube API

时间:2015-11-18 23:29:54

标签: javascript express google-api youtube-api pug

我有以下代码,尝试使用YouTube Data API进行搜索。我使用express generated stack jade

#player

    script.
        // 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() {
            player = new YT.Player('player', {
                height: '345',
                width: '540',
                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();
        }

        function googleApiClientReady() {
            gapi.client.setApiKey('AIzaSyCgOmTzCI4-gkUhL4hOm9R6I9tmUlVqtCw');
            gapi.client.load('youtube', 'v3', function() {
                /**
                * This function searches for videos related to the keyword 'dogs'. The video IDs and titles
                * of the search results are logged to Apps Script's log.
                *
                * Note that this sample limits the results to 25. To return more results, pass
                * additional parameters as documented here:
                *   https://developers.google.com/youtube/v3/docs/search/list
                */
                function searchByKeyword() {
                    var results = YouTube.Search.list('id,snippet', {q: 'dogs', maxResults: 25});
                    for(var i in results.items) {
                        var item = results.items[i];
                        console.log('[%s] Title: %s', item.id.videoId, item.snippet.title);
                    }
                }

                searchByKeyword();
            });
        }

    script(src="https://apis.google.com/js/client.js?onload=googleApiClientReady")`

根据我的代码,我认为它应该加载一个视频(它确实如此),然后搜索“狗”,并将结果记录到控制台。

但是,我收到错误:

ReferenceError: YouTube is not defined

我不知道我做错了什么......脚本没有加载的东西也许......但是我试过在所有可以去的地方加载脚本,我想。

感谢。

更新

我再次将script(放在底部 - 就像我原来的代码一样......现在我可以确认正在运行searchByKeyword方法......但问题又回到了YouTube is not defined问题。在下面的块中,第一行来自我在searchByKeyword方法开头放置的console.log消息,第二行是相同的错误(这篇文章的标题):

searchByKeyword is running ReferenceError: YouTube is not defined

1 个答案:

答案 0 :(得分:3)

您最初的问题是,当gapi.client加载时,它会扩展基础gapi对象。要访问Youtube API,请使用gapi.client.youtube.search代替Youtube.Search

此外,Javascript本质上是异步的,因此任何XHR请求的返回必须在回调中或者已经被保证。

function searchByKeyword() {
  var request = gapi.client.youtube.search.list({
    q: 'dogs',
    part: 'snippet'
  });

  request.execute(function(results) {
    for(var i in results.items) {
      var item = results.items[i];
      console.log('[%s] Title: %s', item.id.videoId,item.snippet.title);
    }
  });
 }
}