Another Step towards Progressive Web Application

Progressive Web App (PWA) is defining the future form of web app. Google has predicted that PWA is going to replace a lot of mobile apps in coming 2-3 years. It's not a surprise that 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 Web App

Push notification has been one of the effective ways to improve retention rate and increase user engagement. The timely received push notification remind 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 update from the server without draining your battery. Once you have enabled the push notification, you are able to receive the alert even without visiting the website.

Example: How a Marketing Site keep us more engaged

neilpatel.com is one of the great 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, that shows you the newest blog from the site on the daily basis. This really improves our engagement with the site for more than 50% than in the past.

Therefore, you need to have push notification for your web app. In fact, 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 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 which what are the optimal wording and presentation to use. You can study the users' behaviour via the analytics data provided.

Firebase Predictions is 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 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 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 this article, 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 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.

Firebase console page Firebase console page

 Tutorial Step 2: Getting your Project Credentials Info

Now, Click on the clog icon beside the "Project Overview" at the top left > choose "Project Settings". Then click on "Cloud Messaging" at 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.

get server key from settings page 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

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: '<replace-with-your-sender-id>'
        };
        firebase.initializeApp(config);
</script>

Tutorial Step 5: Requesting permission from Device

As part of the user privacy policy and to shield the user from unwanted notification, we have to make a request explicitly to the user that we want to send him/her notification.

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.

Notification Request Prompt Notification Request Prompt

 Tutorial Step 6: Getting device token

After the user grant the 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 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 = "token is : " + 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 next step.

Registration token after user grants the permission Registration token after user grants the permission

Tutorial Step 7: Test sending push message

By now, you are all set to send push message to your web app! We will use the curl to initiate the request to inform FCM to fire the notification to the given device. 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.

get Firebase API Access Key Firebase configuration options

To let your users immediately recognize the notification is from you, you can specify the icon for it.

curl -X POST -H "Authorization: key=<API_ACCESS_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 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

receive push notification when web app in the foreground Receiving notification when web app is in the foreground

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, open the browser and browse to the site.

Receiving notification when web app is in the background Receiving notification when web app is in the background

 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.

<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/4.6.2/firebase.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 = {
            apiKey: "<API_KEY>",
            authDomain: "<PROJECT_ID>.firebaseapp.com",
            databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
            storageBucket: "<BUCKET>.appspot.com",
            messagingSenderId: "<SENDER_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);
            });

        messaging.onMessage(function(payload) {
            console.log("Message received. ", payload);
            NotisElem.innerHTML = NotisElem.innerHTML + JSON.stringify(payload) 
        });
    </script>

    <body>

</html>

The End

Last but not least, we are considering to create a push notification simulation tool!! So stay tuned!

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.

References: https://firebase.google.com/docs/cloud-messaging/js/client

Posted in Firebase, Google, Push Notifications, Tutorial, web development on Jul 12, 2017

8 Comments

Godwin - January 26, 2018 @ 3:56 pm

What is curl? How can I enter the curl code? Where should I enter that curl code? I dont know.Please tell

xamDev - March 31, 2018 @ 6:23 am

create php file and put below curl code in it //script \"\n}"); curl_setopt($ch, CURLOPT_POST, 1); $headers = array(); $headers[] = "Authorization: key="; $headers[] = "Content-Type: application/json"; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $result = curl_exec($ch); if (curl_errno($ch)) { echo 'Error:' . curl_error($ch); } curl_close ($ch); echo 'sent through'; ?> remember at Authorization: key you have to use Server key not API Key.

Vico - May 31, 2018 @ 8:12 am

cURL is a library and command line tool (see https://en.wikipedia.org/wiki/CURL for basic informations). You just need to install the curl lib and then execute the above command in your console to execute it. It will send a POST request to FCM with the notification to send to the selected device.

Ken - June 13, 2018 @ 6:39 am

cURL stands for "client URL". cURL is a free and popular command line tool used to initiate request to server using various protocol, for example: POST, GET, PATCH and etc. In order to use cURL, you should either install it in window or it should be readily available in the Linux & Unix based OS. You can run the cURL tool in the terminal shell like "command prompt" in window or "Terminal" in Linux. Hope this helps.

Truebred Labradors - April 11, 2018 @ 1:13 am

Thanks for the guide. I've been using PWA for a while now and wanted to now also include push notifications.

Bart - July 26, 2018 @ 3:05 pm

Notification permission granted. ; 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). Is all i ever get. What's the serviceworker about?

charly arg - August 18, 2018 @ 4:58 pm

Same problem here wonder if something changed on Google's end..

Nagarajan M - August 28, 2018 @ 10:39 pm

all the files should be in root of the server, tried this on a subdirectory got same error, i was able to fix this after i moved all the files to root of the server

Leave a Comment

Your Email address will not be published. Required fields are marked *

About IT Wonders:

IT Wonders is a web agency based in Johor Bahru (JB), Malaysia and Singapore. We provide responsive and custom websites unique to your needs. If you have any inquiries about your website, do not hesitate to contact us.

YOU MIGHT BE INTERESTED:
TOPICS