Now4real Client API tutorial

Why use the Client API?

Now4real offers a modern, developer-friendly, and well-documented JavaScript API that allows you to access all the functions provided by the service, such as: presence send and receive, real-time counter, rankings, and map updates, chat message send and receive, typing indicators, and much more.

The ready-made Now4real widget, which you can install on your site via the provided script or WordPress plugin, is actually implemented on top of the Now4real API. With the API, you can create your own front-ends, widgets, and user interfaces, giving you full control over the presentation logic of analytics and chats:

  • Create custom widgets: From minimalistic to extensive designs, unleash your creativity!
  • Embed presence counters: Show presence counters directly within your pages, like displaying the number of current readers next to each article title on a news site homepage.
  • Full chat API: Implement your own chat front-end while leveraging the fully managed Now4real chat back-end (the Now4real cloud).

For detailed guidance, please consult the API reference documentation. If you have any questions or need support, visit our community forum or email us at support@now4real.com.

A few definitions

Let’s quickly introduce a few terms to make sure we are on the same page…

  • Page presence: Presence of a person on a page of a website (the browser tab must be in the foreground at that moment).
  • Instant community: Group of people present on the same web page at the same moment.
  • Page viewer counter: Real-time counter of people who are present on a page.
  • Site viewer counter: Real-time counter of people who are present on any page of the site.
  • Pagechat: A group chat that lives on a web page (it’s like a chat room dedicated to that page).
  • Page chatter counter: Real-time counter of people who are chatting on a page (in a pagechat).
  • Site chatter counter: Real-time counter of people who are chatting on any page of the site (in any pagechat).
  • Page viewer ranking: Real-time list of pages with most viewers.
  • Page chatter ranking: Real-time list of pages with most chatters.
  • Page viewer heatmap: Real-time density of page viewers on the world map (at country level).
  • Site viewer heatmap: Real-time density of site viewers on the world map (at country level).

The Now4real API enables you to get these and other data in real time from the Now4real cloud. These are subjects you can subscribe to, receiving values asynchronously pushed to your code (a synchronous get method is also available).

Additionally, the Now4real API includes all the building blocks for chat functionality, including authentication, message delivery, typing indicators, error management, and more.

Quick tutorial

Let’s use the Now4real API to create a simple web page that shows the page viewer counter in real time. Our goal is to display how many people have that page open and visible in the foreground on their device at any moment.

This tutorial focuses on presence detection and does not cover the chat functionality. It is primarily aimed at helping you get started with the Now4real API. You can find detailed information on all the subjects and functions available for sending and receiving chat messages, typing indicators, and more in the comprehensive Now4real API reference documentation.

Create an HTML page

First, create a simple page that will contain our project code. Create an empty file named tutorial.html and paste the code below.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Tutorial: Real-time presence counter</title>
  </head>
  <body>
    
  </body>
</html>

Load the Now4real library

Load the Now4real library to see things happen. The library will immediately connect to the Now4real cloud and send a presence signal when a user has the page in the foreground.

Paste the code below before the </body> tag.

