How To

How To Make Chat Box Using HTML For Website

With the changes in technology, you need to improve your business processes as well. And in this tightly competitive world, it has become an essential thing to get your hands on a personal website that resonates your business, if you running a site or blog that related to live chat support or romance compass than you are in right place once you have got yourself a business website, how do the visitors contact you or ask the queries, for that, you need to have a chat box on your website, so that, everyone can contact you and you make the most out of your business website. If you want to have your hands on the chat box, you can create it on your own by using our guide How To Make Chat Box Using HTML For Website. So, let’s get to it right away

What You Will Be Needing

In this section, we have enlisted some basic requirements to go on for the development of chat box using HTML;

  • You need to have a git installed in your computer
  • You need to have Node.js and NPM installed on your computer
  • You need to have http-server to make sure that HTML files are served right

Procedure

So, finally, it is the time that we start off with the development of a chat box for your website. Follow the below-given steps to get your hands on the chat box for your website;

  1. In the first step, sign upon ChatKit and create an instance on Chatkit once you have signed up
  2. You can name the instance as “html-chatbox” to remember what you are up to

  1. Make sure that you take the credentials because you will need to use them to get in touch with Chatkit
  2. In the next step, you have to create a room within the application but we will use the instance inspector from the dashboard to work this out
  3. Now, we will create a server in order to authenticate the users. We are going to copy the express boilerplate thing to create the server rather than making from scratch

    $ git clone https://github.com/pusher-community/express-boilerplate html-chatbox

  1. Once you have cloned the above-mentioned code, delete the views and then update the package.json as we have done in the section below;

// package.json

{

“dependencies”: {

“@pusher/chatkit-server”: “^1.0.4”,

“body-parser”: “^1.18.2”,

“express”: “^4.16.2”,

“express-handlebars”: “^3.0.0”

}

}

  1. Now, we will remove express-handlebars and then, we will add the chatkit node.js CORS and SDK middleware. So, let’s install the dependencies;

    $ cd html-chatbox

$ npm install

  1. Once you have installed them all, start on for the creation and building of the server. To do that, you will have to replace the server.js content with the following;

// server.js

const express = require(‘express’);

const bodyParser = require(‘body-parser’);

const cors = require(‘cors’);

const Chatkit = require(‘@pusher/chatkit-server’);

 

const app = express();

 

const chatkit = new Chatkit.default({

instanceLocator: ‘YOUR_INSTANCE_LOCATOR’,

key: ‘YOUR_SECRET_KEY’,

});

 

app.use(

bodyParser.urlencoded({

extended: false,

})

);

app.use(bodyParser.json());

app.use(cors());

 

app.post(‘/users’, (req, res) => {

const { username } = req.body;

 

chatkit

.createUser({

id: username,

name: username,

})

.then(() => {

res.sendStatus(201);

})

.catch(err => {

if (err.error === ‘services/chatkit/user_already_exists’) {

console.log(`User already exists: ${username}`);

res.sendStatus(200);

} else {

res.status(err.status).json(err);

}

});

});

app.post(‘/authenticate’, (req, res) => {

const authData = chatkit.authenticate({

userId: req.query.user_id,

});

res.status(authData.status).send(authData.body);

});

 

const port = 3001;

 

app.listen(port, err => {

if (err) {

console.log(err);

} else {

console.log(`Running on port ${port}`);

}

});

  1. By using the chatkit node.js SDK, we will create the new instance for chatkit and replace the secret key and instance locator with your own. After that, we will create a new user with the help of username. After that, just return to the success rate if everything goes on the right track otherwise, there will be errors.
  2. As we are now done with the creation of the server, we will now work our way to the creation of the client. To do that, make a new index.html file and paste the following code into it;

<!– index.html –>

<!DOCTYPE html>

<html lang=”en”>

 

<head>

<meta charset=”UTF-8″>

<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

<meta http-equiv=”X-UA-Compatible” content=”ie=edge”>

<title>Chatbox</title>

<link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css” integrity=”sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB”

crossorigin=”anonymous”>

</head>

 

<body style=”padding-top: 100px; padding-bottom: 100px”>

<div class=”container”>

<div class=”row justify-content-center”>

<div class=”col-md-8″>

<div class=”card”>

<div class=”card-body”>

<div id=”join”>

<form method=”post” id=”username-form”>

<div class=”form-group”>

<div class=’input-group’>

<input type=’text’ name=’username’ class=”form-control” placeholder=”Enter your username”>

 

<div class=’input-group-append’>

<button class=’btn btn-primary’>Join</button>

</div>

</div>

</div>

</form>

</div>

 

<div id=”chatbox” style=”display: none”>

<div class=”row”>

<div class=”col-md-8″>

<div class=”card”>

<div class=”card-header”>Chatbox</div>

<div class=”card-body”>

<dl id=”messageList”></dl>

<hr>

<form id=”sendMessage” method=”post”>

<div class=’input-group’>

<input type=’text’ name=’message’ class=”form-control” placeholder=”Type your message…”>

 

<div class=’input-group-append’>

<button class=’btn btn-primary’>Send</button>

</div>

</div>

</form>

</div>

</div>

</div>

<div class=”col-md-4″>

<div class=”card”>

<div class=”card-header”>Users Online</div>

<div class=”card-body p-0″>

<ul id=”onlineUsers” class=”list-group list-group-flush”></ul>

</div>

</div>

</div>

</div>

</div>

</div>

</div>

</div>

</div>

</div>

 

<script src=”https://unpkg.com/@pusher/chatkit-client”></script>

<script src=”https://unpkg.com/axios/dist/axios.min.js”></script>

