Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 'gapi.client' from Google Plus Api undefined ?

I am trying to use google+ api, and i had to modify the sample authentification example to fit my needs like this:

<script src="https://apis.google.com/js/client.js"></script>

Instead of this:

<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>

Basically removed the onload parameter, and placed all the functionality on dom ready.

Here is the problem which i just don't understand:

Code:

console.log(gapi);
console.log(gapi.client);

$.each(gapi, function(){

        console.log(this);

});

gapi.client.setApiKey(this.options.apiKey);

Output:

enter image description here

So, my question basically is:

Why at console.log(gapi) it shows that it has sub-objects like client and auth, and at console.log(gapi.client) it says undefined ?

like image 267
Cristi Pufu Avatar asked Oct 13 '12 15:10

Cristi Pufu


1 Answers

You must use the ?onload callback parameter, it is called when the JS Client has finished loading asynchronously. By running on dom ready, you are trying to access gapi.client before it has been defined. What's happening is that the /js/client.js script defines gapi and some helper functions, but gapi.client and gapi.auth aren't defined until the JS client has finished loading. When you inspect the Object logged by console.log(gapi), the client has finished loading, so you see gapi.client and gapi.auth defined.

like image 68
Brendan Avatar answered Nov 24 '22 00:11

Brendan