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()
:
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") For your reference, the single parameter
|
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:
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:
For example, inside your var item1=result.feed.entries[0] //access first
feed item XML Format Structure In XML format, the |
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.
- Displaying RSS feeds easily using Google Ajax Feed API (intro)
- Detailed look at Google.feeds.Feed.class
- A robust RSS feed displayer