Enhancing Your Established Angular Website with Firebase Cloud Messaging Push Notifications

Push Notification:

Anmol Choudhary
6 min readApr 9, 2024

Push notifications are short messages that pop up on users’ devices, delivering timely information even when they’re not actively using an app or website. They serve as direct communication channels between businesses and consumers. For instance, a retail app might send a push notification alerting users to a flash sale, enticing them to visit the app and make a purchase. These notifications are invaluable in marketing as they can grab users’ attention instantly, drive engagement, and prompt action, thereby increasing customer retention and boosting sales through targeted and personalized messaging strategies.

Firebase Cloud Messaging:

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably send messages at no cost. Using FCM, you can notify a client app that new email or other data is available to sync. You can send notification messages to drive user re-engagement and retention.

Steps to setup:

1. Go to firebase: https://firebase.google.com/

2. Sign Up or Login

3. Go to console (Present at top right corner)

4. Click add project and create new project with desire name

5. From project overview page create a new app e.g. web app

For web click here

6. Type desired app name, click Register app and complete this process with default suggestion

7. You will have got this type of dashboard opened:

Firebase dashboard for messaging configuration

8. And at bottom of you page you have got SDK setup and configuration section

Configurations keys

9. On Cloud messaging tab you will get the cloud messaging section from where you will get “Sender ID” and “Web push certificates” Generate key for web push certificate and you will get your unique key.

Cloud messaging option on dashboard
Web Push Key to generate

10. Keep this sender ID and generated key for use in further process.

11. Now go to your angular project

12. At root level run

npm install firebase

13. Create a new file manifest.json in src directory where index.html file exists. Put the sender ID that is copied from Cloud Messaging tab as below.

{
“gcm_sender_id” : “Sender ID”
}

14. Now link manifest.json in your index,html file like below :

<head>
<link rel = “manifest” href = “./manifest.json”>
</head>

15. To detect new messages from firebase, even if app is closed, our app needs a service worker. Create a new file firebase-messaging-sw.js in src directory where index.html file exist. Paste the below code in it. Update the firebase version here with the version you have installed. Can find the version in angular.json file to re-check.

Put the config data here that has been collected from General tab on Project Settings page. Check package.json file to see firebase version installed for the project and import that. While writing this the latest version was 10.10.0

importScripts("https://www.gstatic.com/firebasejs/10.10.0/firebase-app-compat.js");
importScripts("https://www.gstatic.com/firebasejs/10.10.0/firebase-messaging-compat.js");
firebase.initializeApp({
apiKey: " config data from general tab",
authDomain: " config data from general tab",
projectId: " config data from general tab",
storageBucket: " config data from general tab",
messagingSenderId: " config data from general tab",
appId: " config data from general tab",
measurementId: " config data from general tab "
});
const messaging = firebase.messaging();

16. Now we need to add these created file in angular.json file

"assets": [
"src/favicon.ico",
"src/assets",
"src/firebase-messaging-sw.js", // add new
"src/manifest.json" // add new
]

17. Now Update Environment files. Add new object name firebase, put the data we got from General tab on Project Settings page. Add a additional field vapidKey which we got by clicking Generate key pair on Cloud Messaging tab.

export const environment = {
production: false,
firebase: {
apiKey: "config data from general tab",
authDomain: "config data from general tab",
databaseURL: "config data from general tab",
projectId: "config data from general tab",
storageBucket: "config data from general tab",
messagingSenderId: "config data from general tab",
appId: "config data from general tab",
measurementId: "config data from general tab",
vapidKey: "generated key pair on Cloud Messaging tab"
},
};

18. Update app.module.ts file. Add these lines on the list of the import lines and make sure no error got introduced.

import { environment } from 'src/environments/environment';
import { initializeApp } from "firebase/app";
initializeApp(environment.firebase);

19. Now update app.component.ts file :
Paste this line to import:

import { getMessaging, getToken, onMessage } from "firebase/messaging";

Now ngOnInit call this functions

this.requestPermission();
this.listen();

This function are as below which you need to paste in app.componen.ts which is being called on ngOnInit.

requestPermission() {
const messaging = getMessaging();
getToken(messaging,
{ vapidKey: environment.firebase.vapidKey }).then(
(currentToken) => {
if (currentToken) {
console.log("Hurraaa!!! we got the token.....");
console.log(currentToken);
} else {
console.log('No registration token available. Request permission to generate one.');
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
});
}

listen() {
const messaging = getMessaging();
onMessage(messaging, (payload) => {
console.log('Message received. ', payload);
this.message = payload;
});
}

20. Update app.component.html file. Where you get you notification on website when webpage is open and if you are browsing something else then it will come in your notification Centre. This HTML can be placed wherever this notification is required.

<div *ngIf="message;">
<h1>{{ message.notification.title }}</h1>
<h2>{{ message.notification.body }}</h2>
</div>
<div *ngIf="!message;">
No Message In Notification
</div>

21. Your setup is done now it’s time to test the functionality.

22. Run your angular application on local “ng serve”

23. When you open your website on local host allow the notification

Notification enable in browser for page

24. Go to inspect of your browser where you will get the token / client ID

On inspect key on browser

25. Now go to Firebase dashboard, in engage dropdown click on Messaging and click on create your first campaign.

To check the working

26. Select Firebase Messaging Onboarding

Option to be selected to push notification

27. Fill out the required field and click on Send test message:

Fill the required message / notification text here

28. After this one pop-up will open put the registration token obtained from browser and click on Test and you will get the notification as required. If you are browsing webpage then notification will come on app.component.html part otherwise it will appear as below in notification center.

Notification in notification center on windows

--

--