admin管理员组

文章数量:1296471

After some wise input from jlmcdonald, I re-wrote this post

The end goal is to do some fun stuff with the YouTube API. Today's goal is to just get it to work.

I did the youtube dev java-scrip API tutorial here:


But instead of separate documents, I did one large one and adjusted the script tags as needed.

Could not get it to work.... Ideas?

Here's a pic of my API codes from Google (if needed)

<!doctype html>
<html>
  <head>
    <title>My Uploads</title>
    <link rel="stylesheet" href="my_uploads.css" />
    <style>
      .paging-button {
        visibility: hidden;
      }

      .video-content {
        width: 200px;
        height: 200px;
        background-position: center;
        background-repeat: no-repeat;
        float: left;
        position: relative;
        margin: 5px;
      }

      .video-title {
        width: 100%;
        text-align: center;
        background-color: rgba(0, 0, 0, .5);
        color: white;
        top: 50%;
        left: 50%;
        position: absolute;
        -moz-transform: translate(-50%, -50%);
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
      }

      .video-content:nth-child(3n+1) {
        clear: both;
      }

      .button-container {
        clear: both;
      }
      </style>
      <script>
        //This is the Authorization by Client ID 
        // The client id is obtained from the Google APIs Console at 
        // If you run access this code from a server other than http://localhost, you need to register
        // your own client id.
        var OAUTH2_CLIENT_ID = '367567738093.apps.googleusercontent';
        var OAUTH2_SCOPES = [
          ''
        ];

        // This callback is invoked by the Google APIs JS client automatically when it is loaded.
        googleApiClientReady = function() {
          gapi.auth.init(function() {
            window.setTimeout(checkAuth, 1);
          });
        }

        // Attempt the immediate OAuth 2 client flow as soon as the page is loaded.
        // If the currently logged in Google Account has previously authorized OAUTH2_CLIENT_ID, then
        // it will succeed with no user intervention. Otherwise, it will fail and the user interface
        // to prompt for authorization needs to be displayed.
        function checkAuth() {
          gapi.auth.authorize({
            client_id: OAUTH2_CLIENT_ID,
            scope: OAUTH2_SCOPES,
            immediate: true
          }, handleAuthResult);
        }

        // Handles the result of a gapi.auth.authorize() call.
        function handleAuthResult(authResult) {
          if (authResult) {
            // Auth was successful; hide the things related to prompting for auth and show the things
            // that should be visible after auth succeeds.
            $('.pre-auth').hide();
            loadAPIClientInterfaces();
          } else {
            // Make the #login-link clickable, and attempt a non-immediate OAuth 2 client flow.
            // The current function will be called when that flow is plete.
            $('#login-link').click(function() {
              gapi.auth.authorize({
                client_id: OAUTH2_CLIENT_ID,
                scope: OAUTH2_SCOPES,
                immediate: false
                }, handleAuthResult);
            });
          }
        }

        // Loads the client interface for the YouTube Analytics and Data APIs.
        // This is required before using the Google APIs JS client; more info is available at
        // 
        function loadAPIClientInterfaces() {
          gapi.client.load('youtube', 'v3', function() {
            handleAPILoaded();
          });
        }



      //This is the uploads script
      // Some variables to remember state.
      var playlistId, nextPageToken, prevPageToken;

      // Once the api loads call a function to get the uploads playlist id.
      function handleAPILoaded() {
        requestUserUploadsPlaylistId();
      }

      //Retrieve the uploads playlist id.
      function requestUserUploadsPlaylistId() {
        // 
        var request = gapi.client.youtube.channels.list({
          // mine: '' indicates that we want to retrieve the channel for the authenticated user.
          mine: '',
          part: 'contentDetails'
        });
        request.execute(function(response) {
          playlistId = response.result.items[0].contentDetails.uploads;
          requestVideoPlaylist(playlistId);
        });
      }

      // Retrieve a playist of videos.
      function requestVideoPlaylist(playlistId, pageToken) {
        $('#video-container').html('');
        var requestOptions = {
          playlistId: playlistId,
          part: 'snippet',
          maxResults: 9
        };
        if (pageToken) {
          requestOptions.pageToken = pageToken;
        }
        var request = gapi.client.youtube.playlistItems.list(requestOptions);
        request.execute(function(response) {
          // Only show the page buttons if there's a next or previous page.
          nextPageToken = response.result.nextPageToken;
          var nextVis = nextPageToken ? 'visible' : 'hidden';
          $('#next-button').css('visibility', nextVis);
          prevPageToken = response.result.prevPageToken
          var prevVis = prevPageToken ? 'visible' : 'hidden';
          $('#prev-button').css('visibility', prevVis);

          var playlistItems = response.result.items;
          if (playlistItems) {
            // For each result lets show a thumbnail.
            jQuery.each(playlistItems, function(index, item) {
              createDisplayThumbnail(item.snippet);
            });
          } else {
            $('#video-container').html('Sorry you have no uploaded videos');
          }
        });
      }


      // Create a thumbnail for a video snippet.
      function createDisplayThumbnail(videoSnippet) {
        var titleEl = $('<h3>');
        titleEl.addClass('video-title');
        $(titleEl).html(videoSnippet.title);
        var thumbnailUrl = videoSnippet.thumbnails.medium.url;

        var div = $('<div>');
        div.addClass('video-content');
        div.css('backgroundImage', 'url("' + thumbnailUrl + '")');
        div.append(titleEl);
        $('#video-container').append(div);
      }

      // Retrieve the next page of videos.
      function nextPage() {
        requestVideoPlaylist(playlistId, nextPageToken);
      }

      // Retrieve the previous page of videos.
      function previousPage() {
        requestVideoPlaylist(playlistId, prevPageToken);
      }
    </script>
  </head>
  <body>
    <div id="login-container" class="pre-auth">This application requires access to your YouTube account.
      Please <a href="#" id="login-link">authorize</a> to continue.
    </div>
    <div id="video-container">
    </div>
    <div class="button-container">
      <button id="prev-button" class="paging-button" onclick="previousPage();">Previous Page</button>
      <button id="next-button" class="paging-button" onclick="nextPage();">Next Page</button>
    </div>
    <script src=".8.2/jquery.min.js"></script>
    <script src=".js?onload=googleApiClientReady"></script>
  </body>
