Instead of retrieving the singleton for the GoogleAuth library and setting up the client in my sign-in page controller, I had to initialize it in the index.html file:
<script src="https://apis.google.com/js/api:client.js?onload=start" async defer></script>
<script>
function start() {
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: 'myAppID',
cookiepolicy: 'single_host_origin'
});
});
}
</script>
That solved the logout problem. However, if the sign-in page was refreshed, its controller logic would be executed before the gapi.auth2
was defined and it wouldn't be posible to successfully attach the click handler to the sign-in button.
In order to avoid that - though not being an elegant solution -, I used $interval to wait until gapi.auth2
was initialized:
waitForAuth2Initialization = $interval(function () {
console.log("Checking...");
if (!gapi.auth2)
return;
console.log("Ok, gapi.auth2 is not undefined anymore");
var auth2 = gapi.auth2.getAuthInstance();
// Attach signin
auth2.attachClickHandler...
$interval.cancel(waitForAuth2Initialization);
}, 50);
EDIT: another possible solution is to use a promise callback for the controller logic to wait until the promise is resolved i.e. until Google API is fully loaded and gapi.auth2
is ready to use.
It is posible to achieve that by doing:
<script src="https://apis.google.com/js/api:client.js?onload=start" async defer></script>
<script>
gapiPromise = (function () {
var deferred = $.Deferred();
window.start = function () {
deferred.resolve(gapi);
};
return deferred.promise();
}());
auth2Promise = gapiPromise.then(function () {
var deferred = $.Deferred();
gapi.load('auth2', function () {
auth2 = gapi.auth2.init({
client_id: 'myAppID',
cookiepolicy: 'single_host_origin'
}).then(function () {
deferred.resolve(gapi.auth2);
});
});
return deferred.promise();
});
</script>
And then in the controller:
auth2Promise.then(function () {
console.log("Ok, gapi.auth2 is not undefined anymore");
var auth2 = gapi.auth2.getAuthInstance();
// Attach signin
auth2.attachClickHandler...
});
But, the downside of this approach is that it is slower (taking twice as much time for the click handler to be attached) than the first one using $interval
.