Tutorial: Web Push notification using Firebase
Another Step towards Progressive Web Application
Progressive Web App (PWA) is defining the future form of the web app. Google has predicted that PWA is going to replace a lot of mobile apps in the coming 2-3 years. It's not a surprise that the founder of Tapzo's summarized in his article The mobile app industry's worst-kept secret has reflected that lack of storage is the main reason 60-80% users are uninstalling the native mobile app within 90 days.In comparison to web app, mobile app is able to access to the mobile native features like push notification, camera and others that the web app does not have. Well, the great news is, with the arrival of PWA, the web app is now finally able to access more native features.
Let's dive in to learn one of the very key benefit PWA is offering: engagement.
Push Notification In The Web App
Push notification has been one of the effective ways to improve retention rate and increase user engagement. The timely received push notification reminds users to react to online messaging, go to check out the cart before the offers and sales end, and even to notify users that their kingdom is under attacked by the enemy player so users can react before it's too late.The magic of the push notification is that it allows the devices to get the update from the server without draining your battery. Once you have enabled the push notification, you can receive the alert even without visiting the website.
Example: How a Marketing Site keep us more engaged
neilpatel.com is one of the SEO marketing sites which has made good use of the push notification. Once you allow the site to send you notifications, you will see the pop-up notification first thing you open the Chrome browser, which shows you the newest blog from the site on the daily basis. This improves our engagement with the site by more than 50% than in the past.Therefore, you need to have push notification for your web app. It is not that difficult to enable it, and we will show you the detailed step by step how to develop a push notification demo web app very shortly.
What's Firebase Cloud Messaging
Firebase Cloud Messaging (FCM) is a service offered by Google to let you relay server messages to registered devices and web app. FCM service is free of charge with some limitations. The size is limited to 2KB or 4KB depending on the type of data, and the message will be kept for a default duration of 4 weeks before it gets deleted.FCM offers an array of helpful tools to help you create the right engagements with users. You can create A/B testing to see what are the optimal wording and presentation to use. You can study the users' behaviour via the analytics data provided.
Firebase Predictions is the latest and perhaps the most exciting features added the to platform. Predictions apply Google's machine learning to your analytics data to predict the users' likely action based on users' behaviour.
For an example of a game app, a user who is likely to spend money to upgrade the game equipment, when he/she fail to pass the stage, the app will offer the option to let the user purchase more advanced equipment to continue the game. On the other hand, for free players, the app will trigger an advertisement to let the user watch to continue the game.
Besides FCM, you can also consider Amazon Simple Notification Service (SNS) and OneSignal. Both are also popular and used by a lot of developers. If you are keen to see how both services work, we can write another demo app next time.
Demo Tutorial
In the following, we will walk you through an easy to follow tutorial on how you can enable push notification using FCM. We will also share with you some of the small tips on what to take note of so you can have this up as quickly as possible.Tutorial Step 1: Register Firebase account
Head to Firebase site and click "Go To Console". Once signed in you will see the following page. Click "Add Project" to create a new project. Give your project a name, and choose the country/region that reflects your currency and revenue reporting.
Tutorial Step 2: Getting your Project & Web App Credentials Info
(Updated: 23 Jul 2020) The recent Firebase's update requires the user to register the web app, as you will need the `appId` value. Give the web app a name, then click next and you will get your config like this. The config can be retrieved "Your apps" section in the Project Setting as well after you have created it. ![firebase-create-web](/img/blog/push-notis/firebase-create-web-app.jpg)Now, Click on the cog icon beside the "Project Overview" at the top left > choose "Project Settings". Then click on "Cloud Messaging" on the settings page like below. Take note of the Server Key and Sender ID, you will need this later. You can ignore the "Legacy server key" and use "Server Key". Otherwise. you will face a problem when running the curl to test sending the notification.
Firebase Project Settings for Cloud Messaging
Tutorial Step 3: Create the Simple HTML
Without further ado, let's start writing the simple HTML code. The page will show us the token and any message sent by the Firebase to us later.<html>
<title>Firebase Messaging Demo</title>
<style>
div {
margin-bottom: 15px;
}
</style>
<body>
<div id="token"></div>
<div id="msg"></div>
<div id="notis"></div>
<div id="err"></div>
<script>
MsgElem = document.getElementById("msg")
TokenElem = document.getElementById("token")
NotisElem = document.getElementById("notis")
ErrElem = document.getElementById("err")
</script>
</body>
</html>
Tutorial Step 4: Initialising Firebase and Creating Service Worker JS
Then you have to include the firebase.js. Remember to replace your "sender ID" as the value for messagingSenderId field. After that, you can initialise Firebase.<script>
var config = {
messagingSenderId: "YOUR-SENDER-ID",
apiKey: "YOUR_API_KEY",
projectId: "YOUR_PROJECT_ID",
appId: "YOUR_APP_ID"
};
firebase.initializeApp(config);
</script>
Next, copy the following to firebase-messaging-sw.js
and place it to the root of the web folder, this will create the service worker. (note on update for Firebase v7.0.0 and above)
importScripts("https://www.gstatic.com/firebasejs/7.16.1/firebase-app.js");
importScripts(
"https://www.gstatic.com/firebasejs/7.16.1/firebase-messaging.js",
);
// For an optimal experience using Cloud Messaging, also add the Firebase SDK for Analytics.
importScripts(
"https://www.gstatic.com/firebasejs/7.16.1/firebase-analytics.js",
);
// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
messagingSenderId: "YOUR-SENDER-ID",
apiKey: "YOUR_API_KEY",
projectId: "YOUR_PROJECT_ID",
appId: "YOUR_APP_ID",
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log(
"[firebase-messaging-sw.js] Received background message ",
payload,
);
// Customize notification here
const notificationTitle = "Background Message Title";
const notificationOptions = {
body: "Background Message body.",
icon: "/itwonders-web-logo.png",
};
return self.registration.showNotification(
notificationTitle,
notificationOptions,
);
});
Without the file firebase-messaging-sw.js
, you will get following error
; FirebaseError: Messaging: We are unable to register the default service worker.
Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script. (messaging/failed-serviceworker-registration).
Tutorial Step 5: Requesting permission from Device
We have to make a request explicitly to the user that we want to send him/her notification and get the permission from user to do so.const messaging = firebase.messaging();
messaging
.requestPermission()
.then(function () {
MsgElem.innerHTML = "Notification permission granted."
console.log("Notification permission granted.");
})
.catch(function (err) {
ErrElem.innerHTML = ErrElem.innerHTML + "; " + err
console.log("Unable to get permission to notify.", err);
});
If you start a local server and serve the code above, you will get the request prompt like the following screenshot.
Tutorial Step 6: Getting device token
After the user grant permission for us to send the notification, we can get an FCM registration token that can be used to send push messages to this user. For the sake of the simplicity of this demo app, we do not store the registration token in the database. We will modify the previous function to get the token and print it on the web page. const messaging = firebase.messaging();
messaging
.requestPermission()
.then(function () {
MsgElem.innerHTML = "Notification permission granted."
console.log("Notification permission granted.");
// get the token in the form of promise
return messaging.getToken()
})
.then(function(token) {
// print the token on the HTML page
TokenElem.innerHTML = "Device token is : <br>" + token
})
.catch(function (err) {
ErrElem.innerHTML = ErrElem.innerHTML + "; " + err
console.log("Unable to get permission to notify.", err);
});
Below is the screenshot you will see if you run the local server to check your code. The registration token (example: csxYa...jR4RI) is a long string of text. You will need this token for the next step.
Tutorial Step 7: Test sending push message
By now, you are all set to send a push message to your web app! There are two ways to test sending message to the device.
A) Using Firebase Console
Go to Engage > Cloud Messaging, then click 'New Notification'.
Enter the title and text, then click on 'Send test message
'.
Paste the device token you have gotten earlier, then click 'Test'.
If everything is set up properly, you will see the push notification showing up.
B) Using Curl
Replace your API_ACCESS_KEY and the DEVICE_REGISTRATION_TOKEN we obtained just now. You can get your API_ACCESS_KEY by clicking on the "Authentication" under "Develop", then click on the "WEB SETUP" on the top right.
To let your users immediately recognize the notification is from you, you can specify the icon for it.
curl -X POST -H "Authorization: key=<Server Key>" \
-H "Content-Type: application/json" \
-d '{
"data": {
"notification": {
"title": "FCM Message",
"body": "This is an FCM Message",
"icon": "/itwonders-web-logo.png",
}
},
"to": "<DEVICE_REGISTRATION_TOKEN>"
}' https://fcm.googleapis.com/fcm/send
You will see the following response after successfully executing the curl command
success response after running curl command
When your app is in the foreground, i.e. the user is currently viewing the web page, you can receive and notification directly on the page. For this example, we display the whole notification payload like in below
However, if your app is in the background, the message received will trigger a display notification in the browser like the screenshot below. You can specify what action to perform if the user clicks on the notification as well. For example, to open the browser and load the site. Nevertheless, this behaviour can be changed.
The Complete Solution
Here's the complete code based on what we have discussed so far. You can also get the source code from GitHub via this link.If you are facing issue to get it running, you might also check with messaging example in Firebase quickstart-js. Official source code get updated quite frequently.
<html>
<title>Firebase Messaging Demo</title>
<style>
div {
margin-bottom: 15px;
}
</style>
<body>
<div id="token"></div>
<div id="msg"></div>
<div id="notis"></div>
<div id="err"></div>
<script src="https://www.gstatic.com/firebasejs/7.16.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.16.1/firebase-messaging.js"></script>
<script>
MsgElem = document.getElementById("msg");
TokenElem = document.getElementById("token");
NotisElem = document.getElementById("notis");
ErrElem = document.getElementById("err");
// Initialize Firebase
// TODO: Replace with your project's customized code snippet
var config = {
'messagingSenderId': 'YOUR-SENDER-ID',
'apiKey': 'YOUR_API_KEY',
'projectId': 'YOUR_PROJECT_ID',
'appId': 'YOUR_APP_ID',
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging
.requestPermission()
.then(function () {
MsgElem.innerHTML = "Notification permission granted."
console.log("Notification permission granted.");
// get the token in the form of promise
return messaging.getToken()
})
.then(function(token) {
TokenElem.innerHTML = "token is : " + token
})
.catch(function (err) {
ErrElem.innerHTML = ErrElem.innerHTML + "; " + err
console.log("Unable to get permission to notify.", err);
});
</script>
</body>
</html>
The End
If you are looking for a company to that is able to do website design and PWA you can consider us. We have years of experience in both UI/UX domain and the technical aspects of web.That's all for now! Thanks for the reading and if you find this article helpful, do remember to like our Facebook and Twitter. Your comments will help us to do even better at next post. Cheers.
Sample Source Code: github
References: https://firebase.google.com/docs/cloud-messaging/js/client
Change Log
26 Apr 2021 Github example update. Added description of how to send test message via Firebase Console.23 Jul 2020 The Github example has been updated to user Firebase 7.16.1. There's some breaking change in the firebase-sw.js as well. So if you get a blank response or error, try to get updated the example source code again.
15 Mar 2020
There's some breaking change from the recent Firebase update on v7.0.0. Previously, having {messagingSenderId: 'xxx'}
was sufficient config for firebase messaging, Now, all of these (apiKey, projectId, appId)
are needed too. Otherwise, you will be getting an error.
[Messaging] FirebaseError: Installations:
Missing App configuration values. (installations/missing-app-config-values)
Posted on Apr 21, 2021
Leave a comment or suggestion below