You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

接入Google Identity Services后登录回调未触发无法获取用户信息求助

问题排查及解决方案

核心问题原因

你混用了新旧两套Google登录API的实现逻辑,且React组件渲染时机和初始化脚本执行时机不匹配,导致回调无法触发:

  • 你加在buttonDiv上的class="g-signin2"和data-onsuccess="onSignIn"是旧版Google Sign-In API的属性,会让GSI库优先走旧版回调逻辑,你没有定义onSignIn函数,自然不会有日志输出。
  • 你用的是React项目,window.onload触发时Navbar组件大概率还没挂载完成,document.getElementById("buttonDiv")找不到元素,你写的renderButton方法执行失败,实际显示的登录按钮是旧属性触发渲染的旧版按钮,和你配置的handleCredentialResponse没有关联。

具体解决步骤

  • 第一步:修改Navbar.js代码,删除所有旧版API的遗留属性,仅保留空的容器div:
<li className='nav-item'>
  <div id="buttonDiv"></div>
</li>
  • 第二步:把GSI初始化逻辑从index.html的全局脚本移到Navbar组件的useEffect钩子中,保证组件挂载完成后再执行初始化操作:
import { useEffect } from 'react';

const Navbar = () => {
  // 组件挂载完成后执行GSI初始化
  useEffect(() => {
    // 先判断GSI脚本是否加载完成、全局google对象是否存在
    if (window.google) {
      const handleCredentialResponse = (response) => {
        console.log('hello, world');
        console.log("Encoded JWT ID token: " + response.credential);
      }

      window.google.accounts.id.initialize({
        client_id: 'MY_GOOGLE_ID.apps.googleusercontent.com',
        callback: handleCredentialResponse
      });
      
      // 显示一键登录弹窗
      window.google.accounts.id.prompt();
      
      // 渲染登录按钮
      window.google.accounts.id.renderButton(
        document.getElementById("buttonDiv"),
        { theme: 'outline', size: 'large' }
      );
    }
  }, []);

  return (
    {/* 导航栏其他代码 */}
    <li className='nav-item'>
      <div id="buttonDiv"></div>
    </li>
    {/* 导航栏其他代码 */}
  )
}

export default Navbar;
  • 第三步:额外校验配置项,确保Google Cloud控制台的OAuth客户端配置中,你当前的站点地址(本地测试要加http://localhost:对应端口号)已经被添加到「JavaScript 源」列表中,否则GSI会静默拦截回调。

内容的提问来源于stack exchange,提问作者Paolo Di Pietro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:30:00