Download Feeds with JavaScript

April 20, 2007

The Google AJAX Feed API:

With the AJAX Feed API, you can download any public Atom or RSS feed using only JavaScript, so you can easily mash up feeds with your content and other APIs like the Google Maps API.

Example usage:

function initialize() {
  var feed = new google.feeds.Feed("http://www.digg.com/rss/index.xml");
  feed.load(function(result) {
    if (!result.error) {
      var container = document.getElementById("feed");
      for (var i = 0; i < result.feed.entries.length; i++) {
        var entry = result.feed.entries[i];
        var div = document.createElement("div");
        div.appendChild(document.createTextNode(entry.title));
        container.appendChild(div);
      }
    }
  });
}

Very neat. Puzzling at first sight, though, is the header:

<script type="text/javascript" src="http://www.google.com/jsapi?key=YOUR_KEY_HERE"></script>

Why would one load a script from there instead of just downloading it? The answer is security — Google acts a a proxy, so the JS code never accesses anything other than the domain it was loaded from.

About

This page contains a single entry from Stefan Tilkov's Random Stuff posted on April 20, 2007 7:19 PM. The previous post in this blog was Version Numbers. The next post in this blog is Metacircular Ranting. Many more can be found on the main index page or by looking through the archives.

Comments