CapacitorGoogleAuth icon indicating copy to clipboard operation
CapacitorGoogleAuth copied to clipboard

GoogleAuth.signIn: undefined is not an object (evaluating 'gapi.auth2.getAuthInstance')

Open Linksku opened this issue 1 year ago • 1 comments

If people try to sign in before the Google API file loads, it'll show the error in the title. I can consistently repro this error by throttling my network speed.

I tried to fix this by adding await this.gapiLoaded; to the beginning of signIn(). However, this.gapiLoaded is undefined, even though initialize() ran already.

In this screenshot, gapiResolve is defined, which means initialize() ran already. I don't know why this.gapiLoaded and this.options are undefined. Seems like something weird with Capacitor's plugin proxy?

Screenshot 2024-02-06 014510

The GoogleAuth object in initialize() vs in signIn():

Screenshot 2024-02-06 020512

Linksku avatar Feb 06 '24 09:02 Linksku

I've resolved it like this...

In my code I've created a method where I try and check if the window.gapiResolve property is defined or not. If defined then it's probably loaded correctly and vice versa...

async waitForGapiResolve() {
    return new Promise((resolve, reject) => {
      const intervalId = setInterval(() => {
        if (window['gapiResolve']) {
          clearInterval(intervalId);
          resolve(true); // gapiResolve is available
        } else {
          console.log('waiting for 100ms more...');
        }
      }, 100); // Check every 100ms
  
      // Set a maximum timeout 
      setTimeout(() => {
        clearInterval(intervalId);
        reject(new Error('Gapi resolve timed out')); 
      }, 3000); // Example 3-second timeout
    });
  }

Then the code will run it before running the signIn method

await this.waitForGapiResolve();
const googleUser = await GoogleAuth.signIn();

Monomachus avatar Mar 15 '24 12:03 Monomachus