Vinayak Garg
Vinayak Garg

Reputation: 6616

How to add onload event for gapi?

I am using Google API (gapi) for user log in.

My code is below. It loads google sdk asynchronously. Once it is loaded I need to call the api function gapi.auth.authorize

(function(d: any, s: string, id: string) {
    var js: HTMLScriptElement, gjs: Element = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "https://apis.google.com/js/client.js";
    gjs.parentNode.insertBefore(js, gjs);

    if (js.readyState){  //IE
        js.onreadystatechange = function(){
            if (js.readyState == "loaded" ||
                js.readyState == "complete"){
                js.onreadystatechange = null;
                gapi.auth.authorize();   //<-- details omitted 
            }
        };
    } else {  //Others
        js.onload = function(){
            gapi.auth.authorize();   //<-- details omitted 
        };
    }
}(document, 'script', 'google-jssdk'));

Now the issue is - I get error

TypeError: gapi.auth is undefined

It should be defined right? I looked at the console, and typed gapi.auth and I get an object in response.

So I believe that js.onload event is getting triggered early, i.e when gapi.auth is not ready.

How to fix this? Or more specifically how to add onload event for gapi?

Upvotes: 4

Views: 4721

Answers (3)

Lucas Andrade
Lucas Andrade

Reputation: 4610

You can also try the package gapi-script, this package provides the gapi instantly, so you don't have to wait any script to load, just import it and use:

import { gapi } from 'gapi-script';

And the package also has a function to initialize the gapi auth2:

import { loadAuth2 } from 'gapi-script';

let auth2 = await loadAuth2(clientId, scopes);

Upvotes: 0

Alexandr Yakubenko
Alexandr Yakubenko

Reputation: 564

window.gapi_onload = function() { gapi.auth.authorize(); }

Upvotes: 0

Ben Sittler
Ben Sittler

Reputation: 274

What browser is this seen in? Also, you need to include a ?onload=myFunction parameter at the end of the script's src attribute, then implement window['myFunction'] = function() { ... } to detect library readiness. The loading typically injects an additional script node and you'll need to wait for that one, too.

Upvotes: 3

Related Questions