How to add onload event for gapi?

I use the Google API (gapi) to log in the user.

My code is below. It loads asynchronously the Google sdk. After loading it, I need to call the api functiongapi.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 problem is - I get an error

TypeError: gapi.auth undefined

Do you need to determine this correctly? I looked at the console and typed gapi.auth, and I received the object in response.

Therefore, I believe that the event is js.onloadfired earlier, that is, when gapi.authit is not ready.

How to fix it? Or more specifically, how to add an onload event for gapi?

+4
source share
3 answers

? , ?onload=myFunction script src, window['myFunction'] = function() { ... } . script node, .

+3

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

0

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

import { gapi } from 'gapi-script';

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

import { loadAuth2 } from 'gapi-script';

let auth2 = await loadAuth2(clientId, scopes);
0
source

All Articles