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

Copy following to firebase-messaging-sw.js and place it to the root of the web folder, this will create the service worker.

importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');

// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
   'messagingSenderId': 'YOUR-SENDER-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

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=<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 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

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

Posted in Firebase, Google, Push Notifications, Tutorial, web development on Oct 31, 2018

Leave a comment or suggestion below

30 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.

frek - December 13, 2018 @ 4:34 pm

Can execute "sh curl-test.sh" at the terminal

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

Subhash Diwakar - August 28, 2018 @ 11:27 am

Everytime i get this error 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). How can I link firebase-messaging-sw.js to html

Ken Ng - October 31, 2018 @ 3:31 am

You do not have to link it, the firebase js done it for you. You just have to create this file and put to the root web folder of it. See the updated folder structure in the blog. See the github repo https://github.com/kenng/firebase-push-notification-demo

Pawan - September 27, 2018 @ 7:58 am

Notification permission granted. ; FirebaseError: Messaging: This browser doesn't support the API's required to use the firebase SDK. (messaging/unsupported-browser).

Robert van Lienden - November 9, 2018 @ 12:04 pm

Realy thanks for this article! I'm struggeling for like a week with Push notifications. So much half working code on the internet, and so many puzzle pieces to connect. Your example is the first (!!) I get running in seconds, and understands in like a hour!

David - November 16, 2018 @ 12:12 pm

Thank you very much for being so clear in the explanations, may God bless you!

Sanjay - December 7, 2018 @ 11:44 am

Notification permission granted. ; FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: The script has an unsupported MIME type ('text/html'). (messaging/failed-serviceworker-registration). Facing this issue , please help

Ken Ng - December 9, 2018 @ 5:26 am

Do you face any issue running github sourcecode? You might have missing file or wrong file type. Check to make sure you have firebase-messaging-sw.js at your root folder.

om vishnu - December 10, 2018 @ 10:46 am

good job for this blog

Yogender - December 14, 2018 @ 6:12 am

thankyou it works for me. i did this what how to display notification icon or alert. i am just only getting the response. which i have sent using curl.

Jaydeep Goswami - January 10, 2019 @ 12:39 pm

First of all thanks a lot brother for putting your great efforts and helping us. and next for all those who are getting confused in cURL Shell command or having no idea of command line interface than this is for those: Simply create a PHP file by any name like fire.php and copy the following code to send the notification. This will help you send the notification to the browser as shown in the above example : <?php $data = array(); $data['data']['notification']['title'] = "FCM Message"; $data['data']['notification']['body'] = "This is an FCM Message"; $data['data']['notification']['icon'] = "/itwonders-web-logo.png"; $data['data']['webpush']['headers']['Urgency'] = "high"; $data['to'] = "device-token-or-client-token-here"; // print_r(json_encode($data)); $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); $headers = array(); $headers[] = "Authorization: key = Your-server-key-here"; $headers[] = "Content-Type: application/json"; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_URL , "https://fcm.googleapis.com/fcm/send"); curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); curl_setopt($ch,CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch,CURLOPT_POSTFIELDS, json_encode($data)); // curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, false); // curl_setopt($ch,CURLOPT_SSL_VERIFYPEER , false); $result = curl_exec($ch); if (curl_errno($ch)) echo 'Error:' . curl_error($ch); curl_close($ch); echo "<pre>Result : "; print_r(json_decode($result,1)); echo '<br>sent through</pre>'; ?> Note : don't forget to replace the DEVICE TOKEN & SERVER KEY values with your values. That's it! Now run this file in another tab and you can see the notification in the first tab. :)

mohini kandalkar - January 17, 2019 @ 9:56 am

after run this fire.php i got error Error:SSL certificate problem: unable to get local issuer certificate

Raman - April 23, 2019 @ 5:13 am

Thanks Jaydeep but when I run your code, the code in firebase-messaging-sw.js override it, and in notification - there are static values as defined in firebase-messsaging-sw.js file, please help

Mohammed Junaid - March 22, 2019 @ 11:32 am

{"multicast_id":7072924828349425332,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]} Getting this error on running Curl command

Rick - May 7, 2019 @ 2:56 pm

Hi Thanks for this tutorial.... Just a question: ¿Its posibble to set a push notification for Wordpress Multisite?... I mean, a differente service of Push Notifications for each site or subdomain? Some advice please?

Ken Ng - June 10, 2019 @ 6:03 am

Yes, just have to create different Firebase Project for each Wordpress subdomain and initialize the Wordpress based on the project setting.

suhel - June 1, 2019 @ 2:21 am

need help with send notification form rest is working fine

Marco - July 8, 2019 @ 11:21 am

Beautiful guide! I can get the notification out but I don't know how to change it. When I publish a new article, I would like a new notification to come out with the new article but I can't. How can I do? Thank you

Daniel LD - July 31, 2019 @ 7:36 am

Thanks a lot!! The tutorial is great! I only have one doubt, does this work on iOS?

Mayqui Quintana - September 5, 2019 @ 7:05 pm

Hi, I want could receive the push notification although the browser is not open.

Ken Ng - September 24, 2019 @ 4:14 am

likely not, as the push notification only pop up when the page is not active. it's just like when you are using whatsapp and someone send you a new message, it will just shown in the conversation box than as a push notification.

Charles Ram - September 17, 2019 @ 10:04 pm

Thank you! very nice explanation

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