Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect error: "popup_blocked_by_browser" for google auth2 in javascript

After lot of googling didn't find solution how to catch error of window popup blocker for google auth2

getting an error in console error: "popup_blocked_by_browser". all I want is to do is tell user that pop up should be enabled for auth.

samples using window.open() are not good, since they open useless window. As I see a lot of people searching for this.

Any advice?

like image 391
aleXela Avatar asked Aug 10 '17 22:08

aleXela


3 Answers

Was having same problem. Seems browser(s) (or at least chrome) will block any "window.open" call which it was invoked not as part of a user interaction.

Refer to here for a deeper explanation.

__

I used to have this next code inside click event listener:

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

Note the asynchronous way of loading 'auth2', which is how google docu says.

I changed it to:

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

Then, inside click event handler, we can do:

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

... so browser does not block google login popup

like image 92
Oxcarga Avatar answered Oct 31 '22 15:10

Oxcarga


Finally!! signIn() method uses JS Promise. So code can be used is:

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

Hope this will help!

like image 35
aleXela Avatar answered Oct 31 '22 15:10

aleXela


In your constructor (service) or ngOnInit (for component) do the following:

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

Then, in your login function, call:

    this.googleAuth.signIn()
  .then((user) => {
      this.signInSuccessHandler(user as GoogleUser);
    },
    (error) => console.error(error));
like image 33
Yuvals Avatar answered Oct 31 '22 17:10

Yuvals