</html>

After some wise input from jlmcdonald, I re-wrote this post

The end goal is to do some fun stuff with the YouTube API. Today's goal is to just get it to work.

I did the youtube dev java-scrip API tutorial here:

https://developers.google./youtube/v3/code_samples/javascript#my_uploads

But instead of separate documents, I did one large one and adjusted the script tags as needed.

Could not get it to work.... Ideas?

Here's a pic of my API codes from Google (if needed) http://d.pr/i/Ybcx

<!doctype html>
<html>
  <head>
    <title>My Uploads</title>
    <link rel="stylesheet" href="my_uploads.css" />
    <style>
      .paging-button {
        visibility: hidden;
      }

      .video-content {
        width: 200px;
        height: 200px;
        background-position: center;
        background-repeat: no-repeat;
        float: left;
        position: relative;
        margin: 5px;
      }

      .video-title {
        width: 100%;
        text-align: center;
        background-color: rgba(0, 0, 0, .5);
        color: white;
        top: 50%;
        left: 50%;
        position: absolute;
        -moz-transform: translate(-50%, -50%);
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
      }

      .video-content:nth-child(3n+1) {
        clear: both;
      }

      .button-container {
        clear: both;
      }
      </style>
      <script>
        //This is the Authorization by Client ID http://d.pr/i/mEmY
        // The client id is obtained from the Google APIs Console at https://code.google./apis/console
        // If you run access this code from a server other than http://localhost, you need to register
        // your own client id.
        var OAUTH2_CLIENT_ID = '367567738093.apps.googleusercontent.';
        var OAUTH2_SCOPES = [
          'https://www.googleapis./auth/youtube'
        ];

        // This callback is invoked by the Google APIs JS client automatically when it is loaded.
        googleApiClientReady = function() {
          gapi.auth.init(function() {
            window.setTimeout(checkAuth, 1);
          });
        }

        // Attempt the immediate OAuth 2 client flow as soon as the page is loaded.
        // If the currently logged in Google Account has previously authorized OAUTH2_CLIENT_ID, then
        // it will succeed with no user intervention. Otherwise, it will fail and the user interface
        // to prompt for authorization needs to be displayed.
        function checkAuth() {
          gapi.auth.authorize({
            client_id: OAUTH2_CLIENT_ID,
            scope: OAUTH2_SCOPES,
            immediate: true
          }, handleAuthResult);
        }

        // Handles the result of a gapi.auth.authorize() call.
        function handleAuthResult(authResult) {
          if (authResult) {
            // Auth was successful; hide the things related to prompting for auth and show the things
            // that should be visible after auth succeeds.
            $('.pre-auth').hide();
            loadAPIClientInterfaces();
          } else {
            // Make the #login-link clickable, and attempt a non-immediate OAuth 2 client flow.
            // The current function will be called when that flow is plete.
            $('#login-link').click(function() {
              gapi.auth.authorize({
                client_id: OAUTH2_CLIENT_ID,
                scope: OAUTH2_SCOPES,
                immediate: false
                }, handleAuthResult);
            });
          }
        }

        // Loads the client interface for the YouTube Analytics and Data APIs.
        // This is required before using the Google APIs JS client; more info is available at
        // http://code.google./p/google-api-javascript-client/wiki/GettingStarted#Loading_the_Client
        function loadAPIClientInterfaces() {
          gapi.client.load('youtube', 'v3', function() {
            handleAPILoaded();
          });
        }



      //This is the uploads script
      // Some variables to remember state.
      var playlistId, nextPageToken, prevPageToken;

      // Once the api loads call a function to get the uploads playlist id.
      function handleAPILoaded() {
        requestUserUploadsPlaylistId();
      }

      //Retrieve the uploads playlist id.
      function requestUserUploadsPlaylistId() {
        // https://developers.google./youtube/v3/docs/channels/list
        var request = gapi.client.youtube.channels.list({
          // mine: '' indicates that we want to retrieve the channel for the authenticated user.
          mine: '',
          part: 'contentDetails'
        });
        request.execute(function(response) {
          playlistId = response.result.items[0].contentDetails.uploads;
          requestVideoPlaylist(playlistId);
        });
      }

      // Retrieve a playist of videos.
      function requestVideoPlaylist(playlistId, pageToken) {
        $('#video-container').html('');
        var requestOptions = {
          playlistId: playlistId,
          part: 'snippet',
          maxResults: 9
        };
        if (pageToken) {
          requestOptions.pageToken = pageToken;
        }
        var request = gapi.client.youtube.playlistItems.list(requestOptions);
        request.execute(function(response) {
          // Only show the page buttons if there's a next or previous page.
          nextPageToken = response.result.nextPageToken;
          var nextVis = nextPageToken ? 'visible' : 'hidden';
          $('#next-button').css('visibility', nextVis);
          prevPageToken = response.result.prevPageToken
          var prevVis = prevPageToken ? 'visible' : 'hidden';
          $('#prev-button').css('visibility', prevVis);

          var playlistItems = response.result.items;
          if (playlistItems) {
            // For each result lets show a thumbnail.
            jQuery.each(playlistItems, function(index, item) {
              createDisplayThumbnail(item.snippet);
            });
          } else {
            $('#video-container').html('Sorry you have no uploaded videos');
          }
        });
      }


      // Create a thumbnail for a video snippet.
      function createDisplayThumbnail(videoSnippet) {
        var titleEl = $('<h3>');
        titleEl.addClass('video-title');
        $(titleEl).html(videoSnippet.title);
        var thumbnailUrl = videoSnippet.thumbnails.medium.url;

        var div = $('<div>');
        div.addClass('video-content');
        div.css('backgroundImage', 'url("' + thumbnailUrl + '")');
        div.append(titleEl);
        $('#video-container').append(div);
      }

      // Retrieve the next page of videos.
      function nextPage() {
        requestVideoPlaylist(playlistId, nextPageToken);
      }

      // Retrieve the previous page of videos.
      function previousPage() {
        requestVideoPlaylist(playlistId, prevPageToken);
      }
    </script>
  </head>
  <body>
    <div id="login-container" class="pre-auth">This application requires access to your YouTube account.
      Please <a href="#" id="login-link">authorize</a> to continue.
    </div>
    <div id="video-container">
    </div>
    <div class="button-container">
      <button id="prev-button" class="paging-button" onclick="previousPage();">Previous Page</button>
      <button id="next-button" class="paging-button" onclick="nextPage();">Next Page</button>
    </div>
    <script src="https://ajax.googleapis./ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script src="https://apis.google./js/client.js?onload=googleApiClientReady"></script>
  </body>
