JavaScript コード サンプル

次のコード サンプルは JavaScript用のGoogle APIのクライアントライブラリ を使用しており、YouTube Data API で利用できます。これらのコードサンプルは GithubのYouTube APIコードサンプルレポジトリ 内にあるjavascriptのフォルダからダウンロードできます。

リクエストの承認

  • JavaScript (auth.js)

    auth.js スクリプトでは、Google APIs Client Library for JavaScript を使用し、API にアクセスしてユーザー リクエストを承認する方法を示します。このページの以降のサンプルはすべて、このスクリプトを使ってリクエストを承認しています。

    認証が不要なリクエストの場合は、OAuth 2.0 の代わりに key クエリ パラメータを使って、API キーを指定できます。

    注: auth.js ファイル内のクライアント ID の更新が必要です。自分のクライアント ID を取得するには、Google APIs Consoleアプリケーションを登録します。

    // The client ID is obtained from the Google API Console
    // at https://console.cloud.google.com/.
    // If you run this code from a server other than http://localhost,
    // you need to register your own client ID.
    var OAUTH2_CLIENT_ID = '__YOUR_CLIENT_ID__';
    var OAUTH2_SCOPES = [
      'https://www.googleapis.com/auth/youtube'
    ];
    
    // Upon loading, the Google APIs JS client automatically invokes this callback.
    googleApiClientReady = function() {
      gapi.auth.init(function() {
        window.setTimeout(checkAuth, 1);
      });
    }
    
    // Attempt the immediate OAuth 2.0 client flow as soon as the page loads.
    // If the currently logged-in Google Account has previously authorized
    // the client specified as the OAUTH2_CLIENT_ID, then the authorization
    // succeeds with no user intervention. Otherwise, it fails and the
    // user interface that prompts for authorization needs to display.
    function checkAuth() {
      gapi.auth.authorize({
        client_id: OAUTH2_CLIENT_ID,
        scope: OAUTH2_SCOPES,
        immediate: true
      }, handleAuthResult);
    }
    
    // Handle the result of a gapi.auth.authorize() call.
    function handleAuthResult(authResult) {
      if (authResult && !authResult.error) {
        // Authorization was successful. Hide authorization prompts and show
        // content that should be visible after authorization succeeds.
        $('.pre-auth').hide();
        $('.post-auth').show();
        loadAPIClientInterfaces();
      } else {
        // Make the #login-link clickable. Attempt a non-immediate OAuth 2.0
        // client flow. The current function is called when that flow completes.
        $('#login-link').click(function() {
          gapi.auth.authorize({
            client_id: OAUTH2_CLIENT_ID,
            scope: OAUTH2_SCOPES,
            immediate: false
            }, handleAuthResult);
        });
      }
    }
    
    // Load the client interfaces for the YouTube Analytics and Data APIs, which
    // are required to use the Google APIs JS client. More info is available at
    // https://developers.google.com/api-client-library/javascript/dev/dev_jscript#loading-the-client-library-and-the-api
    function loadAPIClientInterfaces() {
      gapi.client.load('youtube', 'v3', function() {
        handleAPILoaded();
      });
    }

アップロードした動画

