javascriptgoogle-oauthgoogle-signingoogle-identityreact-google-login

Google Identity Service Oauth2 detect if consent pop-up is closed


👋 I am using Google Identity Services, and facing some problems. Have a look at the function below to loginUser and get the access_token:

const client = (window as any).google.accounts.oauth2.initTokenClient({
  client_id: process.env.GOOGLE_CLIENT_ID,
  scope: `profile email`,
  callback: '' // defined at request time
});

const loginUser = async () => {
  const tokenResponse = await new Promise<TokenResponse>((resolve, reject) => {
    try {
      // Settle this promise in the response callback for requestAccessToken()
      client.callback = (resp) => {
        if (resp.error !== undefined) {
          reject(resp);
        }
        resolve(resp);
      };
      // requesting access token
      client.requestAccessToken({ prompt: 'consent' });
    } catch (err) {
      console.log(err)
    }
  });
  return tokenResponse;
}

Invoking loginUser() causes a new pop-up.

Is there a way we could detect if the user has closed the pop-up?


Solution

  • I think you can do something in the "error_callback". You can find details at: Handle Errors

    const client = google.accounts.oauth2.initCodeClient({
      client_id: 'YOUR_GOOGLE_CLIENT_ID',
      scope: 'https://www.googleapis.com/auth/calendar.readonly',
      ux_mode: 'popup',
      callback: myCallback,
      error_callback: myErrorCallback  // You can do something when popup window closed
    });