Reputation: 687
I'm trying to implement a custom google login button in index.html which works perfectly on page load but does not when the page is reloaded or redirected from another page. On page load, console statements 1,2 and 3 are printed sequentially automatically and 4 is printed on sign-in. When redirected from another page or refreshed the console only prints 1 and 2 and the button is not clickable. The script to include gapi is included by
<script src="https://apis.google.com/js/api:client.js"></script>
in index.html. I'm using AngularJS if that has something to do with this.
var googleUser = {};
var startApp = function() {
console.log("1");
gapi.load('auth2', function(){
// Retrieve the singleton for the GoogleAuth library and set up the client.
console.log("2");
auth2 = gapi.auth2.init({
client_id: '*************.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
// Request scopes in addition to 'profile' and 'email'
scope: 'profile email'
});
setTimeout(function(){
attachSignin(document.getElementById('g_login'));
}, 1000);
// attachSignin(document.getElementById('g_login'));
});
};
function attachSignin(element) {
console.log("3");
auth2.attachClickHandler(element, {},
function(googleUser) {
console.log("4");
document.getElementById('name').innerText = "Signed in: " +
googleUser.getBasicProfile().getName();
angular.element(document.getElementById('status')).scope().googleLogin(googleUser.getAuthResponse().id_token);
}, function(error) {
alert(JSON.stringify(error, undefined, 2));
});
}
startApp();
</script>
Upvotes: 4
Views: 5902
Reputation: 687
Solved.
Global variable 'auth2' is automatically initialised each time the page is loaded and can be used to sign users in.
The script is called as:
<script src="https://apis.google.com/js/api:client.js?onload=onLoadCallback" async defer></script>
<script>
var auth2;
var googleUser = {};
var auth3;
window.onLoadCallback = function(){
gapi.load('auth2', function () {
auth2 = gapi.auth2.init({
client_id: '**********.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
// Request scopes in addition to 'profile' and 'email'
scope: 'profile email'
});
auth3 = true;
startApp();
})
}
var startApp = function() {
element = document.getElementById('g_login');
auth2.attachClickHandler(element, {},
function(googleUser) {
console.log("4");
document.getElementById('name').innerText = "Signed in: " +
googleUser.getBasicProfile().getName();
angular.element(document.getElementById('status')).scope().googleLogin(googleUser.getAuthResponse().id_token);
}, function(error) {
console.log("5");
alert(JSON.stringify(error, undefined, 2));
});
};
if (auth3)
startApp();
</script>
Upvotes: 4