简体   繁体   English

在弹出窗口window中访问window object时如何防止CORS问题?

[英]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我正在使用 discord api 进行 oauth 身份验证,我正在关注此博客

I'm able to get the auth code from the url but also I'm getting CORS issue我能够从 url 获得授权码,但我也遇到了 CORS 问题

SecurityError: Blocked a frame with origin "http://localhost:3000" from accessing a cross-origin frame . 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);
  };

maybe add the try/catch in setInterval is available.也许在 setInterval 中添加try/catch是可用的。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM