JavaScript Code Samples

Organízate con las colecciones Guarda y clasifica el contenido según tus preferencias.

Los siguientes ejemplos de código, que utilizan la Biblioteca de cliente de API de Google para JavaScript, están disponibles para YouTube Data API.

Autorización de solicitudes

  • JavaScript (auth.js)

    La secuencia de comandos auth.js muestra cómo utilizar la Biblioteca de cliente de API de Google para JavaScript para proporcionar acceso a la API y autorizar solicitudes de los usuarios. Todos los ejemplos posteriores de esta página usan esta secuencia de comandos para autorizar sus peticiones.

    Para las solicitudes que no requieren autenticación, también es posible utilizar el parámetro de consulta key para especificar una clave de API en lugar de utilizar OAuth 2.0.

    Nota: Es necesario actualizar el ID de cliente en el archivo auth.js. Puede obtener su propio ID de cliente mediante el registro de su aplicación en la Consola de API de Google.

    // 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();
      });
    }

Mis videos subidos

Los siguientes ejemplos de código corresponden a una aplicación que muestra los videos subidos al canal del usuario autorizado. El código supone que los archivos JavaScript y CSS están en el mismo directorio que la página HTML.

  • JavaScript (my_uploads.js)

    El código JavaScript a continuación cumple las siguientes funciones:

    1. Recupera el ID de la lista de reproducción de los videos subidos en el canal del usuario a través del método channels.list de la API.
    2. Entrega ese ID al método playlistItems.list para recuperar los videos en esa lista.
    3. Muestra la lista de videos.
    4. Construye los botones de la página anterior y siguiente y establece su visibilidad en función de la información contenida en la respuesta de la API.

    Como se señala en la sección Autorización de solicitudes, es necesario actualizar el ID de cliente en el archivo auth.js para ejecutar este código.

    // 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)

    La siguiente página HTML utiliza JQuery, los archivos de JavaScript auth.js y my_uploads.js mencionados anteriormente, además de un archivo CSS para mostrar la lista de videos subidos.

    <!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)

    Esta aplicación de ejemplo también utiliza el siguiente CSS:

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

Crear una lista de reproducción

Los siguientes ejemplos de código corresponden a una aplicación que permite a un usuario crear una lista de reproducción privada y agregar videos a esta. (Naturalmente, es posible modificar el código para que cree una lista de reproducción visible públicamente o para que compruebe un valor de formulario para determinar si la lista de reproducción es pública o privada).

  • JavaScript (playlist_updates.js)

    El código JavaScript a continuación cumple las siguientes funciones:

    1. Permite al usuario crear una lista de reproducción privada y muestra la información sobre la lista de reproducción creada recientemente.
    2. Permite al usuario agregar un video a la lista de reproducción y muestra la respuesta de la API de esa operación. Tenga en cuenta que el código JavaScript admite la capacidad de especificar la posición en la que el video debe iniciar y detener la reproducción, pero el HTML a continuación no proporciona una forma de especificar esos valores.

    Una vez más, es necesario actualizar el ID de cliente en el archivo auth.js para ejecutar este código.

    // 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)

    La siguiente página HTML utiliza JQuery, junto con los archivos de JavaScript auth.js y playlist_updates.js anteriormente mencionados.

    <!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>

Búsqueda por palabra clave

Los siguientes ejemplos de código corresponden a una aplicación que ejecuta una búsqueda en YouTube para una consulta especificada y luego muestra el resultado de la API.

  • JavaScript (search.js)

    El siguiente código JavaScript ejecuta una búsqueda en YouTube para el término de consulta especificado y luego rellena un elemento DOM con la respuesta de la API. Una vez más, es necesario actualizar el ID de cliente en el archivo auth.js para ejecutar este código.

    // 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)

    La siguiente página HTML utiliza jQuery, junto con los archivos de JavaScript auth.js y search.js anteriormente mencionados, para mostrar la lista de resultados de búsqueda.

    <!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>