Firebase Web Push Notifications

mukul taneja
Aug 23, 2020 · 6 min read

This article will help you implement firebase web push notifications without using any packages in your project for latest version 7.18.0 or above.

Image for post
Image for post

INTRODUCTION

Firebase uses cloud services for its notification services on Android,IOS & Web.Firebase Cloud Messaging or FCM run on basic principles of tokens, which is uniquely generated for each device & later used for sending messages to respective devices.

Web Push Notification uses javascript to call firebase methods and generate the token.This article will explain how to implement firebase cloud messaging ,right from setting up project.

Note-FCM only works for Https server

1.Register Firebase App

  1. Go to link https://console.firebase.google.com/u/0/ and click create project.
Image for post
Image for post

2.Enter your project name ,& continue once name is checked by google for its uniqueness

3.Enter the information asked such as country and accept terms & conditions and continue.Wait for some time till project is created.

4.Add app to your project,it can be anything from Android,IOS,Web,Unity.For this article we need web app so click on web icon represented as </>

Image for post
Image for post

5.Add a nick-name to your app,this nick-name is only for user and internal use ,which means it is useful just to differentiate between apps in a project from perspective of user.

You can add hosting for project if your project is already not running on https server else you can skip this step.

Click on Register app

Image for post
Image for post

6.After your app is Registered you will be presented with Firebase SDK,which look like the code written below,you may copy this now,if not it can also be used later from settings,steps for which will be described in next section.

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.18.0/firebase-app.js"></script>
General
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
For Messaging
<script src="https://www.gstatic.com/firebasejs/7.18.0/firebase-messaging.js"></script>
Do not copy below code as it is,values will be different for your app.
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyDOCAbC123dEf456GhI789jKl01-MnO",
authDomain: "myapp-project-123.firebaseapp.com",
databaseURL: "https://myapp-project-123.firebaseio.com",
projectId: "myapp-project-123",
storageBucket: "myapp-project-123.appspot.com",
messagingSenderId: "65211879809",
appId: "1:65211879909:web:3ae38ef1cdcb2e01fe5f0c",
};
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>

2.Add firebase to your Project.

  1. On dashboard , go to you side bar and click settings icon.Refer image below.Click project Settings.
Image for post
Image for post

2.Once Setting page(General Settings) is opened you scroll down to bottom of page and copy the code displayed for CDN selected.

Image for post
Image for post

3.Add this code to your HTML file at the end after body tag and add CDN script for firebase messaging , as shown in code below.

<body>
----
----Your Page Contents
----
</body>
<script src="https://www.gstatic.com/firebasejs/7.18.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.18.0/firebase-messaging.js"></script>
//Do not copy below code as it is values will be different for your app.
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyDOCAbC123dEf456GhI789jKl01-MnO",
authDomain: "myapp-project-123.firebaseapp.com",
databaseURL: "https://myapp-project-123.firebaseio.com",
projectId: "myapp-project-123",
storageBucket: "myapp-project-123.appspot.com",
messagingSenderId: "65211879809",
appId: "1:65211879909:web:3ae38ef1cdcb2e01fe5f0c",
};
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>

3.Running Firebase Service

  1. For the code mentioned above, add the lines in code below ,after firebase initialize line.
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const messaging=firebase.messaging();//Custom function made to run firebase service
getStartToken();
//This code recieve message from server /your app and print message to console if same tab is opened as of project in browser messaging.onMessage(function(payload){
console.log("on Message",payload);
});

2.The code below can be written in separate js file included in your html page or can be appended to code above in <script> tag.

messaging.getToken() retrieves token by called firebase sdk,if token is found ,we send it to server for storage,else we ask for permission to user to send him notification by calling method RequestPermission(),which is custom function.

setTokenSentToServer() is also a custom function which uses local storage to set value of sendTokenToServer==1 if token is already sent to server and 0 if token is not sent to server some error is occured while sending to sever or retrieving it from firebase SDK

