【问题标题】:detect error: "popup_blocked_by_browser" for google auth2 in javascript检测错误:javascript 中 google auth2 的“popup_blocked_by_browser”
【发布时间】:2018-01-19 08:15:25
【问题描述】:

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

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

使用 window.open() 的样本不好,因为它们打开了无用的窗口。 我看到很多人都在搜索这个。

有什么建议吗?

【问题讨论】:

    标签: google-app-engine popup popup-blocker


    【解决方案1】:

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

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

    希望这会有所帮助!

    【讨论】:

    【解决方案2】:

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

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

    __

    我曾经在 click 事件监听器中有这个下一个代码:

    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”的异步方式,这是谷歌文档所说的。

    我改成:

    // 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) { ... });
    

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

    【讨论】:

    • 我希望谷歌文档能说明哪些方法是异步的或同步的。 gapi.auth2.init 是同步的完全不明显...感谢您的回答!
    • gapi.auth2.init异步。它返回一个Promise-like GoogleAuth 对象,根据文档:developers.google.com/api-client-library/javascript/reference/…
    • 或者,将gapi.load() 部分添加到脚本标签<script src="https://apis.google.com/js/platform.js" async defer onload="gapi.load('auth2');"></script>
    【解决方案3】:

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

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

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

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

    【讨论】:

      【解决方案4】:

      更新:

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

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

      答案:

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

      错误(弹出被浏览器阻止)(没有回调功能):

      .init({ client_id: main.clientId })
      

      正确像魅力一样工作:

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

      【讨论】:

      • @MarcoA.Braghim 我用 firebase 解决方案更新了答案
      • 猜你错过了什么。这篇文章是关于 Web 浏览器的这个错误...
      猜你喜欢
      • 2017-07-28
      • 1970-01-01
      • 1970-01-01
      • 2011-05-30
      • 2015-02-02
      • 2015-09-23
      • 2022-07-08
      • 2013-11-13
      • 1970-01-01
      相关资源
      最近更新 更多