Firebase Web Push Notification
By: Ayush Chaurasia
Tags: Service Worker, Firebase Cloud Functions, Firebasecloudmessaging, JavaScript, Firebase

Let’s write the code.

Client HTML and js page.

index.html

copy the firebase SDK code in the bottom of the body of the index.html

<!DOCTYPE html> <html>

<head>

<meta charset=utf-8 />

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>FCM cloud messaging</title>

</head>

<body>

<!-- your regular html code -->



<!-- insert here the firebase sdk code-->

<script>

// All the other code realted to firebase will be below this </script> </body>

The Firebase SDK code is used for the initialization of the firebase all the other code should go below that.

Now let’s write a code to receive the message in the foreground.

index.html

//Put this inside the script

messaging.onMessage((payload) => { console.log('Message received. ', payload); });

Here the payload will contain the received notification information.

Sending a message to the firebase browser client

For firebase to be able to send message to the client it needs to uniquely identify it, which it does via token, tokens are generated on the client-side and can be stored on our server-side. Let’s see how to get the client token.

index.html

//Put this inside the script

//Below above snippet code. messaging.getToken({vapidKey: 'MY_VAPID_KEY'}).then((currentToken) => { if (currentToken) { console.log("token is ",currentToken);

//Send this token to your server and store it. } else {

console.log('No registration token available. Request permission to generate one.'); } }).catch((err) => { console.log('An error occurred while retrieving token. ', err); });

In the above snippet use your vapid key.

You can start firebase server and check the printed token in your browser’s console.

Now let’s do the setup to receive notification even our app is not in foreground or browser itself is closed(Background notification).

create a new file firebase-messaging-sw.js and add the following content.

importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js'); //Remeber this part we have used above in our index.html

var firebaseConfig = {

apiKey: "myApiKey",

authDomain: "browser-notif-test.firebaseapp.com",

projectId: "browser-notif-test",

storageBucket: "browser-notif-test.appspot.com",

messagingSenderId: "myMessaginSenderId",

appId: "myAppId",

measurementId: "myMeasurementId"// this is for analytics purpose

}; const messaging = firebase.messaging(); messaging.onBackgroundMessage(function(payload) { console.log('[firebase-messaging-sw.js] Received background message ', payload); // Customize notification here

const notificationTitle = 'Title';

const notificationOptions = {

body: payload,

icon: '/firebase-logo.png' }; self.registration.showNotification(notificationTitle,

notificationOptions); });```

The above file is supposed to run in the background so we will register it with the service worker (A mechanism to run the process in the background, click on the link to get a better understanding of service worker.)

Let’s register with the service worker

async function registerWorker() { console.log('Registering service worker'); const registration = await navigator.serviceWorker.

register('/firebase-messaging-sw.js', {scope: '/'});

console.log('Registered service worker'); const subscription = await registration.pushManager. subscribe({ userVisibleOnly: true, applicationServerKey: 'my_VAPID' }); } if ('serviceWorker' in navigator) {

console.log('Registering service worker');

regiserWorker().catch(error => console.error(error)); }

Now we start the firebase server with firebase serve -p 8081 or if you have express server setup then do node app.js.

You can go to localhost:8081 to see your client-side page, copy the token id printed in the console. You will have to allow the show notification popup of the browser, otherwise, you will not get the token.

Let’s do a curl request to test the notification.

curl -X POST -H "Authorization: key=YOUR_SERVER_KEY" -H "Content-Type: application/json" -d '{ "notification": { "title": "First notif",

"body": "Hello world",

"icon": "firebase-logo.png",

"click_action": "http://localhost:8081" }, "to": "CLIENT_TOKEN" }' "https://fcm.googleapis.com/fcm/send"

Press enter and you should see your first notification.

Thanks for your patience reading. Happy development.

I welcome your suggestions(So don’t be shy to leave one :-D )

Namaste…