Skip to content
Advertisement

Gmail API : Extract “code” param from the URL of a pop-up window to get the access_token details

Iam trying to authenticate gmail using OAuth2 for my web application. From the server, we return a url to the client, which then uses that to open a pop-up. The code is as shown:

        var win = window.open(data.google_oauth_url, `<h1>Gmail</h1>`, 'width=800, height=600');
          var pollTimer = setInterval(() => { 
              try {
                  const searchParams = new URL(win.document.URL).searchParams
                  console.log("url is",win.document.URL, searchParams, searchParams.get("code"))
                  if (searchParams.get("code") != -1) {
                      clearInterval(pollTimer);
                      win.close();
                  }
              } catch(e) {
                console.log("Error",e)
              }
          }, 500);

From the pop-up , i want to extract the “code” param which google returns to us after the authentication is completed. But when i try to extract the param from the client side, iam facing an error :

Uncaught DOMException: Blocked a frame with origin “https://xyz” from accessing a cross-origin frame

Is anyone aware of a solution for this, or any other ways of extracting the “code” param so i can proceed to get the access_token details. Thanks in advance.

Advertisement

Answer

The above code works, although we face CORS error while authenticating with google, once the authentication is complete, it is redirected to the provided url (web application). And then there is no more cross-origin since the domains are now same.

Ex: https://localhost was your web app url, and the redirect url.

Then it detects the authentication code and once obtained, the pop up closes automatically.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement