Google身份验证新方法:如何添加onSignIn()回调函数
新版Google身份验证添加onSignIn回调的方法
你当前的新版代码设置了data-ux_mode="redirect",这种模式下data-onsuccess是无效的——因为认证成功后页面会直接跳转到data-login_uri指定的地址,前端的onSignIn函数没有执行机会。根据你的需求,有两种解决方案:
方案一:切换为Popup模式(保留前端回调)
这种模式下认证过程在弹窗中完成,不会跳转页面,能直接触发onSignIn回调。修改代码如下:
<script src="https://accounts.google.com/gsi/client" async defer></script> <!-- 调整ux_mode为popup,移除不需要的data-login_uri --> <div id="g_id_onload" data-onsuccess="onSignIn" data-client_id="myid" data-ux_mode="popup"> </div> <div class="g_id_signin" data-type="standard"></div> <div class="flex-container"> <div class="g-signin1"> <a href="#" onclick="signOut();"> <img src="images/signout.jpg" width="120" id="imgout" alt="SignOut" /> </a> </div> </div> <!-- 全局定义onSignIn函数,注意新版回调参数与旧版不同 --> <script> function onSignIn(response) { // 解析JWT令牌获取用户信息 const jwtPayload = JSON.parse(atob(response.credential.split('.')[1])); console.log("认证成功,用户信息:", jwtPayload); // 这里添加你原onSignIn函数中的业务逻辑 } function signOut() { // 新版Google登录退出方法 google.accounts.id.disableAutoSelect(); // 可选:清除本地存储的用户数据、更新页面状态等 } </script>
方案二:保留Redirect模式(在跳转页面处理逻辑)
如果必须使用跳转模式(比如需要后端处理认证),原页面的onSignIn无法触发,需要在跳转后的页面(http://localhost:64459)中处理认证结果:
1. 原页面代码保持不变:
<script src="https://accounts.google.com/gsi/client" async defer></script> <div id="g_id_onload" data-client_id="myid" data-ux_mode="redirect" data-login_uri="http://localhost:64459"> </div> <div class="g_id_signin" data-type="standard"></div> <div class="flex-container"> <div class="g-signin1"> <a href="#" onclick="signOut();"> <img src="images/signout.jpg" width="120" id="imgout" alt="SignOut" /> </a> </div> </div>
2. 在跳转后的页面(http://localhost:64459)添加处理脚本:
<script> // 获取URL中的认证凭证参数 const urlParams = new URLSearchParams(window.location.search); const credential = urlParams.get('credential'); if (credential) { // 解析JWT获取用户信息,执行原onSignIn的逻辑 const jwtPayload = JSON.parse(atob(credential.split('.')[1])); console.log("用户认证信息:", jwtPayload); // 后续业务逻辑... } </script>
注意:新版Google身份验证的回调参数与旧版不同,旧版返回
GoogleUser对象,新版返回包含JWT令牌的response对象,需要通过解析JWT获取用户数据。
内容的提问来源于stack exchange,提问作者Kemal AL GAZZAH
相关产品推荐
相关产品推荐

