如何确定用户是否关闭了google auth2.signIn()窗口?

Dee*_*eep 7 javascript google-api google-authentication google-signin google-identity

我使用这个实现auth,当用户点击按钮登录并且auth2帐户选择/登录窗口显示时,我当前在React中显示加载图标.

然而,如果用户关闭窗口,似乎没有任何事件被触发,即返回一个承诺的signIn()函数永远不会解析,我会认为如果窗口关闭,谷歌将为此承诺返回错误.因此,我无法停止显示加载程序图标并重新显示登录菜单.

我想知道是否有人有这个解决方案?

Fen*_*wan 5

我尝试修改调用 Google OAuth 2.0 窗口的代码。
您只需要添加额外的 AJAX 方法来覆盖 Google OAuth 错误结果。

gapi.auth2.getAuthInstance().signIn()
Run Code Online (Sandbox Code Playgroud)

改成这个,

gapi.auth2.getAuthInstance().signIn().then(function(response){
    //If Google OAuth 2 works fine
    console.log(response);
}, function(error){
    //If Google OAuth 2 occured error
    console.log(error);
    if(error.error === 'popup_closed_by_user'){
        alert('Oh Dude, Why you close authentication user window...!');
    }
});
Run Code Online (Sandbox Code Playgroud)

就是这样...

有关 Google OAuth 2.0 信息的更多详细信息,您可以访问此链接。
https://developers.google.com/api-client-library/javascript/samples/samples#authorizing-and-making-authorized-requests
JavaScript 示例代码:https :
//github.com/google/google-api- javascript-client/blob/master/samples/authSample.html


cla*_*ass 1

尽管 API 提供了一种检测用户何时单击“拒绝”按钮的机制,但没有内置方法来检测用户突然关闭弹出窗口(或退出 Web 浏览器、关闭计算机等) 。如果您想以缩小的范围重新提示用户(例如,您请求“电子邮件”但只需要个人资料,并且将允许用户继续操作而不向您提供他们的电子邮件),则提供拒绝条件。

如果登录回调的响应包含错误 ,access_denied则表明用户单击了拒绝按钮:

function onSignInCallback(authResult) {
  if (authResult['error'] && authResult['error'] == 'access_denied') {
    // User explicitly denied this application's requested scopes
  }
}
Run Code Online (Sandbox Code Playgroud)

您应该能够在不检测窗口是否关闭的情况下实现登录;几乎所有 Google+ 示例应用程序都证明了这一点。简而言之,您应该避免使用旋转器,而应该隐藏经过身份验证的 UI,直到用户成功登录。

不建议您这样做,但要实现弹出窗口关闭的检测,您可以执行诸如覆盖全局调用之类的window.open操作,然后在 window.unload 或 poll 中检测窗口是否在未经用户身份验证的情况下关闭:

var lastOpenedWindow = undefined;
window.open = function (open) {
    return function (url, name, features) {
        // set name if missing here
        name = name || "default_window_name";
        lastOpenedWindow = open.call(window, url, name, features);
        return lastOpenedWindow;
    };
}(window.open);

var intervalHandle = undefined;
function detectClose() {
  intervalHandle = setInterval(function(){
    if (lastOpenedWindow && lastOpenedWindow.closed) {
      // TODO: check user was !authenticated
      console.log("Why did the window close without auth?");
      window.clearInterval(intervalHandle);
    }
  }, 500);
}
Run Code Online (Sandbox Code Playgroud)

请注意,正如我所实现的那样,该机制是不可靠的并且受竞争条件的影响。

  • 您好,感谢您的回复,但是 Facebook 为何提供此功能?我的页面上有 facebook 和 google auth 作为选项,如果用户关闭弹出窗口,facebook 的登录方法将解析为失败。对我来说,这似乎是谷歌方面的一个疏忽。微调器只是一个 ux 的东西,用于向用户指示登录过程已经开始(以防他们确实单击另一个窗口并失去对登录窗口的跟踪)。 (4认同)