Build-Basic-JavaScript-Web-Chat-App-with-ChatEngine

Build Basic JavaScript Web Chat App with ChatEngine

In this tutorial, we’ll build a simple JavaScript chat app for web and mobile web using ChatEngine, our SDK and APIs for building chat applications. We’ll cover basic messaging, then add a couple additional features: presence, message history, and markdown support.

The full code we’ll be referencing is available here (.js) and here (.html).

Quick Setup

Before getting started, you’ll have to setup ChatEngine via our ChatEngine Quick Start. This enables you to use your own PubNub application keyset and automagically sets up your account to use ChatEngine.

Ensure a static file server is running from the parent directory of the repo. If not, instantiate a static HTTP server from the project root (either NodeJS or Python):

## NodeJS v6:
http-server &

## Python:
python -m SimpleHTTPServer &

## To exit either server:
fg
CTRL-C

Once the server is running, open the javascript/desktop.html file in your preferred web browser:

## Open file with default browser:
> open javascript/desktop.html

To further experience the functionality of the Javascript ChatEngine example, open javascript/desktop.html in a local incognito browser to chat with yourself.

It should be noted that upon refreshing the webpage, a new user will be created for you to impersonate. After refreshing the chat webpage, please note that users previously created will linger for a small time before the client determines the previously created user instance is offline.

Messaging

By now you should have one desktop client (or more) running locally. Time to inject your PubNub publish and subscribe keys into the application.

Open javascript/desktop.js, find the following code snippet (its a the top of the file) and replace the demo’s default publish and subscribe keys with your own:

// Be sure to replace empty strings with your own App's Publish & Subscribe keys
// otherwise the demo keys will be used.
let userPubKey = '' || 'PUB_KEY_HERE';
let userSubKey = '' || 'SUB_KEY_HERE';

Be wary when instantiating ChatEngine with argument debug:true. Leaving the option true will output console.debug() statements to the browser running the client. With greater load, this flag will cause delays and slowness. Be sure to set debug: false or simply don’t include the arg (defaults to false).

Once finished, be sure to save the changes to javascript/desktop.js and refresh your browser. Once refreshed, the client application will utilize your personal PubNub keys to power ChatEngine.

User Presence

Ideally, a chat client would display whether or not users are online or offline, and update it in realtime. It’s the ‘buddy list’ we all know and love. Thankfully, PubNub Presence provides such functionality.

Let’s take a look at the bindUsers() function within javascript/desktop.js:

// add PubNub Presence: to display users [online|offline] state
bindUsers: function() {

    // when a user comes online, render them in the online list
    this.chat.on('$.online.*', function(data) {
        app.users.unshift(data.user);
        app.renderUsers();
    });

    // when a user goes offline, remove them from the online list
    this.chat.on('$.offline.*', function(data) {

        for (var i in app.users) {
            if (app.users[i].uuid == data.user.uuid) {
                delete app.users[i];
            }
        }

        app.renderUsers();

    });

},

Chat Message History

Currently, the application does not render messages previously sent prior to invoking the current session. ChatEngine allows one to easily populate the chat history with messages previously sent on a specified chat channel. To do so, uncomment the following snippet within below the ready() function within javascript/desktop.js:

ready: function(data) {
    this.me = data.me;
    this.chat = new this.ChatEngine.Chat('chatengine-meta');

    // uncomment code below to leverage PubNub's MSG History feature
    this.chat.on('$.connected', () => {

        // search for 50 old `message` events
        this.chat.search({
          event: 'message',
          limit: 50
        }).on('message', (data) => {

          // when messages are returned, render them like normal messages
          console.debug(data);
          app.renderMessage(data, true);

        });

    });

    this.bindEvents();
},

Plugins

ChatEngine provides a ton of off the shelf plugins. In this example, we’ll provide you with the steps to add markdown rendering to your chat messages, allowing users to bold, italicize, or format code blocks directly in chat messages.

Navigate to the ready() function and uncomment the following:

// UNCOMMENT code below to enbale the 'markdown-plugin'
const markdown = ChatEngineCore.plugin['chat-engine-markdown']();
this.chat.plugin(markdown);

Lastly, in order for Handlebars to properly render the rich HTML, enclose both instances of messageOutput within javascript/desktop.html with triple curly brackets. See example below:

<div class="message other-message float-right">
    {{{messageOutput}}}
</div>

You now have a functioning web chat application powered by ChatEngine! For more ChatEngine tutorials, check out our ChatEngine resouces section.

Use Cases:

Try PubNub Today

Connect up to 100 devices for Free