How do I initialise Google Sign in with no login button?

Viewed 10110

The below code works as a simple test page that uses Google sign in:

<html lang="en">
  <head>

    <script type="text/javascript">

        function onGapiLoaded() {
            auth = gapi.auth2.init({
                client_id: "REPLACE_WITH_YOUR_ID",
                scope: "profile email"

            });

            console.log( "signed in: " + auth.isSignedIn.get() );

            auth.isSignedIn.listen( function(signedIn){ console.log( "signedin: " + signedIn ) } );

            gapi.signin2.render( "signInButton", {
                'width': 230,
                'height': 50,
                'longtitle': true,
                'theme': 'dark',
                'onsuccess': onSignIn
            } );
        }

          function onSignIn(googleUser) {
            // Useful data for your client-side scripts:
            var profile = googleUser.getBasicProfile();
            console.log("Name: " + profile.getName());
          };


    </script>

    <script src="https://apis.google.com/js/platform.js?onload=onGapiLoaded" async defer></script>

  </head>
  <body>
    <div id="signInButton" class="g-signin2"></div>
  </body>
</html>

However if I remove the class="g-signin2" from the signin button, or remove the button completely not only does the button disappear but the whole sign in library stops working - I get an uncaught exception:

Cannot read property 'init' of undefined

when I try to call gapi.auth2.init and the user is not logged in. It seems that the auth library relies on a button being present in the dom to initialise.

I am planning to incorporate this in my Angular app that will initialise the auth lib in a service before any button appears on the stage. If the user is logged in already no login button will appear. Based on the behaviour here I will not be able to use this lib without having a button in the DOM which seems rather constricting.

2 Answers
Related