detect error: "popup_blocked_by_browser" for google auth2 in javascript

detect error: "popup_blocked_by_browser" for google auth2 in javascript

经过大量谷歌搜索后没有找到解决方案如何捕获 window 弹出窗口阻止程序错误 google auth2

出现控制台错误:"popup_blocked_by_browser"。 我想要做的就是告诉用户应该为身份验证启用弹出窗口。

使用 window.open() 的样本并不好,因为它们打开时毫无用处 window。 正如我看到很多人在搜索这个。

有什么建议吗?

终于!! signIn() 方法使用 JS Promise。所以可以使用的代码是:

gapi.auth2.getAuthInstance().signIn().then(function(){}, function(error){ if (error) alert('please allow popup for this app')})

希望对您有所帮助!

遇到同样的问题。似乎浏览器(或至少 chrome)将阻止任何 "window.open" 调用它的调用不是作为用户交互的一部分。

请参阅 here 以获得更深入的解释。

__

我曾经在点击事件侦听器中包含以下代码:

gapi.load('auth2', function() {
  var auth2 = gapi.auth2.init({
    client_id: '.apps.googleusercontent.com',
    fetch_basic_profile: true,
    scope: 'profile'
  });
  auth2.signIn()
    .then(function() {
      var profile = auth2.currentUser.get().getBasicProfile();
      ... 
    })
    .catch(function(err) { ... });
});

注意异步加载方式 'auth2',google docu 是这样说的。

我改成了:

// way earlier, before click event can happen
// we call the gapi.load method.
gapi.load('auth2', function() {});

然后,在点击事件处理程序中,我们可以做:

var auth2 = gapi.auth2.init({
    client_id: '.apps.googleusercontent.com',
    fetch_basic_profile: true,
    scope: 'profile'
  });
  auth2.signIn()
    .then(function() { ... })
    .catch(function(err) { ... });

...所以浏览器不会阻止 google 登录弹出窗口

在您的构造函数(服务)或 ngOnInit(对于组件)中执行以下操作:

 googleAuthService.getAuth().subscribe(
  (auth) => {
    this.googleAuth = auth;
  });

然后,在您的登录函数中,调用:

    this.googleAuth.signIn()
  .then((user) => {
      this.signInSuccessHandler(user as GoogleUser);
    },
    (error) => console.error(error));

更新:

现在您需要使用 Firebase 身份验证

https://firebase.google.com/docs/auth/

答案:

对我来说,我更改了 init 方法以具有 回调函数(空函数)...方法如下:

错误(弹窗被浏览器拦截)(无回调功能):

.init({ client_id: main.clientId })

正确 像魅力一样工作:

.init({ client_id: main.clientId, () => { } })