Samuele B.
Samuele B.

Reputation: 658

JavaScript - Open a popup window and wait for it to be closed

I'm implementing Google OAuth2 authentication flow by generating the auth URL on my backend, opening it up as a popup window on my frontend, and then letting the backend do its thing once the user has auth'd inside of the popup window.

I'm looking for a way to know when the popup was closed by the user.

This is the flow I have in mind:

I don't know how to await the closure of this external window. I know it's possible because Google gapi client does it, but unfortunately the source code for that project isn't public.

This is how I'm opening the popup:

async logIn() {
    const url = await this.getAuthUrl(); // request url from backend
    window.open(url, "", "popup=true"); // open popup using that url
}

I would like to be able to do something like this:

async logIn() {
    const url = await this.getAuthUrl(); // request url from backend
    await openPopup(url)
    // continue with application flow
}

How do you implement this?

Upvotes: 0

Views: 694

Answers (1)

Maksim
Maksim

Reputation: 31

As far as I understand from your description, google closes the authentication window itself. In this case, you can use setInterval

async logIn() {
  const url = await this.getAuthUrl(); // request url from backend
  const authPopup = window.open(url, "", "popup=true"); // open popup using that url
  const intervalId = setInterval(() => {
    if (authPopup?.closed) {
      clearInterval(intervalId);
      // continue with application flow
    }
  }, 1000);
}

Upvotes: 0

Related Questions