</html>
Share Improve this question edited Sep 6, 2013 at 23:17 Chase Westlye asked Sep 6, 2013 at 18:36 Chase WestlyeChase Westlye 3832 gold badges9 silver badges20 bronze badges 3
  • Sorry, super vauge, super newbish... I'm working on it – Chase Westlye Commented Sep 6, 2013 at 18:37
  • Not sure i understand what you want to do but could be an usefull reading if not already done: developers.google./youtube/2.0/… – A. Wolff Commented Sep 6, 2013 at 18:45
  • @ChaseWestlye ,You should not show your keys to others. – Als Commented Sep 7, 2013 at 6:48
Add a ment  | 

3 Answers 3

Reset to default 7

Since your question is primarily about "getting started," I'll point you in some directions and hopefully that will be enough to get you where you want to go. First of all, there are several different YouTube APIs -- there is the data API, for retrieving information about feeds, activities, videos, etc., and there's the player API, for embedding the video and controlling it. (There's also an analytics API and a live broadcast API, but that's not important here.) If your only goal is to get the information about your most recent upload (you mention title and description), then you'll only need the data API. If you also want the video itself to be embedded in an iFrame (the preferred way), then you'll need both ... you'll use the data API first, then call the player API with the video ID you retrieved from your metadata package.

One more thing to point out is that there are two versions of the data API in production; v2 and v3. v2 is sometimes referred to as the gdata API (as it uses the older gdata XML schema). I'd remend using v3 of the data API, as it's much easier to work with, fully REST and CORS pliant, much more logically laid out, etc. Having said that, there are some things not yet available in v3 (such as ment retrieval), so if you end up needing something that v3 doesn't provide, you'll have to hack around it temporarily.