function getStartToken(){
messaging.getToken().then((currentToken) => {
if (currentToken) {
sendTokenToServer(currentToken);
}
else {
// Show permission request.
RequestPermission();
setTokenSentToServer(false);
}
}).catch((err) => {
setTokenSentToServer(false);
});
}function RequestPermission(){messaging.requestPermission()
.then(function(permission){
if (permission === 'granted') {
console.log("have Permission");
//calls method again and to sent token to server
getStartToken();
}
else{console.log("Permission Denied");}
.catch(function(err){
console.log(err);
})
}function sendTokenToServer(token){
if (!isTokensendTokenToServer()) {
$.ajax({url: URL,type: 'POST',data: {//whatever you wanna send
push_token:token,
},success: function (response) {
setTokenSentToServer(true);
},
error: function (err) {
setTokenSentToServer(false);
},
});
}}
function isTokensendTokenToServer() {return window.localStorage.getItem('sendTokenToServer') === '1';
}
function setTokenSentToServer(sent) {
window.localStorage.setItem('sendTokenToServer', sent ? '1' : '0');
}

3.Send Message from Project

1.Sending Mesaging Pre-requirements

a.For vapidKey go to settings on firebase console,click cloud messaging ,scroll down to bottom of page in Web Configuration section click on button Generate Key Pair.

Image for post
Image for post
Image for post
Image for post

b.Code to send message from your project ,refer Google on how to send API request from your respective programming language.

METHOD-POST

URL-https://fcm.googleapis.com/fcm/send

HEADERS-send with authorization using key which can be found on Settings>Cloud Messaging,look for project credentials section and copy server key.

to-Token you saved on in your database for user .

registeration_ids-if sending to multiple device

c.To read about diiferent messages and fcm_options you can refer to this url https://firebase.google.com/docs/cloud-messaging/concept-options

Image for post
Image for post

d.If you want send in FCM notifications in you format you can refer to link https://firebase.google.com/docs/cloud-messaging/js/first-message and see notification message format

e.for this article i will be using data messages/custom/without predefined key-value pairs.

Note-Data send is json format

f.my data look like

{"registration_ids":{token1,token2,token3},"data":{ "title":"demo","body":this is demo data","clickUrl":"https://google.com"}}

5.Add Service Worker

  1. Add a Service-Worker file by name (don’t change the name) firebase-messaging-sw.js in your project root folder or public folder such as opening link-https://your-url/firebase-messaging-sw.js gives you content of file.
  2. payload is data you send you recieve when api request will be sent.
  3. You will not require notification event listener if message is send through standard FCM notification message ,fcm will handle it itself.
importScripts('https://www.gstatic.com/firebasejs/7.18.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.18.0/firebase-messaging.js');
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyDOCAbC123dEf456GhI789jKl01-MnO",
authDomain: "myapp-project-123.firebaseapp.com",
databaseURL: "https://myapp-project-123.firebaseio.com",
projectId: "myapp-project-123",
storageBucket: "myapp-project-123.appspot.com",
messagingSenderId: "65211879809",
appId: "1:65211879909:web:3ae38ef1cdcb2e01fe5f0c",
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging.usePublicVapidKey(ABp.........BS5A);messaging.onBackgroundMessage(function(payload) {
const notificationTitle = payload.data.title;
const notificationOptions = {
body: payload.data.message,
icon:'PATH TO ICON IF ANY',
data: { url:payload.data.onClick }, //the url which we gonna use later
};
return self.registration.showNotification(notificationTitle,notificationOptions);
});//Code for adding event on click of notificationself.addEventListener('notificationclick', function(event) {let url = event.notification.data.url;event.notification.close(); event.waitUntil(clients.matchAll({type: 'window'}).then( windowClients => {// Check if there is already a window/tab open with the target URLfor (var i = 0; i < windowClients.length; i++) {var client = windowClients[i];// If so, just focus it.if (client.url === url && 'focus' in client) {return client.focus();}}// If not, then open the target URL in a new window/tab.if (clients.openWindow) {return clients.openWindow(url);}}));});

These are the only steps you will need to add firebase web push to your project.

Press Clap if this article really helped you.

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data…

Sign up for Analytics Vidhya News Bytes

By Analytics Vidhya

Latest news from Analytics Vidhya on our Hackathons and some of our best articles! Take a look

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

mukul taneja

Written by

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

mukul taneja

Written by

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store