CometChat Pro Documentation

You'll find comprehensive guides and documentation to help you start working with CometChat as quickly as possible. Let's jump right in!

Javascript

This is a guide on how to enable push notification in your Javascript App powered by CometChat Pro SDK. You can explore through the ReactJs Demo on Github.

Add Push Notification

  • To configure Firebase Push Notifications for your apps create a Firebase project at
    Firebase Console

Step 1: Create a Firebase Project

Before you can add Firebase to your JavaScript app, you need to create a Firebase project to connect to your app.

  • If you have previously not created a firebase project for your app Click Add project. If you already have created a project for your app in which you wish to integrate CometChat, select the same project and download the config file:
Create Firebase project

Create Firebase project

Step 2 : Obtain your Firebase config object

Each of the configuration steps in this guide require that you initialize with a Firebase configuration object.

var firebaseConfig = {
  apiKey: "api-key",
  authDomain: "project-id.firebaseapp.com",
  databaseURL: "https://project-id.firebaseio.com",
  projectId: "project-id",
  storageBucket: "project-id.appspot.com",
  messagingSenderId: "sender-id",
};

To get a config snippet for a web app:

  • Sign into Firebase and open your project.
  • On the Overview page, click Add app.
  • Select Add Firebase to your web app.
  • Copy the snippet and add it to your application HTML.
Add Firebase to your web app

Add Firebase to your web app

Step 3 : Firebase Cloud Messaging client app on Web

  1. Installing the Firebase Javascript SDK:

Install the firebase SDK and save it to your package.json file by running:

npm i firebase
yarn install --save firebase
bower install firebase --save
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase.js"></script>

Firebase Method Reference

Learn about the available methods in the Firebase JavaScript reference documentation.

Next, create a PushNotification.js file, then initialize firebase app using initFirebase() with firebase config copied before from Firebase console.

  1. Initialize Firebase app
import firebase from "firebase";
import CCManager from "./../cometchat/ccManager";


export const initFirebase=()=>{

    var config = {
      apiKey: "AIzaSyBkasdasdasdybyI-ZkFCxNpJLAtYyqeERw5I60yTNs",
      authDomain: "testAPP.firebaseapp.com",
      databaseURL: "https://testAPP.firebaseio.com",
      projectId: "testAPP-229414",
      storageBucket: "testAPP.appspot.com",
      messagingSenderId: "app_sender_id"
    };

    firebase.initializeApp(config);
  }

Attention

Please invoke initFirebase() ONLY ONCE in whole app lifecycle.

  1. Request Permission for Web Push

The method messaging.requestPermission() displays a consent dialog to let users grant your app permission to receive notifications in the browser. If permission is denied, FCM registration token requests result in an error.

var messaging = firebase.messaging();

messaging.requestPermission()
    .then(() => {
        console.log("Have Permission");
        return messaging.getToken();
    })
    .then(token => {

        console.log("FCM Token:", token);
        //Do something with TOken like subscribe to topics

    })
    .catch(error => {
        if (error.code === "messaging/permission-blocked") {
            console.log("Please Unblock Notification Request Manually");
        } else {
            console.log("Error Occurred", error);
        }
    });
  1. Subscribe to Topic

To receive notification from different entities, such as users and groups. The user has to subscribe to particular topics as We are using topic-based push notification.

  • All client app will be subscribing to APPID_receiverType_ReceiverId topic.

Assume, APPID is 6a124abc, and

Receiver Type
Reciever Id
Example

User

6a124abc_user_SUPERHERO1

6a124abc_user_SUPERHERO1

Group

6a124abc_group_SUPERGROUP

6a124abc_group_SUPERGROUP

  • FCM topic messaging allows your app server to send a message to multiple devices that have opted in to a particular topic. Based on the publish/subscribe model, topic messaging supports unlimited subscriptions per app.

Since there is no native method available by Javascript SDK,

var token = "generated_FCM_token";

var userType = "user";
var UID = "SUPERHERO1";
var appId="6a124abc";

var topic = appId+"_"+userType+"_"UID;

var url ='https://ext-push-notifications.cometchat.com/fcmtokens/'+token+'/topics/'+topic;

fetch(url, {
      method: 'POST',
      headers: new Headers({
        'Content-Type':'application/json'
      }),
      body:JSON.stringify({"appId":appId})
}).then(response => {
  if (response.status < 200 || response.status >= 400) {
  	throw 'Error subscribing to topic: '+response.status +' - ' +response.text();
  }
  
  console.log('Subscribed to "'+topic+'"');
}).catch(error => {
      console.error(error);
});
var token = "generated_FCM_token";

var userType = "group";
var UID = "SUPERGROUP";
var appId="6a124abc";

var topic = appId+"_"+userType+"_"UID;

var url ='https://ext-push-notifications.cometchat.com/fcmtokens/'+token+'/topics/'+topic;

fetch(url, {
      method: 'POST',
      headers: new Headers({
        'Content-Type':'application/json'
      }),
      body:JSON.stringify({"appId":appId})
}).then(response => {
  if (response.status < 200 || response.status >= 400) {
  	throw 'Error subscribing to topic: '+response.status +' - ' +response.text();
  }
  
  console.log('Subscribed to "'+topic+'"');
}).catch(error => {
      console.error(error);
});
  1. Receive Message

    • When application is in Foreground

