JavaScript

Learn how to set up CometChat Pro Enhanced Push Notifications in JavaScript.

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:

  1. Chrome 50+
  2. Firefox 44+
  3. Edge 17+
  4. Opera 42+

I want to checkout the Sample app.

Click on the link below to check out our React Push Notifications Sample app.

Follow the steps mentioned in the README.md file.

View Sample App on GitHub

Firebase Project Setup

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

Step 1: Create a new Firebase Project

New Firebase ProjectNew Firebase Project

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.

Step 2: 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.
Select WebSelect Web

Select Web

Step 3: Get the Server Key

  1. Once you are back to Console, you will see the Web app added to the Firebase Project.
  2. Click on the app and open up the Settings page.
  3. Go to the "Cloud Messaging" section and get the Server Key. This will be required in the next step.

Extension Setup

Step 1: Enable the extension

  1. Login to the CometChat Dashboard.
  2. Select an existing app or create a new one.
  3. Go to the "Extensions" section and Enable the Push Notifications extension.
  4. Go to the "Installed" tab in the same section and open the settings for this extension.

Step 2: Save your Settings

On the Settings page you need to enter the following:

  1. Push Notifications Title
  • This is usually the name of your app.
  1. FCM Server key
  • Paste the Server key obtained in Step 3 of The Firebase Project Setup.
  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. Notification Triggers
  • Select the triggers for sending Push Notifications. These triggers can be classified into 3 main categories:
    -- Message Notifications
    -- Call Notifications
    -- Group Notifications
  • These are pretty self-explanatory and you can toggle them as per your requirement.

Web App Setup

Step 1: Folder and files setup

Create a folder with the following three files:

Files

Description

index.html

Displays a simple User Login Form.

PushNotification.js

File with the logic to initialize CometChat and Firebase.

firebase-messaging-sw.js

Service worker shows Push Notifications when the tab is either in the background or closed.

Step 2: Add the Firebase Config to the HTML File

  1. Go to the Firebase Console and click on the Web app and open up the Settings page.
  2. Go to the "General" tab on the Settings page.
  3. Scroll down and copy the Firebase SDK snippet and paste in the <head> tag of your index.html file.
Add Firebase to your web appAdd Firebase to your web app

Add Firebase to your web app

Step 3: Setup index.html file

  1. Include the latest CometChat library using CDN.
  2. Register the service worker file.
  3. Also, include the PushNotification.js.
  4. The <body> has a simple form:
    a. Text input for UID.
    b. Login button.
    c. Logout button.

Once done, your index.html file should look like this:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Push Notification Sample</title>
  
  <!-- 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>
  
  <!-- Firebase config and initialization -->
  <script>
    const FIREBASE_CONFIG = {
      // Your Config
    };
    // Initialize Firebase only once
    firebase.initializeApp(FIREBASE_CONFIG);
  </script>
  
  <!-- Register the service worker. -->
  <script>
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', () => {
        navigator.serviceWorker.register('/firebase-messaging-sw.js');
      });
    }
  </script>
  
  <!-- CometChat import -->
  <script type="text/javascript" src="https://unpkg.com/@cometchat-pro/[email protected]/CometChat.js"></script>
  
  <!-- Our app file with the CometChat and Firebase logic -->
  <script src="PushNotification.js" defer></script>
</head>

<body>
  Enhanced Push Notifications!</br>
  <input type="text" id='uid'></input></br>
  <button id='loginButton'>Login</button>
  <button id='logoutButton'>Logout</button>
</body>

</html>

Step 4: Setup the service worker file

  1. Use importScripts to include the firebase-app.js and firebase-messaging.js files in the service worker.
  2. Also paste in the FIREBASE_CONFIG object again in this file.
  3. Initialize the Firebase object using the config.
  4. Call the messaging() on the Firebase object.

Once done, your firebase-messaging-sw.js file should look like this:

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 FIREBASE_CONFIG = {
  // Your Config
};

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

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

