Quick Start

Learn how to add CometChat to your JavaScript website in minutes.

This guide demonstrates how to add chat to a Javascript application using CometChat. Before you begin, we strongly recommend you read the Key Concepts guide.

👍

Improvements in V3.0

Faster connection & response times
Higher rate limits
Supports up to 100K users in a group
Unlimited groups
Support for Transient Messages
Real-time user & group members count
And more!

I want to explore a sample app (includes UI)

Open the app folder in your favourite code editor and follow the steps mentioned in the README.md file.

Download React Chat App

Download Angular Chat App

Download Vue Chat App

Get your Application Keys

Signup for CometChat and then:

  1. Create a new app
  2. Head over to the API & Auth Keys section and note the Auth Key, App ID & Region

Add the CometChat Dependency

NPM

First, install via npm

npm install @cometchat-pro/[email protected] --save

Then, import the CometChat object wherever you want to use CometChat

import { CometChat } from "@cometchat-pro/chat"

HTML (via CDN)

Include the CometChat Javascript library in your HTML code

<script type="text/javascript" src="https://unpkg.com/@cometchat-pro/[email protected]/CometChat.js"></script>

Initialize CometChat

We suggest you call the init() method on app startup, preferably in the index.js file.

var appID = "APP_ID";
var region = "REGION";
var appSetting = new CometChat.AppSettingsBuilder().subscribePresenceForAllUsers().setRegion(region).build();
CometChat.init(appID, appSetting).then(
  () => {
    console.log("Initialization completed successfully");
    // You can now call login function.
  },
  error => {
    console.log("Initialization failed with error:", error);
    // Check the reason for error and take appropriate action.
  }
);

Make sure you replace the APP_ID with your CometChat App ID and REGION with your app region in the above code.

Login your user

Once initialization is successful, you will need to create a user.
To create users on the fly, you can use the createUser() method. This method takes a User object and the Auth Key as input parameters and returns the created User object if the request is successful.

let authKey = "AUTH_KEY";
var uid = "user1";
var name = "Kevin";

var user = new CometChat.User(uid);

user.setName(name);

CometChat.createUser(user, authKey).then(
    user => {
        console.log("user created", user);
    },error => {
        console.log("error", error);
    }
)

Make sure that UID and name are specified as these are mandatory fields to create a user.

Once you have created the user successfully, you will need to log the user into CometChat using the login() method.

We recommend you call the CometChat login() method once your user logs into your app. The login() method needs to be called only once.

var UID = "SUPERHERO1";
var authKey = "AUTH_KEY";

CometChat.login(UID, authKey).then(
  user => {
    console.log("Login Successful:", { user });    
  },
  error => {
    console.log("Login failed with exception:", { error });    
  }
);

Make sure you replace the AUTH_KEY with your CometChat Auth Key in the above code.

📘

Sample Users

We have set-up 5 users for testing having UIDs: SUPERHERO1, SUPERHERO2, SUPERHERO3, SUPERHERO4 and SUPERHERO5.

The login() method returns the User object on Promise resolved containing all the information of the logged in user.

🚧

UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed.

Send a message

Once your user has logged in, you can send a message using the sendMessage() method.

var receiverID = "SUPERHERO2";
var messageText = "Hello";
var receiverType = CometChat.RECEIVER_TYPE.USER;

var textMessage = new CometChat.TextMessage(receiverID, messageText, receiverType);

CometChat.sendMessage(textMessage).then(
  message => {
    console.log("Message sent successfully:", message);
    // Do something with message
  },
  error => {
    console.log("Message sending failed with error:", error);
    // Handle any error
  }
);

Parameter

Description

receiverID

The UID or GUID of the recipient

messageText

The message string to be sent

messageType

The type of the message that needs to be sent which in this case is MESSAGE_TYPE.TEXT (text)

receiverType

The type of the receiver to whom the message is to be sent i.e RECEIVER_TYPE.USER (user) or RECEIVER_TYPE.GROUP (group)

Once the message is sent successfully, you will receive the message information as TextMessage object on Promise resolved.

Receive Messages

You can add multiple MessageListener using the addMessageListener() method, to receive incoming message wherever you need.

var listenerID = "UNIQUE_LISTENER_ID";

CometChat.addMessageListener(
  listenerID, 
  new CometChat.MessageListener({
    onTextMessageReceived: message => {
      console.log("Message received successfully:", message);
      // Handle text message
    }
  })
 );

Parameter

Description

listenerID

An ID that uniquely identifies that listener. We recommend using the activity or fragment name


Did this page help you?