Guide Overview
This guide explains you how to implement Push Notifications Extension in WordPress.
1. Firebase Setup:
Follow the first two steps outlined in our Push Notification Extension Documentation: Web | Push Notifications | Notifications | Extensions | CometChat Docs
This guides you how to setup firebase and save the settings in CometChat Dashboard. Once, you are done with firebase setup and have uploaded the service account file follow the next steps from this GUIDE to implement it in WordPress.
Note: You need to either enable the notification key from the Dashboard or disable it and handle notifications manually using the payload received in onBackgroundMessage. Otherwise, you may receive duplicate notifications.
2. Open your Wordpress site directory in VS Code:
- Create a new file named
firebase-messaging-sw.js
in the public directory. - Copy and paste the below code into the file.
importScripts('https://www.gstatic.com/firebasejs/9.15.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.15.0/firebase-messaging-compat.js');
var firebaseConfig = {
apiKey: "YOUR_API_KEY_FROM_FIREBASE_CONSOLE",
authDomain: "YOUR_AUTH_DOMAIN_FROM_FIREBASE_CONSOLE",
projectId: "YOUR_PROJECT_ID_FROM_FIREBASE_CONSOLE",
storageBucket: "YOUR_STORAGE_BUCKET_FROM_FIREBASE_CONSOLE",
messagingSenderId: "YOUR_SENDER_ID_FROM_FIREBASE_CONSOLE",
appId: "YOUR_APP_ID_FROM_FIREBASE_CONSOLE",
measurementId: "YOUR_MEASUREMENT_ID_FROM_FIREBASE_CONSOLE"
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
self.addEventListener("notificationclick", async function (event) {
if (event?.notification) {
console.log("notification clicked",event)
let data = event.notification.data;
event.waitUntil(
self.clients
.matchAll({ type: "window", includeUncontrolled: true })
.then((clientList) => {
if (clientList.length > 0) {
clientList[0].postMessage({
message: data,
});
return (
clientList[0]
.focus()
.catch((error) => {
console.log(error);
return self.clients.openWindow(clientList[0].url); // Adjust this URL as necessary for your application
})
);
} else {
// Open a new client (tab) if there are no existing clients
self.clients.openWindow("/");
setTimeout(() => {
self.clients
.matchAll({ type: "window", includeUncontrolled: true })
.then((clientList) => {
if (clientList.length > 0) {
clientList[0].postMessage({
message: {...data,fromBackground: true},
});
}
return;
});
}, 1500);
}
})
);
}
});
// Background message handler in case you wish to customize the notification you can add the following code
// and handle the title, icon, body based on the payload received.
// Otherwise, you can skip this if the Notification Key is enabled the browser will handle the notifications.
messaging.onBackgroundMessage((payload) => {
const message = JSON.parse(payload.data.message);
if (
message.category === "call" &&
(message.data.action === "unanswered" ||
message.data.action === "busy" ||
message.data.action === "ongoing")
) {
return;
}
// You need to handle the notifications based on the payload as we have covered some scenarios here
let body = message.data.text;
let notificationTitle = "Notification";
let icon = "icon"
if(message.category ==="message"){
notificationTitle=message.data.entities.sender.entity.name
icon = message.data.entities.sender.entity.avatar
}
if (message.category === "call") {
switch (message.data.action) {
case "cancelled":
body = `Call cancelled`;
notificationTitle=message.data.entities.by.entity.name
icon = message.data.entities.by.entity.avatar
break;
case "initiated":
notificationTitle=message.data.entities.by.entity.name
body = `Incoming ${message.type} call`;
icon = message.data.entities.by.entity.avatar
break;
default:
break;
}
}
const notificationOptions = {
title: notificationTitle,
body: body,
icon: icon
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
Now, navigate to this route where this shortcode.php file lies.
app/public/wp-content/plugins/cometchat-pro/includes/shortcode.php
You need to update the code in this file so that the FCM token gets registered whenever a user login to the CometChat Widget.
// Firebase Config (check values)
// Define the following variable with your credentials in the getCometChatProShortCode() function
$firebaseConfig = json_encode(array(
"apiKey" => "YOUR_API_KEY_FROM_FIREBASE_CONSOLE",
"authDomain" => "YOUR_AUTH_DOMAIN_FROM_FIREBASE_CONSOLE",
"projectId" => "YOUR_PROJECT_ID_FROM_FIREBASE_CONSOLE",
"storageBucket" => "YOUR_STORAGE_BUCKET_FROM_FIREBASE_CONSOLE",
"messagingSenderId" => "YOUR_SENDER_ID_FROM_FIREBASE_CONSOLE",
"appId" => "YOUR_APP_ID_FROM_FIREBASE_CONSOLE",
"measurementId" => "YOUR_MEASUREMENT_ID_FROM_FIREBASE_CONSOLE"
));
// add the following code just below this $html = <<<EOD
<div id="cometchat"></div>
<script src="https://www.gstatic.com/firebasejs/9.15.0/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.15.0/firebase-messaging-compat.js"></script>
<script>
window.addEventListener('DOMContentLoaded', (event) => {
const firebaseConfig = $firebaseConfig;
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
CometChatWidget.init({
"appID": "{$app_id}",
"appRegion": "{$app_region}"
}).then(response => {
console.log("Initialization completed successfully");
CometChatWidget.CometChat.getLoggedinUser().then((user)=>{
if(user){
CometChatWidget.launch({
"widgetID": "{$widget_id}",
"target": "#cometchat",
"height": "{$widget_height}",
"width": "{$widget_width}",
"docked": "{$widget_docked}",
'alignment': '{$widget_docked_position}',
"defaultType": "user"
});
}else{
CometChatWidget.login({
"authToken": "{$authToken}"
}).then(response => {
// Register FCM Token for Push Notification
messaging.getToken().then((fcmToken) => {
console.log('FCM Token: ', fcmToken);
CometChatWidget.CometChat.registerTokenForPushNotification(fcmToken).then(() => {
console.log('FCM Token Registered');
CometChatWidget.launch({
"widgetID": "{$widget_id}",
"target": "#cometchat",
"height": "{$widget_height}",
"width": "{$widget_width}",
"docked": "{$widget_docked}",
'alignment': '{$widget_docked_position}',
"defaultType": "user"
});
});
});
}).catch(error => console.log("Login failed: ", error));
}
})
}).catch(error => console.log("Initialization failed: ", error));
});
</script>
Please note that your WordPress site must be secured with HTTPS for the browser to allow notification permissions.