以下のコード サンプルは、承認済みユーザーのチャンネルにアップロードされた動画をリストするアプリケーション用です。このコードでは、JavaScript ファイルと CSS ファイルが HTML ページと同じディレクトリにあることを前提にしています。

  • JavaScript (my_uploads.js)

    以下の JavaScript コードは次の機能を実行します。

    1. API の channels.list メソッドを使って、ユーザーのチャンネルにアップロードされた動画の再生リスト ID を取得します。
    2. 取得した ID を playlistItems.list メソッドに渡し、リスト内の動画を検索します。
    3. 動画のリストを表示します。
    4. 次のページ ボタンおよび前のページ ボタンを作成し、API のレスポンスを基に表示/非表示を設定します。

    リクエストの承認のセクションで説明したように、このコードを実行するには、auth.js ファイル内のクライアント ID を更新する必要があります。

    // Define some variables used to remember state.
    var playlistId, nextPageToken, prevPageToken;
    
    // After the API loads, call a function to get the uploads playlist ID.
    function handleAPILoaded() {
      requestUserUploadsPlaylistId();
    }
    
    // Call the Data API to retrieve the playlist ID that uniquely identifies the
    // list of videos uploaded to the currently authenticated user's channel.
    function requestUserUploadsPlaylistId() {
      // See https://developers.google.com/youtube/v3/docs/channels/list
      var request = gapi.client.youtube.channels.list({
        mine: true,
        part: 'contentDetails'
      });
      request.execute(function(response) {
        playlistId = response.result.items[0].contentDetails.relatedPlaylists.uploads;
        requestVideoPlaylist(playlistId);
      });
    }
    
    // Retrieve the list of videos in the specified playlist.
    function requestVideoPlaylist(playlistId, pageToken) {
      $('#video-container').html('');
      var requestOptions = {
        playlistId: playlistId,
        part: 'snippet',
        maxResults: 10
      };
      if (pageToken) {
        requestOptions.pageToken = pageToken;
      }
      var request = gapi.client.youtube.playlistItems.list(requestOptions);
      request.execute(function(response) {
        // Only show pagination buttons if there is a pagination token for the
        // next or previous page of results.
        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) {
          $.each(playlistItems, function(index, item) {
            displayResult(item.snippet);
          });
        } else {
          $('#video-container').html('Sorry you have no uploaded videos');
        }
      });
    }
    
    // Create a listing for a video.
    function displayResult(videoSnippet) {
      var title = videoSnippet.title;
      var videoId = videoSnippet.resourceId.videoId;
      $('#video-container').append('<p>' + title + ' - ' + videoId + '</p>');
    }
    
    // Retrieve the next page of videos in the playlist.
    function nextPage() {
      requestVideoPlaylist(playlistId, nextPageToken);
    }
    
    // Retrieve the previous page of videos in the playlist.
    function previousPage() {
      requestVideoPlaylist(playlistId, prevPageToken);
    }
  • HTML (my_uploads.html)

    次の HTML ページは、JQuery、上記の auth.js および my_uploads.js の各 JavaScript ファイル、CSS ファイルを使い、アップロードした動画のリストを表示します。

    <!doctype html>
    <html>
      <head>
        <title>My Uploads</title>
        <link rel="stylesheet" type="text/css" href="my_uploads.css">
      </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://www.gstatic.com/external_hosted/jquery2.min.js"></script>
        <script type="text/javascript" src="auth.js"></script>
        <script type="text/javascript" src="my_uploads.js"></script>
        <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
      </body>
    </html>
  • CSS (my_uploads.css)

    このサンプル アプリは次の CSS も使用しています。

    .paging-button {
      visibility: hidden;
    }
    
    .button-container {
      clear: both;
    }

再生リストの作成