Step 5: Setup the PushNotification.js file

Now our simple web app has the following:

  1. Setup required to start using Firebase SDK.
  2. Service worker registration when the index.html loads for the first time.

Next, we can focus on the flow to setup CometChat login process along with the steps required to setup Push Notifications using Firebase Cloud Messaging (or FCM).

During login:

  1. Initialize CometChat.
  2. Login using CometChat user.
  3. Ask for the User's permission to show Push Notifications.
  4. If permission is granted, obtain the FCM_TOKEN.
  5. Register the obtained FCM_TOKEN with the extension.

During logout:

  1. First delete the token using the firebase object.
  2. Logout CometChat user.

The above steps have been implemented in the login and logout functions in the PushNotifications.js file.
You can copy paste the below code. Do not forget to replace the APP_ID, REGION, AUTH_KEY of your app in the code below.

const APP_ID = "APP_ID";
const REGION = "REGION";
const AUTH_KEY = "AUTH_KEY";

const APP_SETTING = new CometChat.AppSettingsBuilder().subscribePresenceForAllUsers().setRegion(REGION).build();
let FCM_TOKEN = '';

let loginButton;
let logoutButton;

const login = async () => {
  const UID = document.getElementById('uid').value;
  if (!UID) {
    document.getElementById('uid').focus();
    return;
  }
  loginButton.disabled = true;
  console.log('Initiating login... ');
  try {
    // CC init
    await CometChat.init(APP_ID, APP_SETTING);

    // User login
    const loginResponse = await CometChat.login(UID, AUTH_KEY);
    console.log('1. User login complete', loginResponse);

    CometChat.getLoggedinUser().then(user => console.log(user.name));
    // Change the page title
    document.title = UID + ' logged in';

    // Fetch the FCM Token
    const messaging = firebase.messaging();
    FCM_TOKEN = await messaging.getToken();
    console.log('2. Received FCM Token', FCM_TOKEN);

    // Register the FCM Token
    await CometChat.registerTokenForPushNotification(FCM_TOKEN);
    console.log('3. Registered FCM Token');

    logoutButton.disabled = false;
  } catch (error) {
    console.error(error);
  }
}

const logout = async () => {
  console.log('Initiating logout...');
  loginButton.disabled = true;
  logoutButton.disabled = true;
  try {
    // Delete the token
    const messaging = firebase.messaging();
    await messaging.deleteToken();
    
    // Logout the user
    await CometChat.logout();
    console.log('5. Logged out');

    // Refresh the page.
    init();
    window.location.reload();
  } catch (error) {
    console.error(error);
  }
}

const init = () => {
  // Basic initialization
  loginButton = document.getElementById('loginButton');
  logoutButton = document.getElementById('logoutButton');

  loginButton.addEventListener('click', login);
  logoutButton.addEventListener('click', logout);

  logoutButton.disabled = true;
}

window.onload = () => {
  // Call the initialization function on load.
  setTimeout(init, 300);
};

Start receiving Push Notifications

  1. You can now host the project folder using Nginx, Apache web server, or even Live server extension offered by Visual Studio Code.
  2. Launch the web app in a browser and open the browser console to see the logs.
  3. Enter the UID of the user and click on login.
  4. When asked for permission to show notifications, click on Allow.
  5. Once you see logs saying that the FCM Token has been registered, either send the browser tab to the background or close it completely.
  6. Send a message to this logged-in user from another device (using our Sample Apps) and you should be able to see the Push Notifications.

Stop receiving Push Notifications

  1. Reopen the previous closed browser tab and click on logout.
  2. The FCM_TOKEN will be deleted on the extension's end on the CometChat.logout() call.
  3. As a good practice, the FCM_TOKEN should also be deleted using the firebase.messaging().deleteToken().

Custom body for notifications

To send custom body for notifications or 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.
  }
);

Advanced

Check out our documentation on how to add Mute functionality to your apps.


Did this page help you?