How to implement PushNotification Extension in Web Chat Widget

Guide Overview

This guide explains how to implement the Push Notification Extension in the Web Chat Widget.

Steps to be followed-

1. Firebase Project Setup

Visit Firebase Console and login/signup using your Gmail ID.

  • Create a new Firebase Project

  • This is a simple 3 step process where:

      1. You give a name to your project
      2. Add Google Analytics to your project (Optional)
      3. Configure Google Analytics account (Optional)
    
  • Click on Create and you are ready to go.

  • Add Firebase to your Web App

      1. Click on the Web icon on the below screen and Register your app with a nickname.
      2. Once done, click on Continue to Console.
    

    image

  • Download the service account file

2. Extension Settings

Enable the extension

    1. Login to [CometChat](https://app.cometchat.com/login) and select your app.
    2. Go to the Extensions section and Enable the Push Notifications extension.
    3. Open the settings for the extension and add all the mentioned settings and hit save.

Save your Settings

On the Settings page you need to enter the following:

  1. Set extension version
  • If you are setting it for the first time, Select V2 to start using the enhanced version of the Push Notification extension. The enhanced version uses Token-based approach for sending Push Notifications and is simple to implement.
  • If you already have an app using V1 and want to migrate your app to use V2, then Select V1 & V2 option. This ensures that the users viewing the older version of your app also receive Push Notifications.
  • Eventually, when all your users are on the latest version of your app, you can change this option to V2, thus turning off V1 (Topic-based) Push Notifications completely.
  1. Select the platforms that you want to support
  • Select from Web, Android, Ionic, React Native, Flutter & iOS.
  1. Notification payload settings
  • You can control if the notification key should be in the Payload or not. Learn more about the FCM Messages here.
  1. Notification Triggers

  • Select the triggers for sending Push Notifications. These triggers can be classified into 3 main categories:
    1. Message Notifications
    2. Call Notifications
    3. Group Notifications
  • These are pretty self-explanatory and you can toggle them as per your requirement.

3. The Folder Setup

Create a file at firebase-messaging-sw.js at the same level as your index.html (where you have added the Chat Widget Code)

Now add the code snippet given below in the firebase-messaging-sw.js

importScripts("https://www.gstatic.com/firebasejs/7.21.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/7.21.0/firebase-messaging.js");

const firebaseConfig = {
// Get it from firebase console
        apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
        authDomain: "xxxxxxxxxxxxxxxxxxxxxxxx",
        projectId: "xxxxxxxxxxxxxxxxxxx",
        storageBucket: "xxxxxxxxxxxxxxxxxxxxx",
        messagingSenderId: "xxxxxxxxxxxxxxxxx",
        appId: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
        measurementId: "xxxxxxxxxxxxx"
  };

// Initialize firebase in the service worker.
firebase.initializeApp(firebaseConfig);

// Start Receiving Push Notifications when
// the browser tab is in the background or closed.
firebase.messaging();

Now you need to add some code in your index.html file to get the FCM token and register it to CometChat.

Add the below code to your index.html file

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Push Notification Chat Widget</title>
    <script
      defer
      src="https://widget-js.cometchat.io/v3/cometchatwidget.js"
    ></script>
  </head>
  <body>
    <button
      style="height: 30px; width: 100px; position: fixed; right: 20px"
      onclick="handleLogout()"
    >
      Logout
    </button>
    <div id="cometchat"></div>
    <!-- The core Firebase JS SDK is always required and must be listed first -->
    <script src="https://www.gstatic.com/firebasejs/7.21.0/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.21.0/firebase-messaging.js"></script>

    <script>
      async function handleLogout() {
     // to ensure that the `pushToken` registered with the user is deleted during logout
        const messaging = firebase.messaging();
        await messaging.deleteToken();
        await CometChatWidget.CometChat.callExtension(
          "push-notification",
          "DELETE",
          "v2/tokens",
          {
            all: false, // true when ALL the registered tokens for the logged-in user need to be deleted
          }
        )
          .then((response) => {
            // Success response
            console.log("All token deleted", response);
          })
          .catch((error) => {
            // Error occured
          });
        await CometChatWidget.logout().then(async () => {
          // to close the chat widget
          CometChatWidget.openOrCloseChat(false);
          console.log("Logout successful");
        });
      }
      window.addEventListener("DOMContentLoaded", (event) => {
        // Your web app's Firebase configuration
        // For Firebase JS SDK v7.20.0 and later, measurementId is optional
        const firebaseConfig = {
              apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
              authDomain: "xxxxxxxxxxxxxxxxxxxxxxxx",
              projectId: "xxxxxxxxxxxxxxxxxxx",
              storageBucket: "xxxxxxxxxxxxxxxxxxxxx",
              messagingSenderId: "xxxxxxxxxxxxxxxxx",
              appId: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
              measurementId: "xxxxxxxxxxxxx"
        };
        // Initialize firebase in the service worker.
        firebase.initializeApp(firebaseConfig);

        // Start Receiving Push Notifications when
        // the browser tab is in the background or closed.
        const messaging = firebase.messaging();

        CometChatWidget.init({
          appID: "xxxxxxxxxxxxxxxxx",
          appRegion: "xx",
          authKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        }).then(
          (response) => {
            console.log("Initialization completed successfully");
            //You can now call login function.
            CometChatWidget.CometChat.getLoggedinUser().then((user3) => {
              if (user3===null) {
                CometChatWidget.login({
                  uid: "login_user_id",
                }).then(
                  (response) => {
                    // Fetch the FCM Token
                    messaging.getToken().then((fcmToken) => {
                      console.log("2. Received FCM Token", fcmToken);
                      CometChatWidget.CometChat.registerTokenForPushNotification(
                        fcmToken
                      ).then(() => {
                        console.log("3. Registered FCM Token");
                        messaging.onMessage(function (payload) {
                          console.log("payload", payload);
                          const messageData = JSON.parse(payload.data.message);
                          const myIcon =
                            messageData?.data?.entities?.sender?.entity?.avatar;
                          const uid =
                            messageData?.data?.entities?.sender?.entity?.uid;
                          console.log(uid);
                          var notificationTitle = payload.data.title;
                          var notificationOptions = {
                            body:
                              payload.data.title + ": " + payload.data.alert,
                            icon: myIcon,
                          };
                          var notification = new Notification(
                            notificationTitle,
                            notificationOptions
                          );
                          notification.onclick = function (event) {
                 // You can modify it according to your use case
                            CometChatWidget.launch({
                              widgetID: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
                              target: "#cometchat",
                              roundedCorners: "true",
                              height: "600px",
                              width: "600px",
                              docked: "true",
                              alignment: "left",
                              roundedCorners: "true",
                              defaultID: "chat_user_uid", //default UID (user) or GUID (group) to show,
                              defaultType: "user", //user or group
                            });
                          };
                        });
                      });
                    });
                    CometChatWidget.launch({
                      widgetID: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
                      target: "#cometchat",
                      roundedCorners: "true",
                      height: "600px",
                      width: "600px",
                      docked: "true",
                      alignment: "left",
                      roundedCorners: "true",
                      defaultID: "chat_user_uid", //default UID (user) or GUID (group) to show,
                      defaultType: "user", //user or group
                    });
                  },
                  (error) => {
                    console.log("User login failed with error:", error);
                    //Check the reason for error and take appropriate action.
                  }
                );
              } else {
                CometChatWidget.launch({
                  widgetID: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
                  target: "#cometchat",
                  roundedCorners: "true",
                  height: "600px",
                  width: "600px",
                  docked: "true",
                  alignment: "left",
                  roundedCorners: "true",
                  defaultID: "chat_user_uid", //default UID (user) or GUID (group) to show,
                  defaultType: "user", //user or group
                });
              }
            });
          },
          (error) => {
            console.log("Initialization failed with error:", error);
            // Check the reason for the error and take appropriate action.
          }
        );
      });
    </script>
  </body>
</html>

This is how the Chat Widget will look like when a default user chat is open -

When your tab is in the background or the tab is closed you will receive notifications as shown below -