Retrieving Blogger's Recent Post Using JavaScript On Non-Blogger Site



Hey folks, Welcoming you all after a long time. Was unable to write blog for long time. Anyways, I'm back with a great content to read. Today, I'll be writing on getting posts for a non blogger site from a Blogger's Blog using Blogger's V3 API.

What we need?

  • A blog to retrieve posts from
  • A website to show the blogs on
  • API KEY from the Google's Developer's Console
  • Blogger's Blog ID.
  • JS and CSS Skill.
I believe my reader have got some skill on JS and CSS. Also, Most of them may have created a blog and a website prior to think about integrating both of this technology. And You can get API KEY from Google's Developer's Console. You need to create a project and a credentials to get one. Also, Open your blogger's dashboard where you can find your BlogID from the Query-'BlogID' of the URL in your address bar. Now, We are ready to go.




We will be using Google's Blogger's API V3 in-order to complete this task.I'll be focusing on getting the list of the posts of a blog.

The end point that I'm using here to retrieve the posts in JSON format is:
https://www.googleapis.com/blogger/v3/blogs/YOUR-BLOG-ID-HERE?key=YOUR-API-KEY

Retrieving the JSON from the Blog using API

We will be using AJAX to complete the task. The code to retrieve the JSON is shown below.
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://www.googleapis.com/blogger/v3/blogs/1842979261561211771/posts?key=AIzaSyD3t4cjcfI4IAFTyvoMid7SeWHxXbQaf1s", false);
xhttp.send();

The returned JSON consist of three kyes, 'kind', 'nextPageToken', 'items'. Items is an array that contains many posts. The keys in this details are 'kind', 'id', 'blog', 'title', 'content' and others.

Parsing the JSON

let json = JSON.parse(xhttp.responseText);

let list = json['items'];
for(let x in list)
   console.log(list[x]);




Here, It converts the response into JSON Object. And, we traverse each items (post) in the item key to get the values of post. For, now we are logging it in the console. Also, we can access title, content, kind, id, published(date), updated(date), url, author, replies, comments, and labels.

You can access different keys using the following codes with respective index.

console.log(list[x]['url']);
  console.log(list[x]['content']);
  console.log(list[x]['kind']);
  console.log(list[x]['updated']);
  console.log(list[x]['author']);
It retrieves 10 post at a time. So, In order to get more than 10 records we have to use pagination. The url endpoint with additional query  pageToken=nextPageToken will retrieves the next page values. If there are no posts left it won't return the nextPageToken. 

In, this way we can retrieve the post list from the blogger using blogger's API.

