Creating Your Own RSS Reader Using Google Feed API

Creating Your Own RSS Reader Using Google Feed API

52 34166
Creating Your Own RSS Reader Using Google Feed API
How to create own rss reader

Creating Own RSS Reader Using Google Feed API

I think every one faced with the task of connecting RSS feeds to your website, you can search and find some ready solutions (such as jQuery plugins), but also you can write your own script (which will smaller) and that will do it too. In this tutorial I’ll tell you how you can do it in pure javascript. Surfing web, I stumbled upon the Google Feed API, and thought that perhaps he would help me in this matter. Because using this service, I can easily (on-fly) to convert XML (of RSS) to JSON format. And as far as we know, javascript can easily work with JSON response. That’s what we will use, and now, lets check online demo.

Here are samples and downloadable package:

Live Demo

Ok, download the example files and lets start coding !


Step 1. HTML

As usual, we start with the HTML. This is source code of our sample:

index.html

<html>
<head>
    <title>New own RSS reader demonstration</title>
    <link rel="stylesheet" type="text/css" href="css/main.css" />
    <script type="text/javascript" src="js/main.js"></script>
</head>
 <body>
    <div class="example">
        <div class="post_results" id="post_results1" rss_num="8" rss_url="http://rss.news.yahoo.com/rss/topstories">
            <div class="loading_rss">
                <img alt="Loading..." src="images/loading.gif" />
            </div>
        </div>

        <div class="post_results" id="post_results2" rss_num="8" rss_url="http://newsrss.bbc.co.uk/rss/newsonline_world_edition/front_page/rss.xml">
            <div class="loading_rss">
                <img alt="Loading..." src="images/loading.gif" />
            </div>
        </div>

        <div style="clear:both;"></div>
    </div>
 </body>
</html>

As you can see – I prepared 2 DIV elements where going to load RSS feeds, in attributes (rss_url and rss_num) I pointing url of rss feed and amount of elements which going to display

Step 2. CSS

Here are single CSS file with all necessary styles:

css/main.css