<script>
  window.now4real = window.now4real || {};
  now4real.config = {
    target: 'api'
  };
  now4real.onload = function () {
    console.log('Now4real loaded');
  };
  (function () { var n4r = document.createElement('script'); n4r.type = 'text/javascript'; n4r.async = true; n4r.src = 'https://cdn.now4real.com/now4real.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(n4r, s); })();
</script>

This code loads the library from the https://cdn.now4real.com/now4real.js URL, specifying that we only need the API and not the widget (target: ‘api’ in now4real.config). It logs a message to the browser console when the library is loaded (see now4real.onload).

Add the front end

Add some basic HTML markup to display our presence counter.

Paste the code below after the <body> tag.

<h1>Real-time presence counter</h1>
<div id="counter" style="color: #39aae1; font-size: 3rem; font-weight: bold">
  -
</div>
<div>This is the number of people who are viewing this page right now!</div>
<p>
  <b>Context:</b><br>
  <span id="context" style="color: #39aae1; font-size: 1.2rem"></span>
</p>

The real-time counter updates will be displayed inside the div element with id=”counter”. In the span element with id=”context” we will display the pageContext (more details below).

Get the counter

To receive real-time asynchronous updates to the counter, we’ll subscribe to the COUNTER_PAGE_VIEWERS subject.

Paste the code below after the <script> tag.

function subscribeCounter () {
  const counterEl = document.getElementById('counter');
 
  now4real.subscribe('COUNTER_PAGE_VIEWERS', function (counterUpdate) {
    let updatedValue = counterUpdate.data.value;
    counterEl.innerText = updatedValue;
  });
}

The subscribeCounter function uses the Now4real API to subscribe to the COUNTER_PAGE_VIEWERS subject while defining a callback function that is called every time a new update is pushed from the Now4real cloud. We read the update value (counterUpdate.data.value) and write it into the div element with id=”counter”.

Get the context

This part of the tutorial is not needed for reaching our goal of displaying the real-time presence counter, but it is useful to help you understand another concept of Now4real.

How does Now4real decide whether different users should be considered on the same page so that it can increase the same counter? By means of the context.

First, the site must be the same. Now4real gets the site as the window.location.host of the page. This is called the site context (or siteContext).

Then, the page must be the same. Now4real gets the page as the window.location.pathname of the page (with a few exceptions). This is called the page context (or pageContext).

By concatenating the site context and the page context, you can know the full context of the page. To display it, paste the code below after the subscribeCounter function.

function showContext () {
  let context = now4real.siteContext + now4real.pageContext;
  document.getElementById('context').innerText = context;
}

The showContext function uses the Now4real API to get the site and pageContexts and write them into the span element with id=”context”.

In the “Let’s play” section, we will explain what’s the context of pages loaded from the disk.

Putting it all together

Below is the final code of our tutorial.html page. You can also find it on GitHub.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Tutorial: real-time presence counter</title>
</head>
<body>
  <h1>Real-time presence counter</h1>
  <div id="counter" style="color: #39aae1; font-size: 3rem; font-weight: bold">
    -
  </div>
  <div>This is the number of people who are viewing this page right now!</div>
  <p>
    <b>Context:</b><br>
    <span id="context" style="color: #39aae1; font-size: 1.2rem"></span>
  </p>
 
<script>
  function subscribeCounter () {
    const counterEl = document.getElementById('counter');
 
    now4real.subscribe('COUNTER_PAGE_VIEWERS', function (counterUpdate) {
      let updatedValue = counterUpdate.data.value;
      counterEl.innerText = updatedValue;
    });
  }
 
  function showContext () {
    let context = now4real.siteContext + now4real.pageContext;
    document.getElementById('context').innerText = context;
  }
   
  window.now4real = window.now4real || {};
  now4real.config = {
    target: 'api'
  };
  now4real.onload = function () {
    console.log('Now4real loaded');
    subscribeCounter();
    showContext();
  };
  (function () { var n4r = document.createElement('script'); n4r.type = 'text/javascript'; n4r.async = true; n4r.src = 'https://cdn.now4real.com/now4real.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(n4r, s); })();
</script>
</body>
</html>

And this is the result when you open the page in a browser loading it from the disk:

Let’s play!

Now that the sample page is ready, let’s have some fun while learning more about contexts and visibility.

  1. Test locally:
    • You’ve saved your tutorial.html file to the disk. Open it with your favorite browser. The counter should display “1”, unless someone else in the world is viewing a similar tutorial.html page (more on this later). In that case, just rename your HTML file to something unique for this experiment.
    • Open the same file a second time. It will appear in a second browser tab, and the counter will show “1” again because that’s the only tab in the foreground. Now, drag that tab out of the current window, so that you have two separate browser windows displaying the tutorial page. The counter will show “2”.
    • If you minimize one of the windows, the counter will go down to “1”. You can try with more windows and see the counter increase accordingly.

Note: A page is considered visible if it is displayed in the foreground tab of a non-minimized window. Some browsers can even detect if the window is covered by another application window and report it as non-visible.

The video below shows a demo where three different browsers open the same page. Each time a browser tab is brought to the foreground or the background, the presence counter instantly updates on all browsers. Pretty cool, right?

  1. Test on a web server:
    • Deploy the tutorial.html page to a web server if you have one available. This allows you to open the same page from different devices.
    • For example, open your page from both a desktop computer and a smartphone. The counter will show “2”.
    • Switch off the screen of your smartphone, and the counter will drop to “1”. Switch it back on, and the counter returns to “2”.

No Web Server? No problem! We’ve hosted the tutorial.html page on our server for you to play with: https://now4real.com/tutorial.html. Obviously, if other people are viewing this page besides you, the counter will reflect that.

About the site context

Let’s go back to the tutorial.html page loaded from your local file system. You can see that the site context is calledshared-public-sandbox.test“. This is a special sandbox context that allows you to test your Now4real code without mounting it on an actual domain. This context originates automatically whenever you load the page from the file system or from a web server on localhost.

The nice thing is that the sandbox context is shared among all the Now4real users. As long as you load pages from disk or from a localhost server, you can meet other developers who are working in the sandbox.

On the other hand, if you load the page from a web server with a domain name, the site context will be given by the domain name. You can see this by loading tutorial.html from your web server or from ours. The site context reported on the page is no longer “shared-public-sandbox.test” but the actual domain name.

Please see the documentation of the siteContext constant.

Adding the widget

One more step… Let’s add the standard Now4real widget to the tutorial.html page, without removing the code we developed above. It’s enough to change the target in your now4real.config object as follows:

now4real.config = {
  target: 'api+widget'
};

Reload the page, and you’ll see something like this:

This makes it easy to test all the features of Now4real, including the chat, while you are developing your code.

About the page context

Finally, how about the page context? As you can see, when loading the page from the disk, it is just the file name (with a leading ‘/’). So, in our tutorial, it’s/tutorial.html(or whatever name you gave to the file). If you load the page from a web server, the full path is taken. So, if you deployed the page at, say,https://www.example.com/test/tutorial.html“, the site context will be “www.example.com“, and the page context will be/test/tutorial.html“. By default, any query string is not considered. This means that the following URLs would all be considered part of the same context:

– https://www.example.com/test/tutorial.html
– https://www.example.com/test/tutorial.html?p=4
– https://www.example.com/test/tutorial.html?abc=xyz

Remember, you have full control over the page context, with the ability to customize or even override it completely. Please see the documentation of the pageContext constant and the page_context property within now4real.config.

Next steps

This tutorial is extremely basic but should help you get started quickly with the Now4real API. There are tons of other things you can do with the API! You can get more counters, ranking lists, and world heatmaps. And of course you have full-fledged APIs to manage the chats, create your own pagechat front end, and much more. Please take some time to go through the Now4real API reference and explore it.

To learn how to integrate the user authentication with the existing authentication of your site based on the JWT standard, check out the Custom Auth documentation.

In case of doubt and for any issue or feedback, get back to us through the public forum or drop us an email at support@now4real.com.

Add Now4real to your site now

It's easy. It's free.

Enable your visitors to chat with each other. Let them find out the most popular pages.
Spark up instant communities on your website!

© 2024 Now4real Srl. All rights reserved. P.IVA IT10328990964. Illustrations by Freepik Storyset