How to Create a Simple Chat Room with JavaScript
The popularity of chat rooms has been an ongoing topic since its peak in the early '90s. While much more sophisticated communication systems carry more weight today, it's still important to understand the basics.
What You'll Learn from this Tutorial
This tutorial explains the steps needed to create a simple JavaScript chat room and your choice of server-side technology, between either PHP or Node.js. The client-side portion, which we'll be discussing here, will work with both server-side solutions.
You'll also learn how to set your username with a JavaScript prompt, store in localStorage
, and then pass on your username with a custom message for everyone in the chat room to read.
The best parts are the code is clean and very easy to set up, and it's free. You don't have to sign up or pay for any third-party applications or services to get it working. All you need are the code examples below and you're off!
Prerequisites
You'll need the following before you can proceed:
- Administrative access to your server. In these examples, we use a Ubuntu server.
- Apache with a virtual host
- An SSL certificate installed an configured in your virtual host
- WebSocket setup and configuration within Apache
What Are WebSockets?
A WebSocket is a computer communications protocol, providing multiple real-time bi-directional communication channels over a single TCP connection.
With standard HTTP and HTTPS connections, a server request is required to respond. The user initiates a page request to a URL, and that data is then returned to the user and displayed in a web browser.
With WebSockets, the idea of a request is different in that you can pass data to and from a server and your users without initiating a full-page request.
A few practical examples of WebSocket uses include:
- Real-time applications
- Chat rooms or apps
- Notification handling
- Online multiplayer games
The JavaScript Chat Room Code
In this case, we'll be creating a very simple JavaScript chat room to illustrate the fundamentals of how WebSockets work.
First, let's get started by creating our HTML display and form:
<div id="chat">
<div id="chat-messages">
<form id="chat-form" method="post">
<input type="text" name="message" placeholder="Enter a message..." maxlength="500" autocomplete="off">
<button type="submit">Send</button>
</form>
</div>
This is a very basic form. A chat-messages
container is created to hold the messages received from all users. And chat-form
is created to hold an input field and submit button to send messages to the other users.
Initializing WebSockets
Now let's initialize our WebSockets:
var ws_uri = "ws://[your-domain]:9600";
var websocket = new WebSocket(ws_uri);
The ws_uri
variable is the URL in which your WebSocket server is running. You'll need to make sure that you change [your-domain]
to your correct domain name.
The next line initializes the WebSocket connection so you can begin sending and receiving data.
WebSocket Event Handling
There are a few note-worthy event handlers to consider when setting up your WebSocket functionality. Here are the ones we'll be using in short detail:
onopen
: An event listener called when the WebSocket connection has opened.onclose
: An event listener called when the websocket connection has closed.onerror
: An event listener called when an error occurs with the connection.onmessage
: An event listener called when a message is received from the server.
Within each of these event handlers, we've added custom messages that will append to the chat-messages
container, notifying anyone in the chat room of the current connection status.
// on websocket open:
websocket.onopen = function(event) {
MessageAdd('<div class="message green">You have entered the chat room.</div>');
};
// on websocket close:
websocket.onclose = function(event) {
MessageAdd('<div class="message blue">You have been disconnected.</div>');
};
// on websocket error:
websocket.onerror = function(event) {
MessageAdd('<div class="message red">Connection to chat failed.</div>');
};
We'll talk about the MessageAdd()
method here in a bit.
To receive messages from the server and display them for all users in the chat room, we need to set up the onmessage
event handler:
websocket.onmessage = function(event) {
var data = JSON.parse(event.data);
if (data.type == "message") {
MessageAdd('<div class="message">' + data.username + ': ' + data.message + '</div>');
}
};
This code is pretty simple. The parsed JSON data is stored to our local data
variable.
A check for the data type is then done. This isn't required in all cases. Since we're passing variable type
in our object and returning it from the server, I've added it here. This is to illustrate that we could send different types of data to the server and return to the user in real-time, such as a new notification, a new user entering the chat room, etc.
Submitting Form Data With WebSockets
We're set up our chat room to receive data from the server. Now we need a way to submit custom messages to other users in the chat room:
document.getElementById("chat-form").addEventListener("submit", function(event) {
event.preventDefault();
var message_element = document.getElementsByTagName("input")[0];
var message = message_element.value;
if (message.toString().length) {
var username = localStorage.getItem("username");
var data = {
type: "message",
username: username,
message: message
};
websocket.send(JSON.stringify(data));
message_element.value = "";
}
}, false);
This chunk of code creates an event handler for the chat-form
form element we created earlier. The message is then pulled from the input field. If the message is at least one character long, a JavaScript object is created holding some data about the message, the user, and the input text. The websocket.send()
method then submits a stringified version of our object to the server, and the input field value is cleared.
Creating Your Chat Room Username
We can easily prompt and set a username by using a little bit of JavaScript magic:
function Username() {
var username = window.prompt("Enter your username:", "");
if (username.toString().length > 2) {
localStorage.setItem("username", username);
}
else {
alert("Your username must be at least two characters.");
Username();
}
}
Username();
The above code snippet uses a JavaScript prompt to allow the user to enter their username.
A minimum of two characters is required for the user to pass validation. If less than two characters, the user is alerted that the username is invalid then is prompted to enter it again. If validation is successful, the username is stored in localStorage
to be used later when submitting messages.
You can learn more about localStorage here.
You should of course find more secure ways to store a username as it can be easily manipulated as a plain string in localStorage. This is outside the scope of this tutorial and is just to show you how data can be sent via websockets.
Display the Chat Room Messages
Finally, we'll introduce the functionality behind the MessageAdd()
method:
function MessageAdd(message) {
var chat_messages = document.getElementById("chat-messages");
chat_messages.insertAdjacentHTML("beforeend", message);
chat_messages.scrollTop = chat_messages.scrollHeight;
}
Here, a message
string is passed into the function, containing the input field text from our chat form. The chat-messages
container is held in memory while we then append the message using JavaScript's insertAdjacentHTML()
method.
At the end of our function, an automatic scroll is pushed to the chat-messages
container. This ensures that, as new messages are received from the server, the container scrollbar pushes downward automatically so new messages will continue to remain in view for the user.
Conclusion
This tutorial only touches on the very basics of what WebSockets can do. The possibilities are nearly endless as you get into developing more complex systems.
Before this will function properly, you'll need to either set up a PHP WebSocket server or the Node.js WebSocket server. You'll be required to use HTTPS and WSS protocols in a production environment, so an SSL certificate is also required.
You can view the full JavaScript Chat code in our GitHub repository.
Created: April 14, 2020