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

Share:


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.

No comments