9

I am trying to enable sign in with google on my site. The button works, syncs with my account, but I can not access the userId from google. This is what's in my head.

 <script type="text/javascript">
      (function() {
        var po = document.createElement('script');
        po.type = 'text/javascript'; po.async = true;
        po.src = 'https://plus.google.com/js/client:plusone.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(po, s);
      })();
      </script>

And this is where I'm trying to obtain the user Id. In the console I get the error message Uncaught ReferenceError: gapi is not defined. I thought I was calling gapi in the source above. Any help or suggestions would be much appreciated.

$('document').ready(function(){
        var request = gapi.client.plus.people.get({
      'userId' : 'me'
    });

    request.execute(function(resp) {
      console.log('ID: ' + resp.id);
      console.log('Display Name: ' + resp.displayName);
      console.log('Image URL: ' + resp.image.url);
      console.log('Profile URL: ' + resp.url);
    });
});
dopatraman
  • 13,416
  • 29
  • 90
  • 154
RyanY
  • 635
  • 1
  • 8
  • 20

1 Answers1

9

Your code is calling gapi.client.plus.people.get method before loading the google api library https://plus.google.com/js/client:plusone.js. Hence you are getting gapi is not defined error.

Approach to work-

  1. Why its not working?

We are calling https://plus.google.com/js/client:plusone.js asynchronously(non blocking) to improve the performance. With Async javascript file loading, you are not able to call the gapi method on body load.

    <script type="text/javascript">
          (function() {
            var po = document.createElement('script');
            po.type = 'text/javascript'; po.async = true;
            po.src = 'https://plus.google.com/js/client:plusone.js';
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(po, s);
    </script>
  1. To make the api call you first have to know javascript file is successfully loaded.
  2. For this you have to call method using callback. https://apis.google.com/js/client:plusone.js?onload=makeAPICall

  3. Write an api request & execution it in the callback method to get data.

Check below example for this-

    <html>
    <head></head>
    <body>
    <span id="signinButton">
      <span
        class="g-signin"
        data-callback="signinCallback" 
        data-clientid="YOUR CLIENT ID.apps.googleusercontent.com"
        data-cookiepolicy="single_host_origin"
        data-scope="https://www.googleapis.com/auth/plus.login">
      </span>
    </span>
    <script type="text/javascript">      
      (function() {
         var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
         po.src = 'https://apis.google.com/js/client:plusone.js?onload=signinCallback';
         var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
      })();
      function signinCallback(authResult) {
            if (authResult['status']['signed_in']) {
                    document.getElementById('signinButton').setAttribute('style', 'display: none');
                        makeAPICall();
            } else {
                console.log('Sign-in state: ' + authResult['error']);
            }
      }
            function makeAPICall(){
            gapi.client.load('plus', 'v1', function() {
              var request = gapi.client.plus.people.get({
                'userId': 'me'
              });
              request.execute(function (resp){
                console.log(resp);
                if(resp.id){
                  console.log('ID: ' + resp.id);
                }
                if(resp.displayName){
                  console.log('Display Name: ' + resp.displayName);
                }
                if(resp.image && resp.image.url){
                  console.log('Image URL: ' + resp.image.url);
                }
                if(resp.url){
                  console.log('Profile URL: ' + resp.url);
                }
              });
           });
      }
    </script>
    </body>
    </html>

Conclusion: Calling javascript API before loading the asynchronously client library.

To avoid "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.". Call makeAPICall() method only when user is logged in not on every request.

Rajesh Ujade
  • 2,715
  • 19
  • 39