You can capture broadcast push notification using firebase.messaging().onMessage() method. You can create custom web notification display using Notification API.

firebase.messaging().onMessage(function(payload) {
      
  	// Customize notification here
    	var notificationTitle = 'Notification title';
      var notificationOptions = {
        	body: payload.data.alert,
        	icon: ''
      };
  
  
    var notification = new Notification(notificationTitle, notificationOptions);

      notification.onclick= function(event){
        	notification.close();
        	//handle click event onClick on Web Push Notification
      };  
 });  
  • When app is in background (Add Service Worker)

In order to receive the onMessage event, your app must define the Firebase messaging service worker in firebase-messaging-sw.js. Alternatively, you can specify an existing service worker with useServiceWorker.

Add firebase-messaging-sw.js to your index.html level

importScripts("https://www.gstatic.com/firebasejs/5.9.4/firebase.js");

var config = {

    messagingSenderId: "app_sender_id"
  };

firebase.initializeApp(config);

const messaging = firebase.messaging();
 
 //background
messaging.setBackgroundMessageHandler(function(payload) {
	console.log(' Received background message ', payload);
  
  // Customize notification here
  var notificationTitle ="notificationTitle";
  var notificationOptions = {
        body: payload.data.alert,
        icon: ''
  };
    
return self.registration.showNotification(notificationTitle,notificationOptions);
});

// [END background_handler]
self.addEventListener('notificationclick', function(event) {
  event.notification.close();
  //handle click event onClick on Web Push Notification
});

Step 4: Add FCM Server Key

  • Login to CometChatPro Dashboard and move to Extension tab as follows:
  • In extension, section select Push Notification Service and click add Extension, this will add push notification service to your app
  • Move to Your extension tab, Enable push notification service
  • then ACTION > SETTINGS > ADD FCM SERVER KEY > SAVE
  • Always get your Firebase Cloud Messaging Server Key from firebase console as shown below:

Push Notification Payload Sample for Text Message and Attachment/Media Message

{  
   "alert":"Spiderman: Text Message",
   "sound":"default",
   "title":"CometChat Pro",
   "message":{  
      "receiver":"superhero4",
      "data":{  
         "entities":{  
            "receiver":{  
               "entityType":"user",
               "entity":{  
                  "uid":"superhero4",
                  "role":"default",
                  "name":"Wolverine", 
                  "avatar":"http://data.cometchat.com/assets/images/avatars/wolverine.png",
                  "status":"offline"
               }
            },
            "sender":{  
               "entityType":"user",
               "entity":{  
                  "uid":"superhero3",
                  "role":"default",
                  "name":"Spiderman",
                  "avatar":"https://data.cometchat.com/assets/images/avatars/spiderman.png",
                  "status":"offline"
               }
            }
         },
         "text":"Text Message"
      },
      "sender":"superhero3",
      "receiverType":"user",
      "id":"142",
      "sentAt":1555668711,
      "category":"message",
      "type":"text"
   }
}
{
   "alert":"Spiderman: has sent an image",
   "sound":"default",
   "title":"CometChat Pro",
   "message":{
      "receiver":"superhero4",
      "data":{
         "attachments":[
            {
               "extension":"png",
               "size":14327,
               "name":"extension_leftpanel.png",
               "mimeType":"image/png",
               "url":"https://s3-eu-west-1.amazonaws.com/data.cometchat.com/1255466c41bd7f/media/1555671238_956450103_extension_leftpanel.png"
            }
         ],
         "entities":{
            "receiver":{
               "entityType":"user",
               "entity":{
                  "uid":"superhero4",
                  "role":"default",
                  "name":"Wolverine",
                  "avatar":"https://data.cometchat.com/assets/images/avatars/wolverine.png",
                  "status":"offline"
               }
            },
            "sender":{
               "entityType":"user",
               "entity":{
                  "uid":"superhero3",
                  "role":"default",
                  "name":"Spiderman",
                  "avatar":"https://data.cometchat.com/assets/images/avatars/spiderman.png",
                  "status":"offline"
               }
            }
         },
         "url":"https://s3-eu-west-1.amazonaws.com/data.cometchat.com/1255466c41bd7f/media/1555671238_956450103_extension_leftpanel.png"
      },
      "sender":"superhero3",
      "receiverType":"user",
      "id":"145",
      "sentAt":1555671238,
      "category":"message",
      "type":"image"
   }
}
  1. Add the Push Notification extension dependency:
npm i @cometchat-pro/pro-ext-pn@1.0.0

Once the dependency is added, you need to use the getMessageFromJson() which will take the JSON received in The push notification as input, and return the corresponding TextMessage, MediaMessage,CustomMessage or Call object in return. Once the message object is received, you can use the entity as per your requirements.

PNExtension.getMessageFromJson(JSON_MESSAGE).then(
  baseMessage=>{  
		if(baseMessage instanceOf CometChat.TextMessage){
      // Handle Text message received push notification
    }else if(baseMessage instanceof CometChat.MediaMessage){
      // Handle media message received push notification
    }else if(baseMessage instanceof CometChat.CustomMessage){
      // Handle custom message received push notification
    }else if (baseMessage instanceof CometChat.Call){
      // Handle call message
    }
},error=>{
		console.log("JSON parsing failed with error:",error);
});

Javascript


This is a guide on how to enable push notification in your Javascript App powered by CometChat Pro SDK. You can explore through the ReactJs Demo on Github.

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.