JavaScript

Learn how to send push notifications for messages.

The Push Notification extension allows you to send push notifications to mobile apps and desktop browsers.

Push notifications will work in all desktop browsers which support Push API. These include Chrome 50+, Firefox 44+, Edge 17+ and Opera 42+.

Add Push Notification

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

Step 1: Add Firebase to your app

Create Firebase AppCreate Firebase App

Create Firebase 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.

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.

Select WebSelect Web

Select Web

Copy the snippet and add it to your application HTML.

Add Firebase to your web appAdd Firebase to your web app

Add Firebase to your web app

Step 3: Enable the extension from Dashboard

  1. Login to the CometChat Dashboard.
  2. On the Extensions page add the Push Notifications extension.
  3. Go to the Installed tab and open the Settings for this extension.
  4. Enter the Title (usually name of the app) and FCM Server key.
  5. You can also toggle the triggers for sending Push Notifications. The triggers can be classified into 3 main categories:
    a. Message Notifications
    b. Call Notifications
    c. Group Notifications

Step 4: 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 subscribe to topics instead of using the subscribe to a topic method provided by the plugin you are using, we recommend you use our APIs to subscribe to a topic.

You can subscribe to topic/s in two ways:
a. Subscribe to all topics(all the joined groups and one-to-one conversations)
b. Subscribe to one topic.

a. Subscribe to all topics
If you wish to subscribe to all the groups you have previously joined, you can use the below code snippet.

📘

Note

You will still have to subscribe to groups individually whenever you join any group using the joinGroup() method provided by the SDK.

Since there is no native method available by Javascript SDK,

❗️

Please make sure you are subscribing to topics in the success of CometChat.login().

var appID = "APP_ID";
var token = "GENERATED_FCM_TOKEN";
var userUID = "UID_OF_LOGGED_IN_USER";
var appToken;
CometChat.getJoinedGroups().then(groups => {
  CometChat.getAppSettings().then(settings => {
    settings.extensions.forEach(ext => {
      if (ext.id == "push-notification") {
        appToken = ext.appToken;
      }
    });
    var url =
      "https://push-notification-us.cometchat.io/v1/subscribetomany?appToken=" +
      appToken;
    fetch(url, {
      method: "POST",
      headers: new Headers({
        "Content-Type": "application/json"
      }),
      body: JSON.stringify({
        appId: appID,
        fcmToken: token,
        uid: userUID,
        groups: groups,
        platform: "javascript"
      })
    })
      .then(response => {
        if (response.status < 200 || response.status >= 400) {
          console.log("Error subscribing to topics: " +response.status +" - " +response.text());
        } else {
          console.log("Subscribed to all topics");
        }
      })
      .catch(error => {
        console.error(error);
      });
  });
});

b. Subscribe to one topic:

To receive push notifications, the logged-in user must subscribe to two types of topics:

  1. Their own topic - All the messages for one-on-one conversations that are sent to the logged-in user are received using this topic. The topic you must subscribe to is AppID_user_UID where AppID is your CometChat App ID and UID is the logged-in user's ID.

  2. Topics for all the groups the logged in user is a part of - All the messages for a group conversation are received using these topics. For every group joined, the logged-in user will have to subscribe to the topic for that group. For every group, you must subscribe to AppID_group_GUID where AppID is your CometChat App ID and GUID is the group's ID.

🚧

Please note:

UID in case of users and GUID in case of groups are converted to lowercase by the Chat API. These are then used for generating the topic.

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

