How to Add a Real-Time Views Counter Widget in Blogger: A Comprehensive Guide

One of the best ways to engage with your blog readers and improve user experience is by adding interactive features. Real-time view counters are an excellent way to show the level of engagement on your blog posts and increase credibility by displaying how many visitors are reading your content at any given time. Blogger, one of the most popular blogging platforms, is fairly easy to customize, and you can add various widgets, including a real-time views counter. This detailed guide will walk you through the steps required to add a real-time view counter to your Blogger site.

Why Use a Real-Time Views Counter?

Before diving into the technical details, let’s first understand why adding a real-time views counter can be beneficial for your Blogger site:

  1. Visitor Engagement: Displaying a real-time views counter can make your blog more interactive and provide your readers with a sense of activity and community. They can see that they are not alone on the site and are more likely to engage with your content.
  2. Social Proof: A high number of real-time views indicates that your blog is popular, which may encourage new visitors to stay longer and explore more of your posts.
  3. User Experience: For returning visitors, a real-time views counter helps them understand which posts are currently trending on your site, guiding them toward the most relevant content.
  4. Analytics at a Glance: The counter allows you to quickly gauge how your content is performing in real time without needing to dive into backend analytics platforms.

Now that we understand why a real-time views counter is useful, let’s move forward with how you can add this functionality to your Blogger site.

Real-Time Views Counter Widget in Blogger

Step-by-Step Guide to Adding a Real-Time Views Counter to Blogger

There are various ways to add a real-time view counter to your Blogger site, and we will cover the most efficient methods, including using third-party services and custom coding. Follow along step by step to ensure successful implementation.

Prerequisites

Before you start, you need to have a Blogger site set up. If you don’t already have one, visit Blogger and create a blog. Additionally, make sure that you are comfortable editing the layout and adding widgets to your blog. If you’re new to Blogger, don’t worry, the following steps are straightforward and beginner-friendly.


Method 1: Using a Third-Party Real-Time Views Counter Widget

The easiest and fastest way to add a real-time views counter is by using third-party services that provide embeddable widgets. These widgets are simple to integrate into your Blogger site and do not require coding skills.

Step 1: Select a Widget Provider

Here are a few reliable real-time views counter widget providers:

  1. Whos.amung.us – A popular choice for adding a real-time counter.
  2. Histats – Offers both real-time tracking and detailed analytics.
  3. Sitemeter – Another option for tracking visitors and real-time views.
  4. Free-Counters.org – Provides a basic real-time views counter for blogs and websites.

For this guide, we will use Whos.amung.us as it is widely known for its simplicity and effectiveness.

Step 2: Register and Get the Code
  1. Visit the Whos.amung.us website and sign up for a free account.
  2. After registering, navigate to the “Get Your Code” section, where you will be presented with a JavaScript code snippet that you can embed into your site.
  3. Copy the code provided. This is the code that will display the real-time views counter on your Blogger site.
Step 3: Add the Code to Blogger
  1. Log in to your Blogger account and navigate to your blog’s dashboard.
  2. Click on the “Layout” tab in the left-hand menu. This will open up the layout editor, where you can add new widgets to your blog.
  3. In the layout section, find where you would like to place your real-time views counter. Most people choose the sidebar for visibility, but you can also add it to the footer or header area.
  4. Click “Add a Gadget” in your preferred location. A pop-up window will appear with a list of available gadgets. Scroll down and choose “HTML/JavaScript”.
  5. In the HTML/JavaScript gadget settings:
    • Leave the “Title” field blank if you don’t want a title for your widget.
    • Paste the real-time views counter code you copied from Whos.amung.us into the Content field.
  6. Click Save to confirm the changes.
Step 4: Preview and Adjust
  1. Once you’ve saved the gadget, return to your blog’s dashboard and preview your blog to ensure that the real-time views counter is displaying correctly.
  2. If the widget isn’t appearing where you want it, return to the Layout section and drag the widget to a different area of the page.
  3. After you are satisfied with the placement, click Save Arrangement.

That’s it! You now have a working real-time views counter on your Blogger site using a third-party service. The counter will automatically update as visitors arrive on your blog.


Method 2: Using Custom JavaScript and Google Analytics API

For more advanced users who want a custom solution, you can create your own real-time views counter using JavaScript and the Google Analytics API. This method requires more technical knowledge but gives you greater flexibility and control over the appearance and functionality of the widget.

Step 1: Set Up Google Analytics

If you don’t already have Google Analytics installed on your Blogger site, follow these steps:

  1. Sign up for Google Analytics: Go to Google Analytics and sign up for an account if you haven’t already.
  2. Create a Property: In Google Analytics, create a property for your Blogger site. This will generate a tracking code that you will need to embed in your blog.
  3. Add Tracking Code to Blogger:
    • Go to the Admin section of Google Analytics and find your tracking code (it should look like this: UA-XXXXXXXXX-X).
    • Copy this tracking code.
    • Go to your Blogger dashboard, click on Settings, and then navigate to the Other section.
    • Paste the tracking code into the Google Analytics section and click Save.

Once Google Analytics is set up and tracking your site, you can proceed with building the real-time views counter.

Step 2: Enable Google Analytics Real-Time Reporting API

  1. Go to the Google Developers Console.
  2. Create a new project or select an existing one.
  3. Navigate to API & Services and enable the Google Analytics Reporting API.
  4. Create OAuth credentials for your project by navigating to Credentials -> Create Credentials -> OAuth 2.0 Client IDs.
  5. Configure OAuth consent and set the authorized JavaScript origins to your Blogger URL.
  6. Once the API and credentials are set up, you will be provided with a Client ID and Client Secret. You’ll need these for the next step.

Step 3: Write the JavaScript Code

Now that you have access to the Google Analytics Real-Time Reporting API, you can write the JavaScript code to display real-time views on your blog.

Here’s a basic example of what the JavaScript code might look like:

<script src="https://apis.google.com/js/platform.js" async defer></script><script>  var CLIENT_ID = 'YOUR_CLIENT_ID.apps.googleusercontent.com';  var SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'];  function authorize(event) {    gapi.auth.authorize({      'client_id': CLIENT_ID,      'scope': SCOPES.join(' '),      'immediate': false    }, handleAuthResult);    return false;  }  function handleAuthResult(authResult) {    if (authResult && !authResult.error) {      loadAnalyticsClient();    }  }  function loadAnalyticsClient() {    gapi.client.load('analytics', 'v3').then(function() {      queryRealTimeViews();    });  }  function queryRealTimeViews() {    gapi.client.analytics.data.realtime.get({      'ids': 'ga:YOUR_VIEW_ID',      'metrics': 'rt:activeUsers'    }).then(function(response) {      var activeUsers = response.result.totalsForAllResults['rt:activeUsers'];      document.getElementById('real-time-counter').innerText = activeUsers;    });  }</script><div id="real-time-counter">Loading...</div><button onclick="authorize()">Authorize</button>

In this script:

  • Replace 'YOUR_CLIENT_ID' with the Client ID from the Google Developer Console.
  • Replace 'YOUR_VIEW_ID' with the View ID from your Google Analytics property.

Step 4: Add the JavaScript Code to Blogger

  1. Go to your Blogger dashboard and navigate to the Layout section.
  2. Click Add a Gadget and select HTML/JavaScript.
  3. Paste the JavaScript code into the gadget.
  4. Click Save and preview your blog. The real-time views counter will display the number of active users once the API call is authorized.

Read More
How To Seo Blogger Websites: Tips Boost Your Blog Traffic
How to Write SEO Blogger Posts: A Comprehensive Guide to Boost Traffic
How to Add a Bookmark Button on Your Blogger Website

Senzix

Method 3: Using Custom CSS and Design Tweaks for Better Appearance

Adding a real-time post views count widget in Firebase involves integrating Firebase’s Realtime Database or Firestore to track and display the number of views for individual posts on your website or application. Firebase’s backend services allow you to store, update, and retrieve real-time data, making it an excellent choice for building dynamic counters.

This guide will walk you through how to add a real-time post views count widget in Firebase using Firebase Realtime Database and Firebase Firestore, two of its most popular NoSQL databases.


Prerequisites

