Sending Push Notifications from Firebase
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
index.html
is used for subscribing.send.html
is used for triggering push notifications.app.js
managing subscriptions and sending a push notification.sw.js
is used to receive push notifications from firebase when in background.
Steps to follow:
- Create a Firebase account and create a new project.
- Register web app from the firebase project dashboard.
- Copy the firebase config file and past in
sw.js
andapp.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.