var token = "generated_FCM_token";
CometChat.getAppSettings().then(settings => {
    var appToken;
    settings.extensions.forEach(ext => {
        if (ext.id == "push-notification"){
            appToken = ext.appToken;
        }
    });
  var userType = "user";
  var UID = "UID";
  var appId = "APP_ID";
  var region = "REGION_OF_APP";
  var topic = appId + "_" + userType + "_" + UID;
  var url =
    "https://push-notification-"+ region +".cometchat.io/v1/subscribe?appToken=" +
    appToken +
    "";
  fetch(url, {
    method: "POST",
    headers: new Headers({
      "Content-Type": "application/json"
    }),
    body: JSON.stringify({ appId: appId, fcmToken: token, topic: topic })
  })
    .then(response => {
      if (response.status < 200 || response.status >= 400) {
        console.log(
          "Error subscribing to topic: " +
            response.status +
            " - " +
            response.text()
        );
      }
      console.log('Subscribed to "' + topic + '"');
    })
    .catch(error => {
      console.error(error);
    });
});
var token = "generated_FCM_token";
CometChat.getAppSettings().then(settings => {
  var appToken;
  settings.extensions.forEach(ext => {
      if (ext.id == "push-notification){
          appToken = ext.appToken;
      }
  });
  var userType = "group";
  var GUID = "GUID";
  var appId = "APP_ID";
  var region = "REGION_OF_APP";
  var topic = appId + "_" + userType + "_" + GUID;
  var url =
    "https://push-notification-"+ region +".cometchat.io/v1/subscribe?appToken=" +
    appToken +
    "";
  fetch(url, {
    method: "POST",
    headers: new Headers({
      "Content-Type": "application/json"
    }),
    body: JSON.stringify({ appId: appId, fcmToken: token, topic: topic })
  })
    .then(response => {
      if (response.status < 200 || response.status >= 400) {
        console.log(
          "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
});
  1. Unsubscribe From Topic

You can unsubscribe from topic/s in two ways:
a. Unsubscribe from all topics(all the joined groups and one-to-one conversations)
b. Unsubscribe from one topic.

a. Unsubscribe from all topics:
If you subscribe to all topics you can unsubscribe from all the topics you have subscribed to in your logout method using the below code snippet.

var appID =  "APP_ID";
var token = "GENERATED_FCM_TOKEN";
var appToken;
CometChat.getAppSettings().then(settings => {
  settings.extensions.forEach(ext => {
    if (ext.id == "push-notification") {
      appToken = ext.appToken;
    }
  });
  var url = "https://push-notification-us.cometchat.io/v1/unsubscribealltopic?appToken=" + appToken;
  fetch(
    url, 
    {
      method: "DELETE",
      headers: new Headers({
        "Content-Type": "application/json"
      }),
      body: JSON.stringify({ appId: appID, fcmToken: token })
    }
  )
  .then(response => {
    if (response.status < 200 || response.status >= 400) {
      console.log("Error unsubscribing from topics: " +response.status +" - " +response.text());
    } else {
      console.log("Unsubscribed from all topics"); 
    }
  })
  .catch(error => {
    console.error(error);
  });
});

b. Unsubscribe from one topic:
If you subscribe to a single topic you can unsubscribe from the single topic in the following way:

var token = "generated_FCM_token";
CometChat.getAppSettings().then(settings => {
    var appToken;
    settings.extensions.forEach(ext => {
        if (ext.id == "push-notification") {
            appToken = ext.appToken;
        }
    });
    var userType = "user";
    var UID = "UID";
    var appId = "APP_ID";
    var region = "REGION_OF_APP";
    var topic = appId + "_" + userType + "_" + UID;
    var url =
    "https://push-notification-"+ region +".cometchat.io/v1/unsubscribe?appToken=" +
    appToken;
    fetch(url, 
        {
            method: "DELETE",
            headers: new Headers({
                "Content-Type": "application/json"
            }),
            body: JSON.stringify({ appId: appId, fcmToken: token, topic: topic })
        }
    )
        .then(response => {
            if (response.status < 200 || response.status >= 400) {
            console.log(
                "Error subscribing to topic: " +
                response.status +
                " - " +
                response.text()
            );
            } else {
            console.log('Unsubscribed from "' + topic + '"');
            }
        })
        .catch(error => {
            console.error(error);
        });
    });
var token = "generated_FCM_token";
CometChat.getAppSettings().then(settings => {
    var appToken;
    settings.extensions.forEach(ext => {
        if (ext.id == "push-notification") {
            appToken = ext.appToken;
        }
    });
    var userType = "group";
    var GUID = "GUID";
    var appId = "APP_ID";
    var region = "REGION_OF_APP";
    var topic = appId + "_" + userType + "_" + GUID;
    var url =
    "https://push-notification-"+ region +".cometchat.io/v1/unsubscribe?appToken=" +
    appToken;
    fetch(url, 
        {
            method: "DELETE",
            headers: new Headers({
                "Content-Type": "application/json"
            }),
            body: JSON.stringify({ appId: appId, fcmToken: token, topic: topic })
        }
    )
        .then(response => {
            if (response.status < 200 || response.status >= 400) {
            console.log(
                "Error subscribing to topic: " +
                response.status +
                " - " +
                response.text()
            );
            } else {
            console.log('Unsubscribed from "' + topic + '"');
            }
        })
        .catch(error => {
            console.error(error);
        });
    });

Step 4: Add FCM Server Key

Login to CometChatPro Dashboard and move to Extension tab as follows:

FCMFCM

FCM

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

FCM SERVER KEYFCM SERVER KEY

FCM SERVER KEY

Always get your Firebase Cloud Messaging Server Key from firebase console as shown below:

Handle Custom Messages

To receive notification of CustomMessage, you need to set metadata while sending the CustomMessage.

var receiverID = "UID";
var customData = {
  latitude: "50.6192171633316",
  longitude: "-72.68182268750002"
};

var customType = "location";
var receiverType = CometChat.RECEIVER_TYPE.USER;
var metadata = {
  pushNotification: "Your Notification Message",
};

var customMessage = new CometChat.CustomMessage(
  receiverID,
  receiverType,
  customType,
  customData
);

customMessage.setMetadata(metadata);

CometChat.sendCustomMessage(customMessage).then(
  message => {
    // Message sent successfully.
    console.log("custom message sent successfully", message);
  },
  error => {
    console.log("custom message sending failed with error", error);
    // Handle exception.
  }
);

Converting push notification payload to message object

CometChat pro SDK provides a method CometChat.CometChatHelper.processMessage() to convert the message JSON to the corresponding object of TextMessage, MediaMessage,CustomMessage, Action or Call.

This code needs to be added to the onMessageReceived() method of the FirebaseMessagingService class.

var processedMessage = CometChat.CometChatHelper.processMessage(JSON_MESSAGE);

Messages

Simple text message

SenderName: text message

Attachment(s) with text

SenderName: text message

An attachment without text

SenderName: has sent you a/an Type

Attachments without text

SenderName: has sent you Types

📘

Type of Attachment can be of the following the type
1.CometChatConstants.MESSAGE_TYPE_IMAGE
2.CometChatConstants.MESSAGE_TYPE_VIDEO
3.CometChatConstants.MESSAGE_TYPE_AUDIO
4.CometChatConstants.MESSAGE_TYPE_FILE

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"
  }
}

Did this page help you?