So, to retrieve your most recent upload from the data API, the general strategy is to call the REST endpoint that gives you the ID of your uploads feed, then call the REST endpoint that gives you the videos belonging to that feed. Luckily, the docs for v3 of the data API have that exact example for you:

https://developers.google./youtube/v3/code_samples/javascript#my_uploads

(note that the example uses the javascript gapi client, primarily to handle the OAuth2 authentication you need. Whenever you are doing a request to the data API that needs authentication, using the gapi client can be quite useful so you don't have to deal with all the token passing yourself. There are gapi clients in javascript, python, php, go, etc. But if you're ever getting data that you just need to read, and that isn't required to be behind the authorization wall, you could get an API key and call the endpoints directly.)

Once you get the data for the most recent upload, you can put the title and description wherever you want in the HTML, then take the video ID (also returned with the data API call) and use it in the player API. The code you posted above is a great example of that.

As you start going through this, you can post new questions about specific problems you may encounter.

See for reference: https://developers.google./youtube/v3/docs/

Don't forget to update the code-line: var OAUTH2_CLIENT_ID = 'Put Your-Client-Id Here';

Changed your current code into:

<!doctype html>
<html>
  <head>
    <title>My Uploads</title>
    <link rel="stylesheet" href="my_uploads.css" />
    <style>
      .paging-button {
        visibility: hidden;
      }

      .video-content {
        width: 200px;
        height: 200px;
        background-position: center;
        background-repeat: no-repeat;
        float: left;
        position: relative;
        margin: 5px;
      }

      .video-title {
        width: 100%;
        text-align: center;
        background-color: rgba(0, 0, 0, .5);
        color: white;
        top: 50%;
        left: 50%;
        position: absolute;
        -moz-transform: translate(-50%, -50%);
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
      }

      .video-content:nth-child(3n+1) {
        clear: both;
      }

      .button-container {
        clear: both;
      }
      </style>


    <script src="https://ajax.googleapis./ajax/libs/jquery/1.8.2/jquery.min.js"></script>


      <script>
        //This is the Authorization by Client ID http://d.pr/i/mEmY
        // The client id is obtained from the Google APIs Console at https://code.google./apis/console
        // If you run access this code from a server other than http://localhost, you need to register
        // your own client id.
        var OAUTH2_CLIENT_ID = 'Put Your-Client-Id Here';  // <==============================
        var OAUTH2_SCOPES = [
          'https://www.googleapis./auth/youtube'
        ];

        // This callback is invoked by the Google APIs JS client automatically when it is loaded.
        googleApiClientReady = function() {
          gapi.auth.init(function() {
            window.setTimeout(checkAuth, 1);
          });
        }

        // Attempt the immediate OAuth 2 client flow as soon as the page is loaded.
        // If the currently logged in Google Account has previously authorized OAUTH2_CLIENT_ID, then
        // it will succeed with no user intervention. Otherwise, it will fail and the user interface
        // to prompt for authorization needs to be displayed.
        function checkAuth() {
          gapi.auth.authorize({
            client_id: OAUTH2_CLIENT_ID,
            scope: OAUTH2_SCOPES,
            immediate: true
          }, handleAuthResult);
        }

        // Handles the result of a gapi.auth.authorize() call.
        function handleAuthResult(authResult) {
          if (authResult) {
            // Auth was successful; hide the things related to prompting for auth and show the things
            // that should be visible after auth succeeds.
            $('.pre-auth').hide();
            loadAPIClientInterfaces();
          } else {
            // Make the #login-link clickable, and attempt a non-immediate OAuth 2 client flow.
            // The current function will be called when that flow is plete.
            $('#login-link').click(function() {
              gapi.auth.authorize({
                client_id: OAUTH2_CLIENT_ID,
                scope: OAUTH2_SCOPES,
                immediate: false
                }, handleAuthResult);
            });
          }
        }

        // Loads the client interface for the YouTube Analytics and Data APIs.
        // This is required before using the Google APIs JS client; more info is available at
        // http://code.google./p/google-api-javascript-client/wiki/GettingStarted#Loading_the_Client
        function loadAPIClientInterfaces() {
          gapi.client.load('youtube', 'v3', function() {
            handleAPILoaded();
          });
        }



      //This is the uploads script
      // Some variables to remember state.
      var playlistId, nextPageToken, prevPageToken;

      // Once the api loads call a function to get the uploads playlist id.
      function handleAPILoaded() {
        requestUserUploadsPlaylistId();
      }

      //Retrieve the uploads playlist id.
      function requestUserUploadsPlaylistId() {
        // https://developers.google./youtube/v3/docs/channels/list
        var request = gapi.client.youtube.channels.list({
          // mine: '' indicates that we want to retrieve the channel for the authenticated user.
          mine: true,
          part: 'contentDetails'
        });
        request.execute(function(response) {
          playlistId = response.result.items[0].contentDetails.relatedPlaylists.uploads;
          requestVideoPlaylist(playlistId);
        });
      }

      // Retrieve a playist of videos.
      function requestVideoPlaylist(playlistId, pageToken) {
        $('#video-container').html('');
        var requestOptions = {
          playlistId: playlistId,
          part: 'snippet',
          maxResults: 9
        };
        if (pageToken) {
          requestOptions.pageToken = pageToken;
        }
        var request = gapi.client.youtube.playlistItems.list(requestOptions);
        request.execute(function(response) {
          // Only show the page buttons if there's a next or previous page.
          nextPageToken = response.result.nextPageToken;
          var nextVis = nextPageToken ? 'visible' : 'hidden';
          $('#next-button').css('visibility', nextVis);
          prevPageToken = response.result.prevPageToken
          var prevVis = prevPageToken ? 'visible' : 'hidden';
          $('#prev-button').css('visibility', prevVis);

          var playlistItems = response.result.items;
          if (playlistItems) {
            // For each result lets show a thumbnail.
            jQuery.each(playlistItems, function(index, item) {
              createDisplayThumbnail(item.snippet);
            });
          } else {
            $('#video-container').html('Sorry you have no uploaded videos');
          }
        });
      }


      // Create a thumbnail for a video snippet.
      function createDisplayThumbnail(videoSnippet) {
        var titleEl = $('<h3>');
        titleEl.addClass('video-title');
        $(titleEl).html(videoSnippet.title);
        var thumbnailUrl = videoSnippet.thumbnails.medium.url;

        var div = $('<div>');
        div.addClass('video-content');
        div.css('backgroundImage', 'url("' + thumbnailUrl + '")');
        div.append(titleEl);
        $('#video-container').append(div);
      }

      // Retrieve the next page of videos.
      function nextPage() {
        requestVideoPlaylist(playlistId, nextPageToken);
      }

      // Retrieve the previous page of videos.
      function previousPage() {
        requestVideoPlaylist(playlistId, prevPageToken);
      }
    </script>


    <script src="https://apis.google./js/client.js?onload=googleApiClientReady"></script>
  </head>
  <body>
    <div id="login-container" class="pre-auth">This application requires access to your YouTube account.
      Please <a href="#" id="login-link">authorize</a> to continue.
    </div>
    <div id="video-container">
    </div>
    <div class="button-container">
      <button id="prev-button" class="paging-button" onclick="previousPage();">Previous Page</button>
      <button id="next-button" class="paging-button" onclick="nextPage();">Next Page</button>
    </div>
  </body>
</html>

So there's an extra section where I setup to create a cookie to store the user's name. Also the CSS is in an external doc. Outside of that... Check it:

<!DOCTYPE HTML>
<html>
    <head>
        <title>My Sandbox</title>
        <link rel="stylesheet" type="text/css" href="CSS/Style.CSS">
        <script src="http://ajax.aspnetcdn./ajax/jQuery/jquery-1.10.2.min.js">
        </script>   
        <script>
            jQuery(function($){
              $("#video-container").on('click', '.video_select', function(e){
                console.log(e);
                var buttonSource = $(this).data('video');
                var embededVideo = $('#youTube_video');
                    embededVideo.attr('src', buttonSource);
                    return false;
              });
            });


            function getCookie(c_name)
                {
                var c_value = document.cookie;
                var c_start = c_value.indexOf(" " + c_name + "=");
                    if (c_start == -1){
                        c_start = c_value.indexOf(c_name + "=");
                    }
                    if (c_start == -1){
                        c_value = null;
                    }
                    else{
                        c_start = c_value.indexOf("=", c_start) + 1;
                var c_end = c_value.indexOf(";", c_start);
                    if (c_end == -1){
                        c_end = c_value.length;
                    }
                        c_value = unescape(c_value.substring(c_start,c_end));
                    }
                    return c_value;
                    }

            function setCookie(c_name,value,exdays){
                var exdate=new Date();
                    exdate.setDate(exdate.getDate() + exdays);
                var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
                    document.cookie=c_name + "=" + c_value;
                    }

            function checkCookie(){
                var username=getCookie("username");
                    if (username!=null && username!=""){
                        alert("Wele back " + username);
                        document.getElementById("title_script").innerHTML="Wele "+username+" to my sandbox";
                        }
                    else{
                        username=prompt("Please enter your name:","");
                        if (username!=null && username!=""){
                        setCookie("username",username,365);
                        document.getElementById("title_script").innerHTML="Wele "+username+" to my sandbox";
                        }
                    }
            }





                </script>



                  <script>
        //This is the Authorization by Client ID http://d.pr/i/mEmY
        // The client id is obtained from the Google APIs Console at https://code.google./apis/console
        // If you run access this code from a server other than http://localhost, you need to register
        // your own client id.
        var OAUTH2_CLIENT_ID = '367567738093.apps.googleusercontent.';
        var OAUTH2_SCOPES = [
          'https://www.googleapis./auth/youtube'
        ];

        // This callback is invoked by the Google APIs JS client automatically when it is loaded.
        googleApiClientReady = function() {
          gapi.auth.init(function() {
            window.setTimeout(checkAuth, 1);
          });
        }

        // Attempt the immediate OAuth 2 client flow as soon as the page is loaded.
        // If the currently logged in Google Account has previously authorized OAUTH2_CLIENT_ID, then
        // it will succeed with no user intervention. Otherwise, it will fail and the user interface
        // to prompt for authorization needs to be displayed.
        function checkAuth() {
          gapi.auth.authorize({
            client_id: OAUTH2_CLIENT_ID,
            scope: OAUTH2_SCOPES,
            immediate: true
          }, handleAuthResult);
        }

        // Handles the result of a gapi.auth.authorize() call.
        function handleAuthResult(authResult) {
          if (authResult) {
            // Auth was successful; hide the things related to prompting for auth and show the things
            // that should be visible after auth succeeds.
            $('.pre-auth').hide();
            loadAPIClientInterfaces();
          } else {
            // Make the #login-link clickable, and attempt a non-immediate OAuth 2 client flow.
            // The current function will be called when that flow is plete.
            $('#login-link').click(function() {
              gapi.auth.authorize({
                client_id: OAUTH2_CLIENT_ID,
                scope: OAUTH2_SCOPES,
                immediate: false
                }, handleAuthResult);
            });
          }
        }

        // Loads the client interface for the YouTube Analytics and Data APIs.
        // This is required before using the Google APIs JS client; more info is available at
        // http://code.google./p/google-api-javascript-client/wiki/GettingStarted#Loading_the_Client
        function loadAPIClientInterfaces() {
          gapi.client.load('youtube', 'v3', function() {
            handleAPILoaded();
          });
        }



      //This is the uploads script
      // Some variables to remember state.
      var playlistId, nextPageToken, prevPageToken;

      // Once the api loads call a function to get the uploads playlist id.
      function handleAPILoaded() {
        requestUserUploadsPlaylistId();
      }

      //Retrieve the uploads playlist id.
      function requestUserUploadsPlaylistId() {
        // https://developers.google./youtube/v3/docs/channels/list
        var request = gapi.client.youtube.channels.list({
          // mine: '' indicates that we want to retrieve the channel for the authenticated user.
          // mine: false,
          id: 'UCziks4y-RixDhWljY_es-tA',
          part: 'contentDetails'
        });
        request.execute(function(response) {
          console.log(response);
          playlistId = response.result.items[0].contentDetails.relatedPlaylists.uploads;
          requestVideoPlaylist(playlistId);
        });
      }

      // Retrieve a playist of videos.
      function requestVideoPlaylist(playlistId, pageToken) {
        $('#video-container').html('');
        var requestOptions = {
          playlistId: playlistId,
          part: 'snippet',
          maxResults: 9
        };
        if (pageToken) {
          requestOptions.pageToken = pageToken;
        }
        var request = gapi.client.youtube.playlistItems.list(requestOptions);
        request.execute(function(response) {
          // Only show the page buttons if there's a next or previous page.
          console.log (response);
          nextPageToken = response.result.nextPageToken;
          var nextVis = nextPageToken ? 'visible' : 'hidden';
          $('#next-button').css('visibility', nextVis);
          prevPageToken = response.result.prevPageToken
          var prevVis = prevPageToken ? 'visible' : 'hidden';
          $('#prev-button').css('visibility', prevVis);

          var playlistItems = response.result.items;
          if (playlistItems) {
            // For each result lets show a thumbnail.
            jQuery.each(playlistItems, function(index, item) {
              createDisplayThumbnail(item.snippet);
            });
          } else {
            $('#video-container').html('Sorry you have no uploaded videos');
          }
        });
      }


      // Create a thumbnail for a video snippet.
      function createDisplayThumbnail(videoSnippet) {
        console.log(videoSnippet);
        var titleEl = $('<h3>');
        titleEl.addClass('video-title');
        $(titleEl).html(videoSnippet.title);
        var thumbnailUrl = videoSnippet.thumbnails.medium.url;
        var videoLink=$('<a>');
        videoLink.attr('data-video','http://www.youtube./embed/'+videoSnippet.resourceId.videoId);
        videoLink.append(div)
        videoLink.addClass('video_select')

        var div = $('<div>');
        div.addClass('video-content');
        div.css('backgroundImage', 'url("' + thumbnailUrl + '")');
        div.append(titleEl);
        videoLink.append(div)
        $('#video-container').append(videoLink);

      }

      // Retrieve the next page of videos.
      function nextPage() {
        requestVideoPlaylist(playlistId, nextPageToken);
      }

      // Retrieve the previous page of videos.
      function previousPage() {
        requestVideoPlaylist(playlistId, prevPageToken);
      }
    </script>















































        </script>
    </head>
<body onload="checkCookie()" class="background_color">
<div class="wrap">
    <iframe id='youTube_video' width="560" height="315" src="//www.youtube./embed/io78hmjAWHw" frameborder="0" allowfullscreen></iframe>
    <h1 class="title" id="title_script">Wele to my Sandbox</h1>
</div>






<div id="login-container" class="pre-auth">This application requires access to your YouTube account.
  Please <a href="#" id="login-link">authorize</a> to continue.
</div>
<div id="video-container">
</div>
<div class="button-container">
  <button id="prev-button" class="paging-button" onclick="previousPage();">Previous Page</button>
  <button id="next-button" class="paging-button" onclick="nextPage();">Next Page</button>
</div>
<script src="https://apis.google./js/client.js?onload=googleApiClientReady"></script>














</body>
</html>

本文标签: