Categories:

Detailed look at Google.feeds.Feed.class

The Google Ajax Feed API is actually split into two different classes, FeedControl() and Feed(). In this tutorial, we're dealing only with Feed(), or to be more precise, google.feeds.Feed(). Before I get to explaining its syntax, recall that you must first embed the following code in the HEAD section of your page to reference Google Ajax Feed API first:

<head>
<script type="text/javascript" src="http://www.google.com/jsapi?key=YOUR-API-KEY">
</script>

<script type="text/javascript">
google.load("feeds", "1") //Load Google Ajax Feed API (version 1)
</script>
</head>

Where "1" indicates to load version 1 of Google Code API, currently the latest version. Ok, now onto the syntax for google.feeds.Feed():

google.feeds.Feed class

Class Object

Description

google.feeds.Feed(url)

 

Google Feed object class that accepts a single RSS feed based on the "URL" parameter.

Example:

var myfeed=new google.feeds.Feed("http://digg.com/rss/index.xml")

Method Description
Feed.load(callbackfunction) Downloads the feed specified during initialization of the Ajax Feed class, and once it's complete (there is a delay), invokes the desired callbackfunction reference. The call back function is passed a single parameter (ie: result) that contains the contents of the feed. By default, the content is returned in JSON format (versus XML).

Example:

var myfeed=new google.feeds.Feed("http://digg.com/rss/index.xml")
myfeed.load(formatmsgs)

function formatmsgs(result){
var rssContent=""
if (!result.error){//if no error fetching RSS feed
var thefeeds=result.feed.entries //get feed contents (JSON array)
for (var i=0; i<thefeeds.length; i++)
rssContent+="<a href='" + thefeeds[i].link + "'>" + thefeeds[i].title + "</a><br />"
document.getElementById("adiv").innerHTML=rssContent
}
else //if error fetching feed, alert human readable error message
alert(result.error.message)
}

For your reference, the single parameter result contains the following data structure:

  • error? Defined if there's an error loading the feed. Check for its presence to see if an error has occurred.
  • xmlDocument? The feed XML document. Defined if the format specified is either XML_FORMAT or MIXED_FORMAT.
  • feed? The JSON representation of the feed. Defined if the format specified is either JSON_FORMAT or MIXED_FORMAT.
Feed.setNumEntries(int) Optional. Sets the number of entries to retrieve. By default, 4 entries are fetched.
Feed.setResultFormat(format) Optional. Returns the result to one of the following formats:
  • google.feeds.Feed.JSON_FORMAT
  • google.feeds.Feed.XML_FORMAT, or
  • google.feeds.Feed.MIXED_FORMAT.

By default, the JSON format is used.

JSON Format Structure

In JSON format, the feed itself is returned as a JavaScript array with the following structure:

  • title The feed title. Corresponds to the <title> element in Atom and the <title> element in RSS.
  • link The URL for the HTML version of the feed. Corresponds to the <link> element in Atom and the <link> element in RSS.
  • description The feed description. Corresponds to the <subtitle> element in Atom and the <description> element in RSS.
  • author The feed author. Corresponds to the <name> element for the author in Atom.
  • entries[] A list of all of the entries in the feed. Corresponds to the <entry> element in Atom and the <item> element in RSS.
    • title The entry title. Corresponds to the <title> element in Atom and the <title> element in RSS.
    • link The URL for the HTML version of the entry. Corresponds to the <link> element in Atom and the <link> element in RSS.
    • content The body of this entry, including HTML tags. Since this value can contain HTML tags, you should display this value using elem.innerHTML = entry.content (as opposed to using document.createTextNode). Corresponds to the <content> or <summary> elements in Atom and the <description> element in RSS.
    • contentSnippet A snippet (< 120 characters) version of the content attribute. The snippet does not contain any HTML tags.
    • publishedDate The string date on which the entry was published of the form "13 Apr 2007 12:40:07 -0700". You can parse the date with new Date(entry.date). Corresponds to the <published> element in Atom and the <pubDate> element in RSS.
    • categories[] A list of string tags

For example, inside your callbackfunction, the below code accesses the first item within the RSS feed, where result.feed references the feed itself:

var item1=result.feed.entries[0] //access first feed item
alert(item1.title) //title of first item
alert(item1.content) //body of first item
alert(item1.publishedDate) //date of first item

XML Format Structure

In XML format, the xmlDocument attribute is returned that contains the fully parsed XML Document node for the feed. You can access the document using standard DOM methods such as getElementsByTagName).

includeHistoricalEntries() By default, when a feed is loaded, the system returns a cached copy of the specified feed that is 100% in sync with the feed contents at the time that it was cached. By calling this method, you can instruct the system to return any additional historical entries that it might have in its cache.