Here, Is a JS function that does the task for you. It retrieves the post parses it and generate HTML from it.
// document.body.innerHTML = f();
rec = document.getElementsByClassName('blog-container').item(0);
rec.innerHTML = f() + rec.innerHTML;
function f(from = 50, tot = 3, randomize = true) {
// This method may result duplicate content upon randomization, have no time to solve it
let url = 'https://www.googleapis.com/blogger/v3/blogs/1842979261561211771/posts?key=AIzaSyD3t4cjcfI4IAFTyvoMid7SeWHxXbQaf1s';
let ls = [];
let a = 1;
let token = '';
let html = '';
if(!randomize) from = tot; // If randomize is off we just need to extract the top only..
// while (true)
while (a < from)
{
let p = f2(token);
let list = p['items'];
for(let x in list){
ls.push(list[x]);
a++;
}
if(p.hasOwnProperty('nextPageToken'))
token = p['nextPageToken'];
else
break; // Break if total post is less than we want here to select from
}
let len = ls.length;
if(len < tot) tot = len; // Prevent array index out of bound(if it was Array), Prevents Not Found Exception
for(let i = 0; i < tot; i++ )
html += f1(ls[(randomize) ? parseInt(getRandomArbitrary(0, len)) : i]); // Randomize if its true else return i
return html;
function f2(token = '') {
let xhttp = new XMLHttpRequest();
xhttp.open("GET", url + (token !== '' ? '&pageToken=' + token : '') , false);
xhttp.send();
return JSON.parse(xhttp.responseText);
}
function f1(item) {
if(item.hasOwnProperty('kind') && item['kind'] !== "blogger#post") return '';
let h = '<div class = "post-item">';
let doc = new DOMParser().parseFromString(item['content'], 'text/html');
let src = doc.body.getElementsByTagName('img').item(0);
// console.log(item);
h += '<a href = "' + item['url'] + '"> <div class="bg-img" style=\'background-image: url("' + src.getAttribute('src')+ '");\'></div>';
h += '<h6>' + item["title"] + '</h6>';
h += '<span >' + doc.body.innerText.substr(1, 100) + '</span>';
// h.getAttribute('a');
// console.log(doc);
return h + '</a></div>';
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
}




Here, This function accepts three paramaters, from, top and randomize.
from: Sample no. of post to take from
to: Actual no. of post to retreive
randomize: do we need random data or not

If you have any question please write down in the comment section below.

Note: This function may return duplicate post upon randomization. Also, we have at least one image on each post so it retrieves the image link as thumbnail. Please make sure you have at least one image on each post. And, you can customize the HTML layout it returns.
Likewise you can use it to retrieve, post, comments, labels for any blog hosted using Googles's Blogger's Platform.

23 Comments

  1. Guys now its great news that notepad++ mac support almostly all languages

    ReplyDelete
  2. Thank you for helping me through this article. it's amazing and very helpful. Also read some interesting facts about valentines day. you will love it.

    ReplyDelete
  3. Very interesting and it caught my attention. I do want a website that is easy to manage. Bookmarking your article which will probably be my guide. Thank you very much.
    by Cloudi5
    Web Design Company in Coimbatore

    ReplyDelete
  4. I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article. social media marketing

    ReplyDelete
  5. this is really nice to read..informative post is very good to read..thanks a lot! Xham

    ReplyDelete
  6. Beaver says I also have such interest, you can read my profile here: email extractor 1.7

    ReplyDelete
  7. Welcome to the party of my life here you will learn everything about me. email extractor 1.4 lite

    ReplyDelete
  8. Thirdly, you can add increase cameras in the relatively near future. Security Cameras

    ReplyDelete
  9. Interesting topic for a blog. I have been searching the Internet for fun and came upon your website. source to pay software

    ReplyDelete
  10. Nice blog, I will keep visiting this blog very often. buy Canada cannabis

    ReplyDelete
  11. This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information. Keep it up. Keep blogging. Looking to reading your next post. thoptv pc, thop tv for windows

    ReplyDelete
  12. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. аппарат для криолиполиза

    ReplyDelete
  13. Cool stuff you have got and you keep update all of us. trends topics

    ReplyDelete
  14. Friend, this web site might be fabolous, i just like it Fulfillment Center

    ReplyDelete
  15. Nice knowledge gaining article. This post is really the best on this valuable topic. Plastikkirurgi før og efter

    ReplyDelete
  16. very interesting post.this is my first time visit here.i found so mmany interesting stuff in your blog especially its discussion..thanks for the post! Website Hosting

    ReplyDelete
  17. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. sneak a peek at this website

    ReplyDelete
  18. Thank you very much for this useful article. I like it. https://www.seoexpertindelhi.in/

    ReplyDelete
  19. Choosing a web hosting company can be a daunting task. While the number of options available to you is immense, web hosting providers that provide easy, inexpensive hosting are widely available. Here's some tips on what to look for when you choose. https://hostinglelo.in/

    ReplyDelete
  20. Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here. immobilien emsland

    ReplyDelete
  21. Most blogger use this platform for create the blog website. These platform is so reliable. While at this time you have an opportunity to get the Residential Pest Control in New York and keep your life happy and healthy.

    ReplyDelete
  22. Blog commenting or writing is a great way to interact and relate to various individuals in and out of your community. Nonetheless, it's still very important to observe some guidelines and exercise a little discretion when commenting or writing Blogs. Try to keep them short and moderate and try to be as honest as you possibly can. https://hostinglelo.in/

    ReplyDelete
Previous Post Next Post