youtube api v3 search by keyword javascript

佐手、 提交于 2019-12-01 13:37:59

The documentation is misleading a bit (one might even say incorrect); the HTML for the "search by keyword" is loading the same "auth.js" that the other two examples on that page are, but it doesn't then have any HTML elements to actually trigger the login process (i.e. a "login button" if a user isn't already authorized) like the other two examples do. Bascially, if you're using that provided auth.js, you need to have, in your HTML, a section that looks like this:

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

Then, you can also add the class of "post-auth" on a new div that wraps around your existing buttons and search container. The demo will then, when a user visits, only present the login link; when clicked on, and when a user allows the authorization, then the login link will be hidden and your search area will be shown (and the button enabled). That's just how the demo is set up.

Of course, search by keyword does NOT require oAuth2, and so (to answer your 2nd question) you might find it easier to A) remove the handleApiLoaded method (so your button is never disabled), and B) call gapi.client.load() manually (i.e. not triggered by an oAuth success). Then, call gapi.client.setApiKey({YOUR KEY}) so that all of your requests will include your key in their header.

user3080392

Thanks so much jlmcdonald for your help. It took me a while to figure out the second part of your response, but I finally had success. The following html gets the example on the google developers webpage to work. Note though, at first I was getting a 401 error. To fix it, I had to go to the google developers console and select my project. Then, APIs&auth->consent screen and then fill in the email address and product name:

<!doctype html>
<html>
  <head>
  <title>Search</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" class="post-auth">
  <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="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
  <script src="/files/theme/auth.js"></script>
  <script src="/files/theme/search.js"></script>
  <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"> </script>
</body>
</html>

As you noted in your response, oAuth2 isn't necessary for a simple keyword search. The following is some html that just uses the API key. I didn't reference the two .js files like before, rather, I just included the script in the html. Your post at gapi.client.youtube is undefined? really helped me figure it out:

<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
  <div id="buttons">
  <label> <input id="query" value='cats' type="text"/><button id="search-button"  onclick="keyWordsearch()">Search</button></label>
  </div>
  <div id="search-container">
  </div>

  <script>
    function keyWordsearch(){
            gapi.client.setApiKey('API key here');
            gapi.client.load('youtube', 'v3', function() {
                    makeRequest();
            });
    }
    function makeRequest() {
            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>');
            });
    }
 </script>

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
 <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"> </script>
</body>
</html>

Now that I got the search part, could you explain how I can display the thumbnails and titles of the results and then when I click them, the video opens in an embedded player on the same page? Thanks.

Thank you for your coding. Let me share my code:

function makeRequest(){
      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,'',4);
          $('#search-container').val( str);
          makeControl(response);
      });
  }
  
  function makeControl(resp){
      var stList = '<table id="res1" border="1" cellspacing="1" width="100%"><tbody>'; 
      for (var i=0; i<resp.items.length;i++){
          var vid = resp.items[i].id.videoId; 
          var tit = resp.items[i].snippet.title;
          if(typeof vid != 'undefined'){    
              stList += '<tr><td style="width:80px;vertical-align:top">'+
                '<a class="show" href="#" title="'+ vid + '" onclick="playVid(this);'+
                ' return false">'+
                '<img  width="80" height="60" src="http://img.youtube.com/vi/'+ 
                vid +'/default.jpg"></a></td>'+
                '<td><b>'+i+'</b>-'+ tit +'</td></tr>';
          }
      }
      document.getElementById('list1').innerHTML = stList + '</tbody></table>';
      //HTML: <div id="list1" 
      //style="width:853px;height:400px;overflow:auto;background-color:#EEEEEE">
      //</div>
  }
  
  function playVid(thi){
      var st = 'https://www.youtube.com/embed/'+thi.title+'?autoplay=1';
      document.getElementById('player').src = st; 
      //HTML: <iframe id="player" width="853" height="480" src="" frameborder="1" allowfullscreen>
      //</iframe>
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!