MOHANRAJ_G 021
MOHANRAJ_G 021

Reputation: 41

How to prevent CORS issue when accessing window object in popup window?

I am doing oauth authentication using discord api, I'm following this blog

I'm able to get the auth code from the url but also I'm getting CORS issue

SecurityError: Blocked a frame with origin "http://localhost:3000" from accessing a cross-origin frame.

Is there a way to prevent this?

The code:

    const CLIENT_URL = window.location.href;
    const popup = window.open(
      ` https://discord.com/oauth2/authorize?response_type=code&client_id=*******&scope=identify&guilds.join&state=*******&redirect_uri=http://localhost:3000&prompt=consent
    `,
      "popup",
      "popup=true"
    );

    const checkPopup = setInterval(() => {
      if (popup.window.location.href.includes(CLIENT_URL)) {
        const params: any = new Proxy(
          new URLSearchParams(popup.window.location.search),
          {
            get: (searchParams, prop) => searchParams.get(prop),
          }
        );
        let value = params?.code;
        console.log(value);
        popup.close();
      }

      if (!popup || !popup.closed) return;
      clearInterval(checkPopup);
    }, 1000);
  };

Upvotes: 2

Views: 862

Answers (1)

Jupiter pluvius
Jupiter pluvius

Reputation: 36

maybe add the try/catch in setInterval is available.

const checkPopup = setInterval(() => {
   try {
      if (popup.window.location.href.includes(CLIENT_URL)) {
        const params: any = new Proxy(
          new URLSearchParams(popup.window.location.search),
          {
            get: (searchParams, prop) => searchParams.get(prop),
          }
        );
        let value = params?.code;
        console.log(value);
        popup.close();
      }

      if (!popup || !popup.closed) return;
      clearInterval(checkPopup);
    } catch (e) {
      // something
    }
}, 1000);

Upvotes: 0

Related Questions