Tutorial: Simple Chat

Tips and TricksExamples Simple Chat

Here a simple example on how to create a Simple Chat using Webcom.

  1. Edit a html file in your favorite editor. Here is a boilerplate
<!DOCTYPE html>
  <title>Webcom chat demo</title>
  1. Include the Webcom javascript library in head section
    <script src='https://cdn.jsdelivr.net/npm/webcom@2.8/webcom.js'></script>
  1. Create HTML markups for a basic chat UI in body section
    <div class="example-chat">
      <header>Webcom chat demo</header>
      <div class='toolbar'>
        <label for="nameInput">Username:</label>
        <input type='text' id='nameInput' placeholder='enter a username...'>
      <ul id='messages'></ul>
        <input type='text' id='messageInput'  placeholder='Type a message...'>
  1. Before body closing tag (</body>), create a <script> section and create a Webcom reference. Next steps write to this <script> section
        var messagesRef = new Webcom('chat');
  1. Register some DOM elements
var messageField = document.getElementById('messageInput'),
    nameField = document.getElementById('nameInput'),
    messageList = document.getElementById('messages');
  1. Listen for KeyPress events
// Listen for "enter" pressed
messageField.addEventListener('keypress', function (e) {
  var msg = messageField.value;
  if (e.keyCode === 13 && msg !== '' ) {
    // Save data
      name: nameField.value, 
      text: msg
    // Clear message field
    messageField.value = '';
  1. Subscribe to every chat message by adding a callback that is triggered every time a child is added to the Webcom reference
// Add a callback that is triggered for each chat message.
messagesRef.on('child_added', function (snapshot) {
  // Get data
  var data = snapshot.val(),
      username = data.name || "anonymous",
      message = data.text;

  // Create message elements and sanitize text
  var messageElement = document.createElement("li"),
      nameElement = document.createElement("strong");
  nameElement.setAttribute('class', 'username');
  nameElement.innerText = username;
  messageElement.innerText = message;
  messageElement.insertBefore(nameElement, messageElement.childNodes[0]);

  // Add message

  // Scroll to bottom message list
  messageList.scrollTop = messageList.scrollHeight;

For styles, create a new <style> tag in <head> section and copy/paste CSS content of jsBin CSS tab

    <!-- content of CSS JSBin tab -->

Complete HTML

Here is full example in jsBin, test it and modify it as you want !

JS Bin on jsbin.com

Or use our version.

You can access the Webcom developer console and visualize data exchanged in this base in real time with the account : sandbox@list.orange.com (password : sandbox)

Then access the chatsandbox application and browse data