Tutorial: Try it yourself

Tips and TricksExamples Try it yourself

Here is a simple example on how to create a simple chat using Webcom.

1. Create a Webcom application on the Webcom developer console

Select "public access" as a default security rule. On the "Authentication / methods" tab, enable "guest" authentication mode.

2. On Padviews, create a new document with a "web page" type

Copy and paste this code sample (replace “<your-app>” with your actual application identifier):

<!doctype html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery.qrcode@1.0.3/jquery.qrcode.min.js"></script>
    
    <script type='text/javascript' src='https://cdn.jsdelivr.net/npm/webcom@3.3.0/webcom.js'></script>

    <title>WebCom Simple Chat</title>
    
    <!-- CHAT CSS -->
    <style>
      .example-chat {
        border: 1px solid black;
        background-color: white;
         padding: 0px;
        width: 500px;
        height: 400px;
        border-radius: 10px;
      }
      #example-messages li {
        display: block;
      }
      .example-chat ul {
         list-style: none;
         margin: 0px;
         padding: 10px;
         height: 270px;
         overflow: auto; 
      }

      .example-chat ul li {
         margin-bottom: 2px;
         line-height: 16px; 
      }

      .example-chat ul li:last-child {
         margin: 0px; 
      }

      .example-chat ul .example-chat-username {
        margin-right: 4px; 
      }

      .example-chat header {
        font-weight: bold;
        text-align: center;
        padding: 4px;
      }
      
      .example-chat-toolbar, footer {
          padding: 5px;
        font-weight: bold;
        background-color: lightgrey;
        border-top: 1px solid black;
        border-bottom: 1px solid black;
      }
    </style>
  </head>
  
  <body>
    <!-- CHAT MARKUP -->
    <div class="example-chat l-demo-container">
      <header>WebCom Chat Demo</header>
      
      <div class="example-chat-toolbar">
        <label for="nameInput">Username:</label>
        <input type="text" id="nameInput" placeholder="enter a username...">
      </div>
      
      <ul id="example-messages" class="example-chat-messages"></ul>
      
      <footer>
        <input type="text" id="messageInput"  placeholder="Type a message...">
      </footer>
    </div>
    
    <!-- CHAT JAVASCRIPT -->
    <script>
      
    // CREATE A REFERENCE TO YOUR WEBCOM APP
    const app = Webcom.App("<your-app>"); // !!! REPLACE <your-app> WITH YOUR ACTUAL APP ID HERE !!!
    const messagesRef = app.serverlessDb.rootNode.relativeNode('simple-chat');
    const auth = app.authentication;
    
    // REGISTER DOM ELEMENTS
    const messageField = $("#messageInput");
    const nameField = $("#nameInput");
    const messageList = $("#example-messages");
     
    // AUTHENTICATION - GUEST MODE
    auth.subscribe((error, authState) => {
      if (error) {
        // catch error here
        console.log("Authentication error: ", error);
      } else {
        if (authState.isAuthenticated()) {
          // A user is already signed in
          console.log("Signed in with the following identity:" , authState);
          // We can start the app
          startApp();
        } else {
          console.log("Disconnected");
          // call guest auth method to sign the user in, the auth callback will be recalled once authenticated
          auth.signInAsGuest();
        }
      }
    });
    

    // MAIN APP CODE
    function startApp() {
      // LISTEN FOR KEYPRESS EVENT
      messageField.keypress((e) => {
        if (e.keyCode == 13) {
          //FIELD VALUES
          const username = nameField.val();
          const message = messageField.val();
          //SAVE DATA
          messagesRef.push({name:username, text:message});
          messageField.val("");
        }
      });
      
      // Add a callback that is triggered for each chat message.
      messagesRef.subscribe(Webcom.Event.Child.Addition, Webcom.Callback(snapshot => {
        //GET DATA
        const data = snapshot.val();
        const username = data.name || "anonymous";
        const message = data.text;
        
        //CREATE ELEMENTS MESSAGE & SANITIZE TEXT
        const messageElement = $("<li>");
        const nameElement = $("<strong class='example-chat-username'></strong>");
        nameElement.text(username);
        messageElement.text(message).prepend(nameElement);
        
        //ADD MESSAGE
        messageList.append(messageElement)
          
          //SCROLL TO BOTTOM OF MESSAGE LIST
        messageList[0].scrollTop = messageList[0].scrollHeight;
      }));
    }
    
    </script>
  </body>
</html>

3. Set some security rules

On the Webcom developer console, in "security" tab, copy and paste this security rule:

{
  "rules": {
    ".read": false,
    ".write": false,
    "simple-chat": {
      ".write": "auth!==null",
      ".read": "auth!==null",
      "$message": {
        "name": {
          ".validate": "newData.isString()"
        },
        "text": {
          ".validate": "newData.isString()"
        },
        "$other": {
          ".validate": false
        }
      }
    }
  },
  "platform-security-tags": []
}

Congratulations !

You have done your first Webcom app !

This app, as easy to create it can be, is already able to store and retrieve data, to react to events from the back end and to share data between multiple users. It also has a session-based authentication that you can easily replace with another authencation mode offered by Webcom.