Monitoring the user's session state

After the Google Sign-In client has been initialized, you can attach handlers that check various attributes and methods of the client to determine the user's session state. You can use information returned by the client object to help sync your site's user experience across multiple tabs and devices for your user.

The following code demonstrates using the 2.0 client method attachClickHandler to create a callback that either silently finishes sign-in for the user, or prompts the user to re-authorize based on the state of the user's session.

  /** 
  
 * 
  
 The 
  
 Sign 
 - 
 In 
  
 client 
  
 object 
 . 
  
 */ 
 var 
  
 auth2 
 ; 
 /** 
  
 * 
  
 Initializes 
  
 the 
  
 Sign 
 - 
 In 
  
 client 
 . 
  
 */ 
 var 
  
 initClient 
  
 = 
  
 function 
 () 
  
 { 
  
 gapi 
 . 
 load 
 ( 
 'auth2' 
 , 
  
 function 
 (){ 
  
 /** 
  
 * 
  
 Retrieve 
  
 the 
  
 singleton 
  
 for 
  
 the 
  
 GoogleAuth 
  
 library 
  
 and 
  
 set 
  
 up 
  
 the 
  
 * 
  
 client 
 . 
  
 */ 
  
 auth2 
  
 = 
  
 gapi 
 . 
 auth2 
 . 
 init 
 ({ 
  
 client_id 
 : 
  
 'CLIENT_ID.apps.googleusercontent.com' 
  
 }); 
  
 // 
  
 Attach 
  
 the 
  
 click 
  
 handler 
  
 to 
  
 the 
  
 sign 
 - 
 in 
  
 button 
  
 auth2 
 . 
 attachClickHandler 
 ( 
 'signin-button' 
 , 
  
 {}, 
  
 onSuccess 
 , 
  
 onFailure 
 ); 
  
 }); 
 }; 
 /** 
  
 * 
  
 Handle 
  
 successful 
  
 sign 
 - 
 ins 
 . 
  
 */ 
 var 
  
 onSuccess 
  
 = 
  
 function 
 ( 
 user 
 ) 
  
 { 
  
 console 
 . 
 log 
 ( 
 'Signed in as ' 
  
 + 
  
 user 
 . 
 getBasicProfile 
 () 
 . 
 getName 
 ()); 
  
 }; 
 /** 
  
 * 
  
 Handle 
  
 sign 
 - 
 in 
  
 failures 
 . 
  
 */ 
 var 
  
 onFailure 
  
 = 
  
 function 
 ( 
 error 
 ) 
  
 { 
  
 console 
 . 
 log 
 ( 
 error 
 ); 
 }; 
 
Create a Mobile Website
View Site in Mobile | Classic
Share by: