Sending Push Notifications from Firebase

Bharat Agarwal
GDG Jalandhar

--

Firebase is a platform that offers various services for mobile and web applications and helps developers build an application quickly with a lot of features. We can send push notification to the client with firebase cloud messaging, which allows us to send messages to any devices over the network using an HTTP request.

In this article, I will be going to show you how we can trigger push notification from a web page from javascript.
You can visit the demo web application or you can check code on GitHub.

Here I going to make two web pages, one service worker file, and one app.js file

  1. index.html is used for subscribing.
  2. send.html is used for triggering push notifications.
  3. app.js managing subscriptions and sending a push notification.
  4. sw.js is used to receive push notifications from firebase when in background.

Steps to follow:

  1. Create a Firebase account and create a new project.
  2. Register web app from the firebase project dashboard.
  3. Copy the firebase config file and past in sw.js and app.js file.
var firebaseConfig = {
apiKey: "XXXXXXXXXXXXXXXXXXXXXX",
authDomain: "XXXXXXXXX.firebaseapp.com",
databaseURL: "https://XXXXXXXXX.firebaseio.com",
projectId: "XXXXXXXXXX",
storageBucket: "XXXXXXXXXXXXX.appspot.com",
messagingSenderId: "XXXXXXXXXXXXX",
appId: "XXXXXXXXXXXXXX"
};
firebase.initializeApp(firebaseConfig);

Subscribe for push notifications and get Token

For subscribing push notifications and to get token will use getToken() and which return us promises.

If notification permission has not granted this method will ask the user for the notification permissions. Otherwise, it will return a token or reject the promise due to an error.

Notification.requestPermission().then(permission => {
if (permission == "granted") {
messaging.getToken().then(currentToken => {
console.log(currentToken);
});
} else {
console.log("permission denied")
}
}).catch(e=>{
console.log(e)
});

Messaging service requires a service worker file.

if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./sw.js').then(res => {
console.log("Register Success");
messaging.useServiceWorker(res);
}).catch(e => {
console.log(e);
});
}

Also, you need to import firebase, firebase messaging library and firebase config for the project in service worker file sw.js

importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js');
var firebaseConfig = {
apiKey: "XXXXXXXXXXXXXXXXXXXX",
authDomain: "XXXXXXXX.firebaseapp.com",
databaseURL: "https://XXXXXXXXXX.firebaseio.com",
projectId: "XXXXXXXXXXXXXX",
storageBucket: "XXXXXXXXXXXXXX.appspot.com",
messagingSenderId: "XXXXXXXXXXXXX",
appId: "XXXXXXXXXXXXXXXXXX"
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();

Sending Push Notification from web page

For sending push notification it requires serverkey from firebase settings, and have to send serverkey in the header as Authorization, and with the FCM API, we have to pass notifications details (title and body) in the body while calling FCM APIs.

let body = {
to: "your push notification Token",
notification: {
title: "Title",
body: "Body",
click_action: "/",
}
};
const options = {
method: "POST",
headers: new Headers({
Authorization: "key=AAAAAAAAXAXAXAXAXAXAXAX(Your Server KEY)",
"Content-Type": "application/json"
}),
body: JSON.stringify(body)
};
fetch("https://fcm.googleapis.com/fcm/send", options)
.then(res => res.json())
.then(data => {
if (data.failure == 1) {
alert("Token Expire");
} else {
alert("Send Success");
}
}).catch(err => {
alert(err);
});

You can find the Sample code at Github.

Got questions or feedback? Let me know in the comments! Thanks for reading! Hope the information was helpful.

--

--

Bharat Agarwal
GDG Jalandhar

Opensource Contributor, Working on Full Stack Development in Web and Mobile (Flutter) platform, also Cybersecurity Enthusiast.