Consuming RSS feeds via Javascript

This article briefly discusses how to consume an RSS feed via javascript.

Consuming an RSS feed via javascript is not particularly difficult. RSS is based on XML and the XMLDOM provides an easy way of interacting with XML documents.

The example below describes how to consume the HowToDoThings.com JavaScript section's news RSS feed.

 

<HTML>
<HEAD>
<script type="text/javascript">
function GetRSSNews(){
 
 var iMax = 6
 
 var rssDoc = new ActiveXObject("Microsoft.XMLDOM")
 rssDoc.async = false
 rssDoc.load("http://www.howtodothings.com/rss.aspx"
   + "?id=d21bf29f4b3d4299b142536d5c3b610a")
 
 var headNode = rssDoc.selectNodes("/rss/channel")
 var itemNodes = rssDoc.selectNodes("/rss/channel/item")
 
 if(itemNodes.length<iMax){
  iMax = itemNodes.length
 }
 
 var feedBody = ""
 
 for(i=0;i<iMax;i++){
  feedBody = feedBody + "<p><a href='" + itemNodes.item(i).getElementsByTagName("link").item(0).text + "'>" + itemNodes.item(i).getElementsByTagName("title").item(0).text + "</a></p>"
 }
 
 myFeeds.innerHTML  = feedBody

 myChannel.innerText = headNode.item(0).getElementsByTagName("title").item(0).text
}
</script>
</HEAD>
<BODY onload="GetRSSNews()">
<div id="myChannel"></div>
<div id="myFeeds"></div>
</BODY>
</HTML>

We have capped number of articles to display in variable iMax, loaded the xml file into the DOM and used simple HTML dom scripting to display the contents of the xml file.

 

You might find out however that while the script works well on your local domain it might not work so easily if you dumped it on a page hosted by your ISP. This is because by default some browsers (IE for example) have security settings which disallow "cross-domain file access." Surfers to your page will have to edit their internet security settings to allow cross domain file access.

An alternative is to find a way of "caching" the rss feed file on your web server and call it locally ie bringing it into the same domain as your webpage. Of course, there's also easy to use alternatives like rss-to-javascript.com who will provide you with a simple HTML script to add to your page. The only downside in my opinion is that they will include a "powered by..." line in your page.

To learn more about IE's security context please go to http://msdn.microsoft.com

 

Share this article!

Follow us!

Find more helpful articles: