I am using the Google JavaScript quickstart to connect to the Calender API.
As in the example I use the http server on port 8000
npx http-server -p 8000
So http://localhost:8000 works as intended.
The example works as described and I can authenticate. Now I am looking for a way to save this authentication for the browser. But the solutions I have found do not work.
It seems this part should handle it, but gapi.client.getToken()
is always null.
if (gapi.client.getToken() === null) {
// Prompt the user to select a Google Account and ask for consent to share their data
// when establishing a new session.
tokenClient.requestAccessToken({prompt: 'consent'});
} else {
// Skip display of account chooser and consent dialog for an existing session.
tokenClient.requestAccessToken({prompt: ''});
}
Then I tried to cache the access token.
function gisLoaded() {
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: CLIENT_ID,
scope: SCOPES,
callback: (tokenResponse) => {
access_token = tokenResponse.access_token;
*** window.localStorage.setItem("access_token", tokenResponse.access_token);***
},
});
gisInited = true;
maybeEnableButtons();
}
function maybeEnableButtons() {
if (gapiInited && gisInited) {
*** if (window.localStorage.getItem('access_token') !== null) { ***
access_token = window.localStorage.getItem('access_token');
document.getElementById('signout_button').style.visibility = 'visible';
document.getElementById('authorize_button').innerText = 'Refresh';
listUpcomingEvents()
} else {
document.getElementById('authorize_button').style.visibility = 'visible';
}
}
}
But this token always seems to be “undefined” or “null”. No matter where I call it.
tokenResponse.access_token;
gapi.client.getToken();
tokenClient.requestAccessToken();
All these calls don’t seem to help me with my goal of having the browser authenticated with the API.
Google documentation doesn’t help me much there either.
Am I missing something?
In some forums, there was also something about not working at all with localhost. Is there something to it? How else should I test such a program if not as very first on a local server?