login - Google SignIn State -
i'm trying build google signin button website. i'm trying avoid using built-in button. code below works sign in user, can't figure out how make webpage remember they're signed in when user refreshes page, or leaves site , comes back.
using chrome's developer tools, can see there's entry https://accounts.google.com
under both local storage
, session storage
. seem more or less contain same information, including user's validated token.
what don't understand how gapi.auth2.init()
function recognize , use token. documentation doesn't seem cover it.
<html> <head> <title>login test</title> <script src="http://code.jquery.com/jquery-2.1.4.js"></script> <script src="https://apis.google.com/js/platform.js?onload=renderbutton" async defer></script> </head> <script> var googleuser = {}; function renderbutton() { gapi.load('auth2', function(){ auth2 = gapi.auth2.init({ client_id: 'my_credentials.apps.googleusercontent.com', }); attachsignin(document.getelementbyid('custombtn')); }); }; function attachsignin(element) { auth2.attachclickhandler(element, {}, function(googleuser) { document.getelementbyid('name').innertext = "signed in: " + googleuser.getbasicprofile().getname(); }, function(error) { alert(json.stringify(error, undefined, 2)); } ); } </script> <body> <div id="gsigninwrapper"> <span class="label">sign in with:</span> <input type="button" id="custombtn" value="google"></input> </div> <p id="name"></p> </body> </html>
you can use listeners. relevant part:
// listen sign-in state changes. auth2.issignedin.listen(signinchanged); // listen changes current user. auth2.currentuser.listen(userchanged);
you can date values
var issignedin = auth2.issignedin.get(); var currentuser = auth2.currentuser.get();
to strictly detect returning users can do:
var auth2 = gapi.auth2.init(config); auth2.then(function() { // @ point initial authentication done. var currentuser = auth2.currentuser.get(); });
when comes code do:
auth2 = gapi.auth2.init(config); auth2.currentuser.listen(onuserchange); auth2.attachclickhandler(element, {});
this way changes in sign-in state passed onuserchange (this includes returning users, new sign-ins attachclickhandler, new sign-ins different tab).
Comments
Post a Comment