Google Firebase - Easy Steps To Run Your Chrome Notification Service

FCM is a new version of Google Cloud Messaging (GCM) offering many great services called Notification , Authenticatin , Database , Storage , Hosting  etc.

Click Here To See Pricing And Features
If you want to add a push notification service , here we go through the necessary and easy steps to run  your Notification project via your FCM account .

As google chrome is the most popular browser and it can run background services for push notifications - both for mobile and desktop - we are going to add the prerequired features to add a notification service to our website .



1.Create your FCM project

First you to create your project in FCM console (https://console.firebase.google.com) and go to the next step .

2. Add Chrome Manifest to your project

The first step is to add your website chrome configuration to a json file mostly is named manifest.json .
you can take a look at this website (airhoner.com) as a sample website using manifest.json and service workers , so you can see a real example there.
to make sure that the manifest is working fine check your chrome developer tools , and check the application tab , which represents your manifest.json file information .


So lets create a chrome manifest file , to see a sample file check airhorner manifest file here .
but writing a manifest file needs a few considerations and you may get a few errors before writing your correct version manifest file.
so to make a quick manifest file with its dependencies you can use this generator app  , therefore you can quickly create a manifest file awesome !, after that add the generated file to anywhere on your website directory and reference it in your html file before </head>  tag:

<link rel="manifest" href="manifest.json">

then add this field at the end of your manifest file  (as described in FCM docs) :
"gcm_sender_id": "103953800507"

3.Add FCM JavaScript SDK

After setting up your manifest file , you need to reference FCM libraries , to add them click on web app in your FCM dash and copy paste the code to your html file . so you need to add a code like the one below :

<script src="https://www.gstatic.com/firebasejs/3.6.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.6.2/firebase-messaging.js"></script>
<script>
  // 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);
</script>

4. Grant Chrome Notification Permission

As you know people need to approve your notification service permission request shown by chrome , so to do that add this sample code (provided by firebase) to your html page , download it from github , make sure to include the code above (step 2) before suing the sample code .
 after completing all the steps here, you can delete the sample UI and use your own interface, or call this javascript method requestpermission() when your app is loaded in case that you don't need to use any html interface used int the code above .

5.Add A Service Worker

In order to get notifications while your website is not opened on chrome browser , you need to add serviceworker file located in your root directory of your website , this will play as a background service on your chrome browser , so add this file to your website project - download it from her sw.js . the only thing you need to modify is this line :

  firebase.initializeApp({ 'messagingSenderId': 'YOUR-SENDER-ID' });


you can find your sender id in your firebase console .

now run your app press F12 and check Application tab and choose the 'service worker' on the left panel . and make sure it starts working after granting notification permission request.

6. Send Notification


To send notifications simply send a post request with the token (IID-Token) shown by running the sample code ( step 3 & 4)  and your apiKey , here is the post message detail:

POST /fcm/send HTTP/1.1
Host: fcm.googleapis.com
Authorization: key=YOUR-SERVER-KEY
Content-Type: application/json

{
  "notification": {
    "title": "Portugal vs. Denmark",
    "body": "5 to 1",
    "icon": "firebase-logo.png",
    "click_action": "http://localhost:8081"
  },
  "to": "YOUR-IID-TOKEN"
}

7. Send Notification From Your Server

To send notification from the server you need to store users tokens in your database , and to do that find this line on step 3
// TODO(developer): Send the current token to your server.
and replace it with this code snippet :

 var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", "https://<your back-end url>/?token"+currenToken, true); // true for asynchronous 
    xmlHttp.send(null);


I wish this post could help you to create your push notification service , please leave your feedback below in the comments (no sign up needed)

Comments

Popular posts from this blog

Xamarin Forms , Designer Tools

How To Run Xamarin Forms Previewer Beta On Windows