Reputation: 11
I have some troubles to display list of accesible calendar from Google Calendar via Google API. I use JavaScript and AJAX.
What methods do I need to use? I found only event`s related methods, but not for display description of calendar.
Thank you!
Upvotes: 1
Views: 4316
Reputation: 282845
Here's some code I just wrote:
kb.loadAsync('https://apis.google.com/js/client.js', 'onload', 'gapi').then(gapi => {
gapi.auth.authorize({
client_id: __GOOGLE_CALENDAR_API_KEY__,
scope: 'https://www.googleapis.com/auth/calendar',
immediate: true,
}, authResult => {
if(authResult && !authResult.error) {
gapi.client.load('calendar','v3', () => {
gapi.client.calendar.calendarList.list({
maxResults: 250,
minAccessRole: 'writer',
}).execute(calendarListResponse => {
let calendars = calendarListResponse.items;
console.log(calendars.map(cal => cal.summary));
});
});
} else {
console.log('unauthorized');
}
});
});
kb.loadAsync
is a helper function I wrote; looks like this:
/**
* Helps load Google APIs asynchronously.
*
* @param {string} source
* @param {string} callbackParam
* @param {string=} globalName
* @returns {Promise}
*/
export function loadAsync(source, callbackParam, globalName) {
return new Promise((resolve,reject) => {
let callbackFunc = Math.random().toString(36);
window[callbackFunc] = () => {
resolve(window[globalName]);
delete window[callbackFunc];
};
let sep = source.includes('?') ? '&' : '?';
$script(`${source}${sep}${encodeURIComponent(callbackParam)}=${encodeURIComponent(callbackFunc)}`);
});
}
It uses scriptjs. Unfortunately scriptjs' callback fires too early -- Google loads some more junk after client.js has downloaded, so it isn't quite ready to run even after it's "ready"! You have to use Google's onload
parameter.
You don't need all those dependencies if you just to use a bunch of <script>
tags, but I prefer me some async functions.
Upvotes: 1
Reputation: 783
To get a basic working model you can follow the quickstart example on the calendar API site
The example has a function called listUpcomingEvents() to get events on the "primary" calendar. To get the list of calendars use the following method:
function listCalendars()
{
var request = gapi.client.calendar.calendarList.list();
request.execute(function(resp){
var calendars = resp.items;
console.log(calendars);
});
}
Upvotes: 8