Web
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+
- Opera 42+
Firebase Project Setup
Visit Firebase Console and login/signup using your Gmail ID.
Step 1: Create a new Firebase Project
This is a simple 3 step process where:
- You give a name to your project
- Add Google Analytics to your project (Optional)
- Configure Google Analytics account (Optional)
Click on Create and you are ready to go.
Step 2: Add Firebase to your Web App
- Click on the Web icon on the below screen and Register your app with a nickname.
- Once done, click on Continue to Console.
Step 3: Download the service account file
Extension settings
Step 1: Enable the extension
- Login to CometChat and select your app.
- Go to the Extensions section and Enable the Push Notifications extension.
- Open the settings for the extension and add all the mentioned settings and hit save.
Step 2: Save your settings
On the Settings page you need to enter the following:
- 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 useV2
, then SelectV1 & 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 offV1
(Topic-based) Push Notifications completely.
- Select the platforms that you want to support
- Select from Web, Android, Ionic, React Native, Flutter & iOS.
- Notification payload settings
- You can control if the notification key should be in the Payload or not. Learn more about the FCM Messages here.
- Push payload message options
-
The maximum payload size supported by FCM and APNs for push notifications is approximately 4 KB. Due to the inclusion of CometChat's message object, the payload size may exceed this limit, potentially leading to non-delivery of push notifications for certain messages. The options provided allow you to remove the sender's metadata, receiver's metadata, message metadata and trim the content of the text field.
-
The message metadata includes the outputs of the Thumbnail Generation, Image Moderation, and Smart Replies extensions. You may want to retain this metadata if you need to customize the notification displayed to the end user based on these outputs.
- 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
- Go to the Firebase Console and click on the Web app and open up the Settings page.
- Go to the "General" tab on the Settings page.
- Scroll down and copy the Firebase SDK snippet and paste in the <head> tag of your index.html file.
Step 3: Setup index.html file
- Include the latest CometChat library using CDN.
- Register the service worker file.
- Also, include the
PushNotification.js
. - The <body> has a simple form:
- Text input for UID.
- Login button.
- Logout button.
Once done, your index.html
file should look like this:
- HTML
<!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/chat-sdk-javascript/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
- Use
importScripts
to include thefirebase-app.js
andfirebase-messaging.js
files in the service worker. - Also paste in the
FIREBASE_CONFIG
object again in this file. - Initialize the Firebase object using the config.
- Call the messaging() on the Firebase object.
Once done, your firebase-messaging-sw.js
file should look like this:
- Javascript
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:
- Setup required to start using Firebase SDK.
- 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:
- Initialize CometChat.
- Login using CometChat user.
- Ask for the User's permission to show Push Notifications.
- If permission is granted, obtain the
FCM_TOKEN
. - Register the obtained
FCM_TOKEN
with the extension.
During logout:
- First delete the token using the firebase object.
- 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.
- Javascript
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
- You can now host the project folder using Nginx, Apache web server, or even VSCode Live server extension.
- Launch the web app in a browser and open the browser console to see the logs.
- Enter the UID of the user and click on login.
- When asked for permission to show notifications, click on Allow.
- Once you see logs saying that the FCM Token has been registered, either send the browser tab to the background or close it completely.
- 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
- Reopen the previous closed browser tab and click on logout.
- The
FCM_TOKEN
will be deleted on the extension's end on theCometChat.logout()
call. - As a good practice, the
FCM_TOKEN
should also be deleted using thefirebase.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
.
- Javascript
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.
}
);