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

Google Sign-In迁移至FedCM:代码实现疑问及迁移方案咨询

迁移Google Sign-In至FedCM的具体代码修改方案

你可以通过以下两种方式任选其一完成迁移,两种方式都能满足谷歌要求的FedCM启用规则:

方式一:通过HTML属性启用FedCM(适合使用默认Google登录按钮的场景)

如果你的页面中使用了Google官方提供的默认登录按钮(类似 <div class="g-signin2" data-onsuccess="onSignIn"></div>),直接给该按钮元素添加 data-use_fedcm_for_prompt="true" 属性即可:

<div class="g-signin2" data-onsuccess="onSignIn" data-use_fedcm_for_prompt="true"></div>

你现有代码中的 <meta name='google-signin-client_id' content='$GLOBALS[google_signin_client_id].apps.googleusercontent.com'> 标签无需修改,可继续保留。

方式二:通过JavaScript初始化配置启用FedCM(适合手动初始化auth2的场景)

你当前代码里的 gapi.auth2.init() 未传入任何配置,迁移指南中提到的IdConfiguration对象就是这个init方法的参数对象。你需要在初始化时传入客户端ID和FedCM启用标志:

修改后的完整JavaScript代码:

function onLoad() {
    if (!gapi.auth2) {
        gapi.load('auth2', function() {
            gapi.auth2.init({
                // 与meta标签中的客户端ID保持一致
                client_id: '$GLOBALS[google_signin_client_id].apps.googleusercontent.com',
                // 开启FedCM支持的布尔标志
                use_fedcm_for_prompt: true
            });
        });
    }
}

function onSignIn(googleUser) {
    var profile = googleUser.getBasicProfile();
    var redirectUrl = '?followup=$followup&id='+encodeURIComponent(profile.getId())+'&name='+encodeURIComponent(profile.getName())+'&email='+encodeURIComponent(profile.getEmail())+'&image='+encodeURIComponent(profile.getImageUrl());
    window.location = redirectUrl;
}

注:采用这种方式时,你可以移除页面中的 <meta name='google-signin-client_id'> 标签,因为客户端ID已经通过初始化配置传入。

额外说明

  • 你的onSignIn函数不需要修改:FedCM仅调整登录请求的触发逻辑(适配现代浏览器隐私规范,规避第三方Cookie限制),不会影响用户信息的获取流程。
  • 验证方式:使用Chrome 116+、Edge 116+等支持FedCM的浏览器测试登录,确认弹出的是符合FedCM规范的登录界面,而非旧版OAuth弹窗。

内容的提问来源于stack exchange,提问作者Erel Segal-Halevi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:54:54