3

I have the Google Signin Button properly rendering inside my react component using the gapi.signin2.render method on the latest Google platform web-client api (https://apis.google.com/js/platform.js).

But, for the life of me, I can't get it to properly call my success or failure callbacks.

The button renders, clicking the button opens the account auth window, clicking a Google account closes the window, but no callback.

function myCallback(obj) {
  console.log(obj);
}

gapi.signin2.render('my-signin2', {
  scope: 'https://www.googleapis.com/auth/plus.login',
  width: 200,
  height: 50,
  longtitle: true,
  theme: 'dark',
  onsuccess: myCallback,
  onfailure: myCallback
});

I have no clue what I'm missing here. Any help is much appreciated!

Matt Martin
  • 513
  • 2
  • 7
  • 18

2 Answers2

2

The docs tell you to add this:

<div class="g-signin2" data-onsuccess="onSignIn"></div>

But that won't work with React. I found that removing data-onsuccess and class (className) from the div did the trick. So if you have something like this:

  useEffect(() => {
    window.gapi.signin2.render('gs2', {
      'scope': 'https://www.googleapis.com/auth/plus.login',
      'width': 200,
      'height': 50,
      'longtitle': true,
      'theme': 'dark',
      'onsuccess': onGoogleSignIn
    });
  }, []);

  const onGoogleSignIn = user => {
    console.log('user', user);
  }

then your jsx for the google button can simply be this:

<div id="gs2"></div>

note that I removed the class and added id because gapi.signin2.render is looking for an id.

The caveat is that now you lose the styling. Unfortunately, addingclassName="g-signin2" back to the div actually breaks the callbacks.

Rokit
  • 977
  • 13
  • 23
0

When you created your client ID you set your url to , let us say 'localhost'. Now you running you code on, let us say 'localhost:8080'. your 'myCallback' is not running because there is no data coming back from google api, the data is sent to the trusted url that you specified which is 'localhost'. The idea is simple, the request can come from anywhere, but google api is sending the data to your trusted url as a security step, if the request is coming from there you get it, if it is not someone is trying to hack using your client ID.

  • localhost is actually used as an example in the Google docs: https://developers.google.com/identity/sign-in/web/server-side-flow – TomTom101 Jun 04 '19 at 10:34