反应谷歌登录返回错误“idpiframe_initialization_failed”

我尝试使用 react-google-login 包实现谷歌登录。我已将客户端 ID 也放入正确的 URL http://localhost:3000 and https://localhost:3000 。但是我遇到了错误消息“idpiframe_initialization_failed”的问题,详细信息如下: **You have created a new client application that uses libraries for user authentication or authorization that will soon be deprecated. New clients must use the new libraries instead; existing clients must also migrate before these libraries are deprecated** 。我真的很困惑。请花点时间帮助我解决这个问题。谢谢你。 enter image description here


            <header className="App-header">
                <h1>React Google Login App</h1>
                <div>
                    {loginData ? (
                        <div>
                            <h3>You logged in as {loginData.email}</h3>
                            <button onClick={handleLogout}>Logout</button>
                        </div>
                    ) : (
                        <GoogleLogin
                            clientId={"846142574809-apbj2h6v9upultr3qvfskn6kfght9udb.apps.googleusercontent.com"}
                            buttonText="Log in with Google"
                            onSuccess={handleLogin}
                            onFailure={handleFailure}
                            cookiePolicy={'single_host_origin'}
                        ></GoogleLogin>
                    )}
                    <GoogleLogout clientId='846142574809-apbj2h6v9upultr3qvfskn6kfght9udb.apps.googleusercontent.com' buttonText='logout' onLogoutSuccess={handleoutSuccess}></GoogleLogout>

                </div>
            </header>
        </div>``` 

 `` `
stack overflow React google login return error "idpiframe_initialization_failed"
原文答案

答案:

作者头像

Google 登录是迁移到新的 google 服务标识 SDK,您可以在 https://developers.google.com/identity/gsi/web 上实现它

或者您可以使用 @react-oauth/google 它正在使用新的 SDK

作者头像

我们将停止使用适用于 Web 的 Google 登录 JavaScript 平台库。在 2023 年 3 月 31 日弃用日期之后,该库将无法下载。相反,请使用新的 Google 网络身份服务。默认情况下,现在阻止新创建的客户端 ID 使用旧平台库,现有客户端 ID 不受影响。在 2022 年 7 月 29 日之前创建的新客户 ID 可以设置 plugin_name 以启用 Google 平台库。

Google Sign-In JavaScript client reference

作者头像

React google login 使用的是旧版 google,将于 2023 年 3 月 31 日弃用。详情 here 。检查实现 here

您可以使用支持较新版本的新库作为上面的注释,例如 https://www.npmjs.com/package/@react-oauth/google

您也可以自己实现:首先您需要从 google 加载脚本。详细链接:

https://developers.google.com/identity/gsi/web/guides/client-library

然后你需要做一些设置并渲染谷歌按钮:


export function GoogleLoginButton({
  onSuccess,
  onError,
  type = 'standard',
  theme = 'outline',
  size = 'large',
  text,
  shape,
  logoAlignment,
  width,
  locale,
  ...props
}: GoogleLoginProps): React.ReactElement {
    const [isOAuthClientLoaded, setIsOAuthClientLoaded] = React.useState(false);

  const btnContainerRef = useRef<HTMLDivElement>(null);

  const onSuccessRef = useRef(onSuccess);
  onSuccessRef.current = onSuccess;

  const onErrorRef = useRef(onError);
  onErrorRef.current = onError;

  useEffect(() => {
    const scriptTag = document.createElement('script');

    scriptTag.src = 'https://accounts.google.com/gsi/client';
    scriptTag.async = true;
    scriptTag.defer = true;

    scriptTag.onload = () => {
      setIsOAuthClientLoaded(true);
    };

    scriptTag.onerror = () => {
      setIsOAuthClientLoaded(false);
    };

    document.body.appendChild(scriptTag);

    return () => {
      document.body.removeChild(scriptTag);
    };
  }, []);

  useEffect(() => {
    if (!isOAuthClientLoaded) {
      return;
    }

    window.google?.accounts.id.initialize({
      client_id: clientId,
      callback: (credentialResponse: OAuthCredentialResponse): void => {
        if (!credentialResponse.clientId || !credentialResponse.credential) {
          onErrorRef.current?.(
            new Error('Client id is invalid when initializing')
          );

          return;
        }

        onSuccessRef.current(credentialResponse);
      },
      ...props
    });

    window.google?.accounts.id.renderButton(btnContainerRef.current!, {
      type,
      theme,
      size,
      text,
      shape,
      logo_alignment: logoAlignment,
      width,
      locale
    });
  }, [
    onSuccess,
    onError,
    clientId,
    type,
    theme,
    size,
    text,
    shape,
    logoAlignment,
    width,
    locale,
    props,
    isOAuthClientLoaded
  ]);

  return <div ref={btnContainerRef} />;
}
作者头像

I tried many solutions but they did not work for me. So I have an easy solution that helps me fix it.

  1. Install gapi-script (https://www.npmjs.com/package/gapi-script).

    npm install --save gapi-script

  2. Use it in component.

      import { loadGapiInsideDOM } from "gapi-script";
      ...
      useEffect(() => {
        (async () => {
          await loadGapiInsideDOM();
        })();
      });