【问题标题】:How to unattach gapi- auth2.attachClickHandler on a condtion如何在条件上附加 gapi-auth2.attach Click Handler
【发布时间】:2020-10-11 05:54:20
【问题描述】:

我在我的代码中使用 google auth for client (gapi) 并且我有这个 onLoad 事件:

<script>
    function onLoad() {
        gapi.load('auth2', function () {
            auth2 = gapi.auth2.init();
            var additionalParams = {};
            auth2.attachClickHandler('signinButton', additionalParams, onSignIn, onSignInFailure);
            //auth2.attachClickHandler('btnGoRegister', additionalParams, onRegisterIn, onSignInFailure);
        });
    }
</script>

正如您在上面看到的,我为我的登录按钮附加了一个点击处理程序,它工作正常。另一部分是对于注册按钮,我必须在适用于其他身份验证(如 FB)的条件下启用/禁用按钮和相关事件。

这里的问题是,一旦调用了attachClickHandler,我就无法取消附加它,因此如果我的条件不正确,则不应调用 Google 弹出屏幕(目前如果它被调用一次)无论我的情况如何,它都会一直显示)。

有人知道如何实现这一目标吗?

谢谢

【问题讨论】:

    标签: javascript jquery google-authentication google-api-js-client


    【解决方案1】:

    看起来Google Sign-In API 不支持取消附加点击处理程序的方法。另一方面,他们有一个 disconnect()signOut() 功能,但我认为它没有达到你想要的。

    一种解决方案是添加一个附加按钮,该按钮处理加载 Google Auth API 的决定并执行对 signinButton 的点击。可以使用 css 隐藏 signinButton。

    我没有启动和运行 api,但代码应该类似于:

    const GoogleSignInButton = 'signinButton';
    const GoogleDecisionGateSignInButton = 'googleDecisionGateButton';
    
    function onLoad() {
        document.getElementById(GoogleDecisionGateSignInButton).addEventListener("click", GoogleDecisionGateButton);
    }
    
    function GoogleDecisionGateButton() {
        if (ShouldUseGoogleSigninButton()) {
            LoadGoogleAuthApi();
            ClickGoogleAuthButton();
        }
    }
    
    function ShouldUseGoogleSigninButton() {
        return true; // Replace this with logic to decided if user should use Google API Auth button or not.
    }
    
    function LoadGoogleAuthApi() {
        gapi.load('auth2', function () {
            auth2 = gapi.auth2.init();
            var additionalParams = {};
            auth2.attachClickHandler(GoogleSignInButton, additionalParams, onSignIn, onSignInFailure);
            //auth2.attachClickHandler('btnGoRegister', additionalParams, onRegisterIn, onSignInFailure);
        });
    }
    
    function ClickGoogleAuthButton() {
        document.getElementById(GoogleSignInButton).click()
    } 
    

    HTML:

    <button id="signinButton" type="button"></button>
    <button id="googleDecisionGateButton" type="button"></button>
    

    CSS:

    #signinButton { display: none !important }
    

    【讨论】:

    • 抱歉,我对此进行审查有点晚了,但这很好用。感谢您的努力。
    猜你喜欢
    • 2014-02-26
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 2012-02-23
    • 1970-01-01
    • 2013-09-28
    相关资源
    最近更新 更多