以下のコード サンプルは、非公開の再生リストをユーザーが作成し、動画を追加できるようにします(コードを修正すれば、公開の再生リストを作成することも、フォームの値を確認して再生リストが公開か非公開かを判別することもできます)。

  • JavaScript (playlist_updates.js)

    以下の JavaScript コードは次の機能を実行します。

    1. 非公開の再生リストを作成できるようにし、作成された再生リストに関する情報を表示します。
    2. 再生リストに動画を追加できるようにし、その操作の API レスポンスを表示します。なお、この JavaScript コードでは動画の再生開始位置と停止位置を指定できますが、次の HTML ではこれらの値を指定できません。

    繰り返しになりますが、このコードを実行するには、auth.js ファイル内のクライアント ID を更新する必要があります。

    // Define some variables used to remember state.
    var playlistId, channelId;
    
    // After the API loads, call a function to enable the playlist creation form.
    function handleAPILoaded() {
      enableForm();
    }
    
    // Enable the form for creating a playlist.
    function enableForm() {
      $('#playlist-button').attr('disabled', false);
    }
    
    // Create a private playlist.
    function createPlaylist() {
      var request = gapi.client.youtube.playlists.insert({
        part: 'snippet,status',
        resource: {
          snippet: {
            title: 'Test Playlist',
            description: 'A private playlist created with the YouTube API'
          },
          status: {
            privacyStatus: 'private'
          }
        }
      });
      request.execute(function(response) {
        var result = response.result;
        if (result) {
          playlistId = result.id;
          $('#playlist-id').val(playlistId);
          $('#playlist-title').html(result.snippet.title);
          $('#playlist-description').html(result.snippet.description);
        } else {
          $('#status').html('Could not create playlist');
        }
      });
    }
    
    // Add a video ID specified in the form to the playlist.
    function addVideoToPlaylist() {
      addToPlaylist($('#video-id').val());
    }
    
    // Add a video to a playlist. The "startPos" and "endPos" values let you
    // start and stop the video at specific times when the video is played as
    // part of the playlist. However, these values are not set in this example.
    function addToPlaylist(id, startPos, endPos) {
      var details = {
        videoId: id,
        kind: 'youtube#video'
      }
      if (startPos != undefined) {
        details['startAt'] = startPos;
      }
      if (endPos != undefined) {
        details['endAt'] = endPos;
      }
      var request = gapi.client.youtube.playlistItems.insert({
        part: 'snippet',
        resource: {
          snippet: {
            playlistId: playlistId,
            resourceId: details
          }
        }
      });
      request.execute(function(response) {
        $('#status').html('<pre>' + JSON.stringify(response.result) + '</pre>');
      });
    }
  • HTML (playlist_updates.html)

    次の HTML ページでは、JQuery および上記の auth.jsplaylist_updates.js の各 JavaScript ファイルを使っています。

    <!doctype html>
    <html>
      <head>
        <title>Playlist Updates</title>
      </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="buttons">
          <button id="playlist-button" disabled onclick="createPlaylist()">Create a new Private Playlist</button>
          <br>
          <label>Current Playlist Id: <input id="playlist-id" value='' type="text"/></label>
          <br>
          <label>Video Id: <input id="video-id" value='GZG9G5txtaE' type="text"/></label><button onclick="addVideoToPlaylist()">Add to current playlist</button>
        </div>
        <h3>Playlist: <span id="playlist-title"></span></h3>
        <p id="playlist-description"></p>
        <div id="playlist-container">
          <span id="status">No Videos</span>
        </div>
        <script src="https://www.gstatic.com/external_hosted/jquery2.min.js"></script>
        <script src="auth.js"></script>
        <script src="playlist_updates.js"></script>
        <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
      </body>
    </html>

キーワードで検索

以下のコード サンプルは、指定したクエリに対して YouTube 検索を実行し、API 結果を表示します。

  • JavaScript (search.js)

    次の JavaScript コードは、指定したクエリ用語で YouTube 検索を実行し、API レスポンスを DOM 要素に追加します。繰り返しになりますが、このコードを実行するには、auth.js ファイル内のクライアント ID を更新する必要があります。

    // After the API loads, call a function to enable the search box.
    function handleAPILoaded() {
      $('#search-button').attr('disabled', false);
    }
    
    // Search for a specified string.
    function search() {
      var q = $('#query').val();
      var request = gapi.client.youtube.search.list({
        q: q,
        part: 'snippet'
      });
    
      request.execute(function(response) {
        var str = JSON.stringify(response.result);
        $('#search-container').html('<pre>' + str + '</pre>');
      });
    }
  • HTML (search.html)

    次の HTML ページでは、JQuery および上記の auth.jssearch.js の各 JavaScript ファイルを使い、検索結果のリストを表示します。

    <!doctype html>
    <html>
      <head>
        <title>Search</title>
      </head>
      <body>
        <div id="buttons">
          <label> <input id="query" value='cats' type="text"/><button id="search-button" disabled onclick="search()">Search</button></label>
        </div>
        <div id="search-container">
        </div>
        <script src="https://www.gstatic.com/external_hosted/jquery2.min.js"></script>
        <script src="auth.js"></script>
        <script src="search.js"></script>
        <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
      </body>
    </html>