</body>

 

</html>

  1. The page will be now categorized into two parts; the actual chat box and a form to enter the username. With this code, the chatbox will appear only if users enter a username. The user will hit the join button and the form will disappear leaving only the chatbox behind.
  2. Now, we will add two scripts to the page. The first one will be the creation of Chatkit JavaScript client Axios and SDK, which will need the HTTP requests and after that, add the code before the </body>

//index.html

<script>

 

const ROOM_ID = ‘ROOM_ID’;

 

const usernameForm = document.getElementById(‘username-form’);

 

usernameForm.addEventListener(‘submit’, e => {

e.preventDefault();

 

const username = e.target.username.value;

 

axios

.post(‘http://localhost:3001/users’, { username })

.then(() => {

document.getElementById(‘join’).style.display = ‘none’;

document.getElementById(‘chatbox’).style.display = ‘block’;

 

const tokenProvider = new Chatkit.TokenProvider({

url: ‘http://localhost:3001/authenticate’,

});

 

const chatManager = new Chatkit.ChatManager({

instanceLocator: ‘PUSHER_INSTANCE_LOCATOR’,

userId: username,

tokenProvider,

});

 

chatManager

.connect()

.then(currentUser => {

currentUser

.subscribeToRoom({

roomId: ROOM_ID,

messageLimit: 100,

})

.catch(error => console.error(error));

})

.catch(error => console.error(error));

});

</script>

  1. Now, we will get the username format first and then add the event listener when you submit the form. Once you submit the form, make sure you don’t refresh the page to prevent the default form behavior. After that, you can easily make the POST request to the /users on the server and pass along the username. Once the procedure is successful, the username will be hidden and the chatbox will be displayed.
  2. After this, tokenprovider will be created using the endpoint of the server. Once done with that, create the chatmanager instance locator, tokenprovider, and user ID. We can connect to chatkit with the help of chatmanager. Once the procedure is successful, you will be given access to the current user and then just subscribe to the current user with the earlier created room. You can set the message limit as you want. For example, if you want to set the message limit to 100, set the messagelink:100 and if you want it to 0, set the messagelink:0
  3. Now, you have made the chatbox, we will now add the options of receiving and sending the message. In order to make that work, update subscribetoroom such as below;

subscribeToRoom({

roomId: ROOM_ID,

hooks: {

onMessage: message => {

const { senderId, text } = message;

 

const messageList = document.getElementById(‘messageList’);

const messageUser = document.createElement(‘dt’);

const messageBody = document.createElement(‘dd’);

 

messageUser.appendChild(document.createTextNode(senderId));

messageBody.appendChild(document.createTextNode(text));

 

messageList.appendChild(messageUser);

messageList.appendChild(messageBody);

},

onPresenceChanged: (state, user) => {

if (currentUser.id !== user.id) {

addUserElement(user);

}

 

if (state.current === ‘offline’) {

document.getElementById(user.id).remove()

}

},

},

messageLimit: 100,

})

.then(() => {

currentUser.rooms[0].users.forEach(user => {

if (user.presence.state === ‘online’) {

addUserElement(user);

}

});

 

const sendMessage = document.getElementById(‘sendMessage’);

sendMessage.addEventListener(‘submit’, e => {

e.preventDefault();

 

const message = e.target.message.value;

 

currentUser.sendMessage({

text: message,

roomId: ROOM_ID,

});

 

e.target.message.value = ”;

});

})

.catch(error => console.error(error));

  1. Now, we will add the onMessage hook to the object and the hook will be triggered once you receive some message. We will just create the HTML elements with the message text and sender ID to create the hook and then, we will append the HTML to the chatbox.
  2. Once you have submitted the chat text, you have to make sure that the page isn’t refreshed and then, you will enter the message into the text box.
  3. With the help of current user object, we will use the sendmessage method to the ID and message content and then, the text box will be cleared
  4. Now, we will work on making sure that we are able to see the active status on the chat. If you want to show the active status to the chat, copy and paste the following code immediately;

document.getElementById(‘sendMessage’):

currentUser.rooms[0].users.forEach(user => {

if (user.presence.state === ‘online’) {

addUserElement(user);

}

});

  1. Now, we will work on creating the adduserelement function and the code is given below as;

function addUserElement(user) {

const onlineUsers = document.getElementById(‘onlineUsers’);

const singleUser = document.createElement(‘li’);

 

singleUser.className = ‘list-group-item’;

singleUser.id = user.id;

 

singleUser.appendChild(document.createTextNode(user.name));

onlineUsers.appendChild(singleUser);

}

  1. If you want to know when a user goes online or offline, you can use the following code to insert in the hooks object;

…,

onPresenceChanged: (state, user) => {

if (currentUser.id !== user.id) {

addUserElement(user);

}

 

if (state.current === ‘offline’) {

document.getElementById(user.id).remove()

}

},

Testing the chatbox

You have done all the work but you cannot launch the chatbox. Before launching it, you need to test and to do that, start the server;

    $ node server.js

Should be running on http://localhost:3001.

Also, in a new terminal, start a dev server to serve the index.html file:

    $ http-sever

You can use any dev server but make sure that the client is accessible on http://127.0.0.1:8080

After that, the result should be like this;

This was all about How To Make Chat Box Using HTML For Website and we hope that you got benefits from this. If you want any more help, you can ask us in the comment section below and we will be here to help you out. Thank you!

Seerat Ul Qamar

I'm Seerat Ul Qamar. When I'm not eating, I'm typing away at my desk. I've got a knack for writing from others' perspectives. I can guarantee the content and information that you have been looking for!

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button
Close