Note: Reference based on Google's google.feeds.Feed() documentation.

Putting everything into context, the following example displays a single news entry from Slashdot:

<script type="text/javascript">

document.write('<div id="slashdot"></div>')
var feedpointer=new google.feeds.Feed("http://rss.slashdot.org/Slashdot/slashdot") method
feedpointer.setNumEntries(1) //Show 1 entry only
feedpointer.load(formatoutput)


function formatoutput(result){
if (!result.error){
var rssoutput=""
var thefeeds=result.feed.entries
for (var i=0; i<thefeeds.length; i++){
var entrydate=new Date(thefeeds[i].publishedDate) //get date of entry
var entrydatestr=' '+entrydate.getFullYear()+"/"+(entrydate.getMonth()+1)+"/"+entrydate.getDate()
rssoutput+="<p><a href='" + thefeeds[i].link + "'>" + thefeeds[i].title + "</a> " +entrydatestr + "<br />" + thefeeds[i].content + "</p>"
}
document.getElementById("slashdot").innerHTML=rssoutput
}
else //if error fetching feed, alert human readable error message
alert(result.error.message)
}

</script>

Output:

Handling any errors while fetching a RSS feed

As reliable as Google's servers are known to be, there are bound to be times when it doesn't successfully fetch a RSS feed. When that occurs, you can refer to the error object inside your callbackfunction to detect it, which becomes defined. For example:

if (!result.error){
// display RSS feed
}
else
alert("An error has occured fetching the feed") //alert error code

Formatting the date field of a RSS item

You can display the date/time for each RSS item using the publishedDate property of each item. However, the default output is a complete date string in the format 13 Apr 2007 12:40:07 -0700, which may not be to your liking. You can customize the date by passing the publishedDate property into the Date() object of JavaScript to create a valid date object. For example, to output the date in the format "yyyy/month/day", you can do this:

var thefeeds=result.feed.entries //get feed contents (JSON array)
for (var i=0; i<thefeeds.length; i++){
var itemdate=new Date(thefeeds[i].publishedDate)
var itemdate_yr=itemdate.getFullYear()
var itemdate_mon=itemdate.getMonth()+1
var itemdate_day=itemdate.getDate()
var output=itemdate_yr + "/" + itemdate_mon + "/" + itemdate_day //format: yyyy/month/day
}

Check out JavaScript's Date Object for all the methods at your disposal to format the date and time.

Taking into account the delay before a RSS feed is successfully fetched

When you call Feed.load(callbackfunction) to download the requested RSS feed, it's important to note that there is a delay before the process is complete and callbackfunction is run. Firstly, this means you can't use document.write()  inside your callbackfunction to output the feed. Secondly, make sure whatever object or elements you're referencing inside callbackfunction is defined when the function is called, which might not always be. Consider the below code:

function formatmsgs(result){
document.getElementById("adiv").innerHTML=result.title //display RSS feed title inside DIV
}

In this case, you need to make sure the DIV (ID="adiv") is defined on the page when the callback function formatmsgs() is executed. If this DIV is physically defined in the page's source and proceeding your script, then most likely it will be. However, what if the DIV is dynamically created using the DOM? Since elements can only be dynamically added to the page after it has fully loaded, this means your DIV won't be defined until that time. If the callbackfunction is invoked before then, it won't have access to the DIV yet (and an error is returned). In cases where you're not confident the element(s) referenced in your callbackfunction will be defined before the function is invoked, the easiest way is remedy this is to call Feed.load() after the page has loaded (which includes any elements as well), for example:

var myfeed=new google.feeds.Feed("http://digg.com/rss/index.xml")

function formatmsgs(result){
document.getElementById("adiv").innerHTML=result.title //display RSS feed title inside DIV
}

window.onload=function(){
myfeed.load(formatmsgs)
}

Or instead of using window.onload(), you can use Google's custom function for calling a function on window.load, google.setOnLoadCallback(functionreference). It accepts a reference to the function (without parameters) to invoke. The advantage of using this method is that you don't have to worry about multiple onload event handlers cancelling each other out. So what you end up instead is something like the following:

var myfeed=new google.feeds.Feed("http://digg.com/rss/index.xml")

function initfeed(){
myfeed.load(formatmsgs)
}

function formatmsgs(result){
document.getElementById("adiv").innerHTML=result.title //display RSS feed title inside DIV
}

google.setOnLoadCallback(initfeed)

However you do it, the point is, you should invoke Feed.load() after the page has loaded if there's a possibility what you're referencing within callbackfunction may not be defined when the function is called.