Before proceeding, ensure you have the following:

  • A Google account to access Firebase.
  • A Firebase project set up.
  • Basic knowledge of HTML, JavaScript, and Firebase.
  • A web application or blog where you want to implement the real-time post views counter.

Step 1: Set Up a Firebase Project

If you don’t already have a Firebase project, follow these steps to create one.

1.1 Create a Firebase Project

  1. Visit the Firebase Console.
  2. Click on Add Project.
  3. Follow the setup steps by entering a project name and selecting Google Analytics if needed.
  4. Click Create Project and wait for Firebase to set up your project.

1.2 Add Firebase to Your Web Application

  1. Once the project is created, click on the Web icon (</>) to add Firebase to a web app.
  2. Provide an app nickname and click Register app.
  3. Firebase will give you a configuration code block for Firebase SDK that looks like this:
javascriptCopy code<script src="https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js"></script><script src="https://www.gstatic.com/firebasejs/9.0.0/firebase-database.js"></script><script>// Firebase configurationconst firebaseConfig = {  apiKey: "YOUR_API_KEY",  authDomain: "YOUR_PROJECT_ID.firebaseapp.com",  databaseURL: "https://YOUR_PROJECT_ID.firebaseio.com",  projectId: "YOUR_PROJECT_ID",  storageBucket: "YOUR_PROJECT_ID.appspot.com",  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",  appId: "YOUR_APP_ID"};// Initialize Firebasefirebase.initializeApp(firebaseConfig);</script>
Copy this code into your HTML file, typically before the closing </body> tag, to initialize Firebase.

Step 2: Set Up Firebase Realtime Database

2.1 Enable Realtime Database

  1. In the Firebase Console, go to your project.
  2. Click on Realtime Database in the left-hand menu.
  3. Click Create Database, choose a location, and select Start in test mode (this provides open access for development purposes but can be restricted later for production environments).
  4. Click Enable.

2.2 Structure Your Realtime Database

In Firebase, the data structure is key. We’ll store post views under a posts node, where each post will have its own unique ID and view count. For example, the structure might look like this:

jsonCopy code{  "posts": {    "postId1": {      "views": 10    },    "postId2": {      "views": 25    }  }}

This allows each post to have its own node with the number of views stored under the views key.


Step 3: Write the Code to Track Views

Now, let’s set up the code to increase the post view count every time a user visits a post.

3.1 Increment the View Count in Real-time Database

Add the following code to your JavaScript file. This code will increment the views for each post every time the post is viewed:

javascriptCopy code// Reference to the Realtime Databaseconst database = firebase.database();// Function to update the view count for a specific postfunction incrementPostViewCount(postId) {  const postRef = database.ref('posts/' + postId + '/views');  // Increment the view count using a transaction  postRef.transaction(function(currentViews) {    return (currentViews || 0) + 1; // Increment by 1, if null, set to 1  });}// Example usage: Call this function on page load or when the post is viewedconst currentPostId = 'postId1'; // Replace with the actual post IDincrementPostViewCount(currentPostId);

Explanation:

  • firebase.database().ref() references the path of the specific post in the Realtime Database.
  • transaction() is used to increment the view count atomically. It ensures that even if multiple users visit the post simultaneously, the view count is updated correctly.

You can call this function on page load, or whenever the post is viewed, to update the view count in real-time.


Step 4: Display the Real-Time View Count

To display the real-time view count on the post, you’ll need to listen for changes in the database and update the view count dynamically.

HTML for Displaying the View Counter:

In your HTML file, you can add an element where the view count will be displayed:

htmlCopy code<div>  <h3>Post Views: <span id="view-counter">0</span></h3></div>

Now, every time a post is viewed, the counter will automatically increment in the Realtime Database, and the updated view count will be displayed on the page.


Step 5: Using Firebase Firestore (Alternative to Realtime Database)

If you prefer to use Firestore instead of Realtime Database, follow these steps.

5.1 Enable Firestore

  1. In the Firebase Console, click on Firestore Database in the left-hand menu.
  2. Click Create Database, select a location, and choose Start in test mode.
  3. Click Next and Enable.

5.2 Structure Your Firestore Database

Firestore stores data in collections and documents. Each post can be a document inside a posts collection, where the view count is stored as a field.

