GCalendar: Accessing Google Calendar from JavaScript

Christian Decker wrote this in the late evening:

Introduction

Some weeks ago Google has added a nice new feature to their GData libraries: JSON data retrieval. This means that we now can retrieve data from some services of Google (Base, Blogger and Calendar for now) without having to proxy it through our servers (if you still don’t know, after thousands of posts about Cross-Domain issues, why you need to do this, just look here).

Why can we do this? Because we can just create a <script>-Element, points the src to the feed URL and tell the GData API what function to call upon load.

 
var headTag = document.getElementsByTagName('head')[0]; 
var script = document.createElement('script'); 
script.type = 'text/javascript'; 
script.src = feedurl; 
headTag.appendChild(script);

I was a bit sorry to see that Google doesn’t provide an API for Client side JavaScript. So once again, in one of those “don’t complain, do it better“-moments I figured it would be nice to write it myself for the Calendar. Off course some stuff can’t be done with JavaScript, we can only retrieve data, not submit new data to Google, so we can’t add new entries directly, but hey it’s a start :D

The library

We start off by modelling the Entry class, as you might easily figure out by the following code we rely on the Prototype library.

 
var EventEntry = Class.create();
EventEntry.prototype = {
	title: null,
	content: null,
	startDate: null,
	endDate: null,
	location: null,
	initialize: function(entry){
		this.title = entry.title.$t;
		this.content = entry.content.$t;
		this.startDate = DateConverter.rfc3339toDate(entry.gd$when[0].startTime);
		this.endDate = DateConverter.rfc3339toDate(entry.gd$when[0].endTime);
		this.location = entry.gd$where[0].valueString;
	}
};

Next we create a class that takes care of loading the feed, calling the callbacks and so on.

 
var Calendar = Class.create();
Calendar.prototype = {
	uri: "7cghno42lleqpbihmoi5qiikm8%40group.calendar.google.com",
	orderby: "starttime",
	singleEvents: true,
	futureEvents: true,
	sortOrder: "ascending",
	entries: {},
	initialize: function(u){
		if(u){this.uri = u;}
	},
	
	buildURL: function(){
		var str = "http://www.google.com/calendar/feeds/";
		str += this.uri;
		str += "/public/full-noattendees?orderby=" + this.orderby;
		str += "&alt=json-in-script&callback=window.activeCalendar.parseFeed&";
		str += "singleevents=" + this.singleEvents;
		str += "&sortorder=" + this.sortOrder;
		str += "&futureevents=" + this.futureEvents;
		return str;
	},
	
	loadFeed: function(){
		window.activeCalendar = this;
		var headTag = document.getElementsByTagName('head')[0]; 
		var script = document.createElement("script");
		script.src = this.buildURL();
		script.language = "JavaScript";
		headTag.appendChild(script);
	},
 
	parseFeed: function(json){
		e = json.feed.entry;
		for(var i=0;i < e.length;i++){
			this.entries[i] = new EventEntry(e[i])
		}
		try {
			this.onsuccess(this);
      } catch (e) {}
	},
	
	onsuccess: function(c){}
};

Notice the first line of the loadFeed? Yep, it’s a workaround, and an ugly one too. The problem is that we want to have access to the Calendar-object once we have the feed data. So we add it to the window-object. Anyway, this is the reason why you can load only one calendar at once.
And what would we be without some really ugly utility objects? So here you go, a pretty useless date converter class:

 
/**
 * Singleton object used to convert Dates from one format to another.
 */
var DateConverter = {
	rfc3339toDate: function(t){
		t = t.substr(0,19).replace(/-/g,"/").replace("T"," ");
		var dt = new Date();
		dt.setTime(Date.parse(t));
		return dt;
	}
};

So after all this code that you don’t have to write (because you can download it all here) now some code you have to write.

How to use it

I tried to keep it as simple as possible, if there are enough requests I may well extend it further, but for now it works nicely as it is. First you have to find out the feed identifier. Take the Feed URL as can be found in Google Calendar in the Calendar details and it will look something like this:

http://www.google.com/calendar/feeds/7cghno42lleqpbihmoi5qiikm8%40group.calendar.google.com/public/basic

Take the bold part and that’s the Feed Identifier that will then be used to create the instance of the Calendar:

 
var cal = new Calendar("7cghno42lleqpbihmoi5qiikm8%40group.calendar.google.com");

Next thing we need to do is add a callback function that is called once the Feed is loaded, and then kick the request off:

 
cal.onsuccess = function(c){alert(c);}
cal.loadFeed();

And that’s it :P
Now let’s see what we can do with it, and the reason I started fiddling with the Calendar in the first place. My custom frontend to one of my calendars can be seen here.

The main objective of advertising is to give detailed information about any kind of products in order to increase the number of potential customers. The dedicated servers provide the perfect managed web hosting solutions with great efficiency and productivity. You have a lot of opportunities to do work at home by surfing different freelancing jobs via internet. The application of website development software helps a lot to enhance the speed of web designers to develop new web designs. The internet advertising has opened a new horizon to run marketing campaigns on the large scale to have direct access to the extensive range of the customers. The wireless camera is designed by the implementation of the advanced technology of wireless networking system.

Also interesting posts:

11 Responses to “GCalendar: Accessing Google Calendar from JavaScript”

  1. Chowarmaan Says:
    Thanks for the API. I will be looking to add this to my site in the near future.
  2. mjparker Says:
    I have been looking for something like this for a while now. Glad I found this site. One suggestion, you have start date and end date but if the event is “All Day” then having that property/field would be nice.
  3. Skylog » Blog Archive » links for 2007-01-04 Says:
    [...] GCalendar: Accessing Google Calendar from JavaScript (tags: javascript) [...]
  4. Accessing Google Calendar from JavaScript : Popular Bookmarks : eConsultant Says:
    [...] Accessing Google Calendar from JavaScript Posted in bookmarks | Trackback | del.icio.us [...]
  5. Techno Mojo » Blog Archive » links for 2007-01-11 Says:
    [...] GCalendar: Accessing Google Calendar from JavaScript (tags: javascript google calendar programming api googleCalendar howto) [...]
  6. Fatih HayrioÄŸlu’nun not defteri » 12 Ocak 2007 Web’den seçme haberler Says:
    [...] Google bazı servislerine(Base, Blogger ve Calendar) erişmek için Gdata kütüphanesini bizlerin hizmetine açmış durumda. Bu makalede bu hizmeti kullanarak sitemize Google Calendar verilerimiz eklemeyi gösteren bir javascript kodu Link [...]
  7. Andrew Newdigate Says:
    Nice work! Thanks for going to the effort. I’ve used your library to build up an events page for an accommodation site I run. Check it out: http://www.ladolcevita-capetown.co.za/events.html.

    Many Thanks Again.

  8. Christian Decker Says:
    Thanks alot, I appreciate your feedback ^^
  9. Fading Roses & Raging Viruses » Blog Archive » Y! Pipes support for Prototype Says:
    [...] So I figured I should write a small wrapper that works like the Prototype Ajax.Request object (as I did a few months ago for Google Calendar) for Yahoo! Pipes. So here it is: YPipe Library [...]
  10. Dovy Says:
    Hey Christian,
    http://www.emeraldforeststudios.com/calendar/
    I can’t get your script working. Am I missing something? I know I don’t need to sign up for an API key, that’s just for google maps.

    Please direct me.

  11. Jim Says:
    A lot of useful staff, thank you for sharing.

Leave a Reply