body{background:#eee;margin:0;padding:0}
.example{background:#FFF;width:825px;border:1px #000 solid;margin:20px auto;padding:15px;-moz-border-radius: 3px;-webkit-border-radius: 3px}

.post_results {
    margin: 5px;
    width: 400px;
    border:1px solid #444;
    float:left;
}
.post_results ul {
    list-style:none;
    text-align:left;
    padding:0;
    margin: 0;
}
.post_results ul li {
    background: #555555;
    background: -moz-linear-gradient(top, #555555 0%, #444444 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#555555), color-stop(100%,#444444)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top, #555555 0%,#444444 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top, #555555 0%,#444444 100%); /* Opera11.10+ */
    background: -ms-linear-gradient(top, #555555 0%,#444444 100%); /* IE10+ */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#555555', endColorstr='#444444',GradientType=0 ); /* IE6-9 */
    background: linear-gradient(top, #555555 0%,#444444 100%); /* W3C */
    height: 60px;
    padding: 10px;
}
.post_results ul li:hover{
    background: #666;
}
.post_results ul li a{
    color: #fff;
    display: block;
    font-size: 14px;
    font-weight: bold;
    text-align: center;
    text-decoration: none;
    margin-bottom:5px;
}
.post_results ul li a:hover{
    color: #eee;
}
.post_results ul li p {
    color: #ddd;
    font-size: 13px;
    margin: 0;
}

Step 3. JS

Here are our main Javascript:

js/main.js

function myGetElementsByClassName(selector) {
    if ( document.getElementsByClassName ) {
        return document.getElementsByClassName(selector);
    }

    var returnList = new Array();
    var nodes = document.getElementsByTagName('div');
    var max = nodes.length;
    for ( var i = 0; i < max; i++ ) {
        if ( nodes[i].className == selector ) {
            returnList[returnList.length] = nodes[i];
        }
    }
    return returnList;
}

var rssReader = {
    containers : null,

    // initialization function
    init : function(selector) {
        containers = myGetElementsByClassName(selector);
        for(i=0;i<containers.length;i++){
            // getting necessary variables
            var rssUrl = containers[i].getAttribute('rss_url');
            var num = containers[i].getAttribute('rss_num');
            var id = containers[i].getAttribute('id');

            // creating temp scripts which will help us to transform XML (RSS) to JSON
            var url = encodeURIComponent(rssUrl);
            var googUrl = 'https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num='+num+'&q='+url+'&callback=rssReader.parse&context='+id;

            var script = document.createElement('script');
            script.setAttribute('type','text/javascript');
            script.setAttribute('charset','utf-8');
            script.setAttribute('src',googUrl);
            containers[i].appendChild(script);
        }
    },

    // parsing of results by google
    parse : function(context, data) {
        var container = document.getElementById(context);
        container.innerHTML = '';

        // creating list of elements
        var mainList = document.createElement('ul');

        // also creating its childs (subitems)
        var entries = data.feed.entries;
        for (var i=0; i<entries.length; i++) {
            var listItem = document.createElement('li');
            var title = entries[i].title;
            var contentSnippet = entries[i].contentSnippet;
            var contentSnippetText = document.createTextNode(contentSnippet);

            var link = document.createElement('a');
            link.setAttribute('href', entries[i].link);
            link.setAttribute('target','_blank');
            var text = document.createTextNode(title);
            link.appendChild(text);

            // add link to list item
            listItem.appendChild(link);

            var desc = document.createElement('p');
            desc.appendChild(contentSnippetText);

            // add description to list item
            listItem.appendChild(desc);

            // adding list item to main list
            mainList.appendChild(listItem);
        }
        container.appendChild(mainList);
    }
};

window.onload = function() {
    rssReader.init('post_results');
}

It is rather simple. When the page loads – I appending prepared javascript objects into our containers (div class="post_results"). That javascript asking google to convers RSS(XML) feed to JSON format using Google Feed API. After, script pass executing to ‘parse’ function of our object, that function convert JSON date into HTML presentation. So, in result – it loading our XML feed in HTML format. All pretty nice :)

Step 4. Images

For our demo I used only one image (this is loading icon):

img_01


Live Demo

Conclusion

Today’s lesson has demonstrated and Google Feed API, and how we can easily handle the received data and draw up (at client-side) result, using pure javascript. I hope you enjoyed our lesson. Good luck!

SIMILAR ARTICLES


52 COMMENTS

  1. i think less it on css coded…
    .loading_rss {
    text-align: center;
    background: #eee;
    padding: 10px;
    }
    hihihi…
    thanks, it’s great tut’s ;)

  2. This is a great tutorial and very simple, thanks. But how can i increase the number of words displayed or allow the reader to display all the words. The feed im getting normally contains about 60 words in their excerpts…

    Also i can i display the images in the feed?

    Many thanks in advance…

      • hi
        when i added content instead of contentSnippet it shows the full content but problem is that it shows html tag in that.
        like
        American cyclist Lance Armstrong will be stripp……
        how i will remove this tag from the content ?

  3. where in the parser do i ad the entries[i].mediaGroups[0].contents[0].url at so i can get images in the rss feed viewer ??

      • I notice that the feed does not refresh regularly. Is there anyway to increase (or control) the refresh rate of the feeds? Refreshing the webpage does not refresh the feed.

      • Hi Mark,
        You probably have a problem with caching. The feed can be cached by your browser, or google caches feed requests. You need to find out what it is exactly.

  4. Amazing RSS tutorial! Best iv’e read so far.

    But I have a quick question about adding images, how do I do it?

    for (var i=0; i<entries.length; i++) {
    entries[i].mediaGroups[0].contents[0].url; < I did this and its not working so I am obviously wrong.
    var listItem = document.createElement('li');

    Can you help?

    • Hi Jo,
      It can be something like that:
      var img = new Image();
      img.src = entries[i].mediaGroups[0].contents[0].url;
      listItem.appendChild(img);

      • Great tutorial! Just wondering w/ this image, how can we control its positioning and what nots in css?

      • Hi Sam,
        Which position exactly? Parent elements are usual boxes (div), you can place them everywhere you want.

  5. Thank you for this simple example. Do you happen to know what java script I would need to add to get this Div RSS box to auto scroll after the page loads?

    • Hello Justin,
      Can you please explain – scroll to which position? As I see, there are not so many elements to scroll.
      It should generate elements from the beginning to end (from top to bottom). What position do you want to scroll to?

  6. Figured it out, :) You have to access the data object in the parse function. Its just a json object. There’s documentation too. Thanks for sharing the tutorial!

  7. Great tut my dear…i just wanted to know…we have 2 files…the main.js where you put the images code :
    var img = new Image();
    img.src = entries[i].mediaGroups[0].contents[0].url;
    listItem.appendChild(img);

    and the main.css
    the images appears but very big…my question is:
    - how can i align it to the right and shrink the image scale to be something like 100px for width and height?
    - can i use this to create thumb images beside the news feed in every block?

    looking forward to hear from you..

    • Hello wahid,
      The first thing that came to my mind – you should use CSS rules to decrease this image (use ‘width’ and ‘height’ properties). If you need to align, you can use ‘float’ property.
      Yes, you can use this code to display images for every block, don’t worry :-)

      • the problem is that i didn’t know where to put the 3 lines of codes in the main.js in the same time…i donno how to connect those 3 ccodelines with the main.css ….i’m not that good in scripting

      • Hello Wahid,
        Check the comments above, I already explained to JO where exactly we can put the code to work with images (inside of ‘for’ cycle where we go through all the entries)

  8. Greetings! Thank you very much for this tutorial, I’m settling this code for an app on BlackBerry Playbook and so far it has worked very well.
    I have a question, what happens in the BlackBerry app is that you can’t open the link of each item within the app.
    To open the link in the news item is necessary to invoke a function that opens the browser app Playbook as well:

    function OpenLink (urlItem) {
    var args = new blackberry.invoke.BrowserArguments (urlItem);
    blackberry.invoke.invoke (blackberry.invoke.APP_BROWSER, args);
    }

    Where “urlItem” is the argument passed to the function with a link that opens in the native browser.

    In your code you have the following:

    var link = document.createElement (‘a’);
    link.setAttribute (‘href’, entries [i]. link);
    link.setAttribute (‘target’, ‘_blank’);

    I have added the following line:

    link.setAttribute (‘onclick’, ‘OpenLink ()’);

    I would like to know if it is possible to get the link of an item once I select it, and in this way pass that value in something like this: OpenLink (“link of selected item”).

    I really really appreciate any suggestions or help you can give me.

    • Hi Diego,
      Yes, sure, this is possible, instead of var link = document.createElement (‘a’); link.setAttribute (‘href’, entries [i]. link); etc …
      you can easily create: var myLink = ‘<a href="__url__" onclick="OpenLinl(‘__url__’)">__title__</a>’;
      because you always can append the HTML string to elements (for example: listItem.appendChild(myLink); )
      Moreover, it is not essential to use A element, you can use any other element (for instance: Div)

    • Hi Pradeep, if you don’t want to display description – you can comment this code: listItem.appendChild(desc);

  9. Hello, awsome tutorial! But I’m stock on the adding images part. I’m trying to get the images to show as you outlined with this:


    var img = new Image();
    img.src = entries[i].mediaGroups[0].contents[0].url;
    listItem.appendChild(img);

    The images won’t work, however. That snipped (above) breaks the code somehow. Can you show the snippet within the rest of the code to show how to place it? THis is what I was trying and it wouldn’t work

    Line 51:

    // also creating its childs (subitems)
    var entries = data.feed.entries;
    for (var i=0; i<entries.length; i++) {
    var img = new Image();
    img.src = entries[i].mediaGroups[0].contents[0].url;
    listItem.appendChild(img);
    var listItem = document.createElement('li');
    var title = entries[i].title;
    var contentSnippet = entries[i].contentSnippet;
    var contentSnippetText = document.createTextNode(contentSnippet);

    Much thanks!

    • Hi Jim,
      You made a basic mistake, you started using ‘listItem’ before you defined it, look:

      listItem.appendChild(img);
      var listItem = document.createElement(‘li’);

      can you see this mistake?
      Of course, you should move your code a bit below, under the definition:
      var listItem = document.createElement(‘li’);

      For example, change your code to:

      // also creating its childs (subitems)
      var entries = data.feed.entries;
      for (var i=0; i var listItem = document.createElement(‘li’);
      var title = entries[i].title;
      var contentSnippet = entries[i].contentSnippet;
      var contentSnippetText = document.createTextNode(contentSnippet);

      var img = new Image();
      img.src = entries[i].mediaGroups[0].contents[0].url;
      listItem.appendChild(img);

  10. When I try to add Image the whole script stops working. Doesn’t show any feed.
    for (var i=0; i<entries.length; i++) {
    var listItem = document.createElement('li');
    var title = entries[i].title;
    var contentSnippet = entries[i].contentSnippet;
    var contentSnippetText = document.createTextNode(contentSnippet);

    var link = document.createElement('a');
    link.setAttribute('href', entries[i].link);
    link.setAttribute('target','_blank');
    var text = document.createTextNode(title);
    link.appendChild(text);
    // add link to list item
    listItem.appendChild(link);

    var imgDiv = document.createElement('div');
    imgDiv.className = "thumb-img"
    var detailDiv = document.createElement('div');
    var imgThumb = new Image();
    imgThumb.src = entries[i].mediaGroups[0].contents[0].url;

    imgDiv.appendChild(imgThumb);
    listItem.appendChild(imgDiv);

    var desc = document.createElement('p');
    desc.appendChild(contentSnippetText);
    detailDiv.appendChild(desc);
    // add description to list item
    listItem.appendChild(detailDiv);

    // adding list item to main list
    mainList.appendChild(listItem);
    }

    • Hi Anas,
      You forgot that it can be provided without ‘mediaGroups’, thus, please replace your code to:
      if (entries[i].mediaGroups) {
      var img = new Image();
      img.src = entries[i].mediaGroups[0].contents[0].url;
      listItem.appendChild(img);
      }

      (I updated our demo with this code)

  11. Hi, i have try at modified code for show thumbnails, but don’t work, can you help me?

    var link = document.createElement(‘a’);
    link.setAttribute(‘href’, entries[i].link);
    link.setAttribute(‘target’,’_blank’);
    var text = document.createTextNode(title);
    link.appendChild(text);

    var img = new Image();
    img.src = entries[i].mediaGroups[0].contents[0].url;
    listItem.appendChild(img);

    • Hello Cloude,
      Please use
      if (entries[i].mediaGroups) {
      var img = new Image();
      img.src = entries[i].mediaGroups[0].contents[0].url;
      listItem.appendChild(img);
      }

      instead

  12. Hi andrew – I implemented the code using the same file structure and when I test it shows the loading images. Anything that I’m missing?

    Best,

    Marco

    • Hi Sertleris,
      To achieve this, you can add the following styles for the .post_results ul li :

      -moz-box-sizing: border-box;
      float: left;
      width: 50%;

  13. Hi, first of all great tutorial, thanks for writing it.
    I’m hoping you still check for any comments…

    I was wondering, how would one go about having multiple feeds displayed under one div?
    In your example there are two – “post_results1″ and “post_results2″ and both have their separate rss urls.
    I’m trying to figure out how to “merge” these two feeds and have them display the news in one list.

    Thanks

    • Hi Kamil,
      In your case, you need to customize the script, because you will need to provide two (or more) different rss feed urls. Then, you will need to make two different ajax requests to get both feeds, – and then – just put result records into the single (div) parent object.

  14. Hi Andrey,

    I am very curious on how to get it to display the title of the feed. I have several of them and sometimes can’t tell the difference between them. I would like it to have the same format, or within the same frame. Can you help me? Thank you.

    Cody

      • Hi Andrey,
        Thank you for the response. Do you know where and how I can use ‘data.feed.title’?

      • Hi Cody,
        You may use it in the ‘parse’ function. Because only this function generates the result

  15. Hi Andrey!
    This works nicely. Although when I tried reading a (different) JSON feed taking this code as a base and removing the XML parsing part, I couldn’t figure out how to exactly make this work.
    Any suggestions/code lines?
    Thanks so much!

    • Hi Alcaldo,
      If your source is JSON, you need to work with it as with ordinary array. Basically, you need that ‘parse’ part to convert your result (feed) into html

  16. Hi,
    This is a really helpful tutorial.
    I’m finding that this is returning html special characters as their unicode eq and not readable text.
    Do you know of a way to escape html characters when the xml is parsed?

Leave a Reply