The structure would look like:

javascriptCopy codeposts (collection)   postId1 (document)      views: 10   postId2 (document)      views: 25

5.3 Increment View Count in Firestore

The following code demonstrates how to increment the view count for a specific post in Firestore:

javascriptCopy code// Reference to Firestoreconst db = firebase.firestore();// Function to increment post view countfunction incrementFirestoreViewCount(postId) {  const postRef = db.collection('posts').doc(postId);  // Increment the view count using a transaction  return db.runTransaction((transaction) => {    return transaction.get(postRef).then((postDoc) => {      if (!postDoc.exists) {        // If the post does not exist, create it with 1 view        transaction.set(postRef, { views: 1 });      } else {        // If the post exists, increment the view count        const newViews = (postDoc.data().views || 0) + 1;        transaction.update(postRef, { views: newViews });      }    });  });}// Example usage: Call this function on page load or when the post is viewedincrementFirestoreViewCount(currentPostId);

5.4 Display the Real-Time View Count in Firestore

To display the real-time view count from Firestore, use this code:

javascriptCopy code// Function to get and display the real-time view countfunction displayFirestoreViewCount(postId) {  const postRef = db.collection('posts').doc(postId);  // Listen for real-time updates in the view count  postRef.onSnapshot((doc) => {    if (doc.exists) {      const viewCount = doc.data().views;      document.getElementById('view-counter').innerText = viewCount || 0;    } else {      document.getElementById('view-counter').innerText = 0;    }  });}// Example usage: Call this function on page load or when the post is displayeddisplayFirestoreViewCount(currentPostId);

Once your app is in production, you’ll want to secure your Firebase Realtime Database or Firestore from unauthorized access.

For Realtime Database, go to the Firebase Console, click on Rules, and modify the rules to restrict access. For example:

jsonCopy code{  "rules": {    "posts": {      ".read": true,      ".write": "auth != null" // Only authenticated users can write    }  }}

For Firestore, you can set similar rules in the Firestore Rules tab to allow only authorized users to modify the data.

Method 4: Using Custom CSS and Design Tweaks for Better Appearance

Adding a real-time views counter widget is just the first step. To ensure that the widget fits seamlessly into your blog’s design, you may want to customize its appearance using CSS.

  1. Customizing Third-Party Widgets: Most third-party services provide basic customization options. For example, on Whos.amung.us, you can choose different widget styles, colors, and sizes.
  2. Customizing Your JavaScript Widget: If you are using the Google Analytics API method, you have complete control over how the counter looks. Use CSS to style the #real-time-counter element and make it match your blog’s design.

For example, to create a sleek, modern look, add the following CSS:

#real-time-counter {  font-size: 24px;  color: #333;  background-color: #f9f9f9;  padding: 10px;  border-radius: 5px;  text-align: center;  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);}

Place this CSS in the Theme section of Blogger under Edit HTML or in the custom CSS section if your theme allows it.


Best Practices for Using a Real-Time Views Counter

  1. Monitor Widget Performance: While a real-time views counter can be beneficial, ensure it doesn’t slow down your site. Regularly check your blog’s performance using tools like Google PageSpeed Insights.
  2. Don’t Overdo It: Avoid cluttering your blog with too many widgets. A clean, minimal design is more appealing and user-friendly.
  3. Make It Visible but Not Overpowering: Place the counter in a prominent yet unobtrusive location, such as the sidebar or footer, to avoid distracting readers from the main content.
  4. Ensure Mobile Responsiveness: Make sure that your widget looks good and functions well on both desktop and mobile devices. Test it across different screen sizes to ensure responsiveness.

Senzix Conclusion

Adding a real-time view counter to your Blogger site can significantly improve user engagement, create a sense of community, and offer quick insights into how your content is performing. Whether you choose to use a third-party widget or build a custom solution using the Google Analytics API, the steps outlined in this guide will help you successfully integrate a real-time views counter into your blog.

By following these methods, you’ll not only enhance your blog’s functionality but also provide a more engaging experience for your readers. Remember to test the widget after installation and regularly monitor its performance to ensure that it continues to meet your expectations.

Post a Comment