integrating firebase javascript web push notification

Saturday 23 Feb 2019


complete guide to integrate firebase foreground and background web push notification with source code

before getting started , you must have SSL enabled website , just  go to https://console.firebase.google.com and create a project , we will get the following configuration things as :

<script src="https://www.gstatic.com/firebasejs/5.8.4/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "AIzaSyAplsH4Lsdr7TuIHsyxJFQ-13T3mu2u9Zo",
    authDomain: "testing-6d2e7.firebaseapp.com",
    databaseURL: "https://testing-6d2e7.firebaseio.com",
    projectId: "testing-6d2e7",
    storageBucket: "testing-6d2e7.appspot.com",
    messagingSenderId: "22996533258"
  };
  firebase.initializeApp(config);
</script>





  create firebase-messaging-sw.js file in website root directory that will look like this :

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


// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
 var config = {
    apiKey: "AIzaSyAplsH4Lsdr7TuIHsyxJFQ-13T3mu2u9Zo",
    authDomain: "testing-6d2e7.firebaseapp.com",
    databaseURL: "https://testing-6d2e7.firebaseio.com",
    projectId: "testing-6d2e7",
    storageBucket: "testing-6d2e7.appspot.com",
    messagingSenderId: "22996533258"
  };


     firebase.initializeApp(config);
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
var messaging = firebase.messaging();




messaging.setBackgroundMessageHandler(function(payload) {
    console.log('[firebase-messaging-sw.js] Received background message ', payload);
    // Customize notification here
   var notificationTitle = payload.data.title;
   var notificationOptions = {
       body: payload.data.body,
       icon: payload.data.icon
    };


    return self.registration.showNotification(notificationTitle,
        notificationOptions);
});




create manifest.json file in directory where your  source  code is , this file looks like :

{
  "gcm_sender_id": "103953800507"
}

please note,  "gcm_sender_id": "103953800507" will be exactly same , this value is not from firebase configuration .  

 




place the below code in page where we will ask for user permission and if user grant , we will save token and let the notification fire on

<!DOCTYPE html>
<html>
<head>
  <title>  hello world  </title>

  <script src="https://www.gstatic.com/firebasejs/5.5.0/firebase.js"></script>
<link rel="manifest" src="manifest.json" />
 <script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
  


<script>
  ///////////   basic thing
  var config = {
    apiKey: "AIzaSyAplsH4Lsdr7TuIHsyxJFQ-13T3mu2u9Zo",
    authDomain: "testing-6d2e7.firebaseapp.com",
    databaseURL: "https://testing-6d2e7.firebaseio.com",
    projectId: "testing-6d2e7",
    storageBucket: "testing-6d2e7.appspot.com",
    messagingSenderId: "22996533258"
  };
  firebase.initializeApp(config);
  ////////  ending basic thing
  
  
  // Retrieve Firebase Messaging object.
const messaging = firebase.messaging();



///request permission things
messaging.requestPermission().then(function() {
  console.log('Notification permission granted.');
  // TODO(developer): Retrieve an Instance ID token for use with FCM.


 if(isTokenSentToServer){
    console.log('Token already saved !');   
}else{
    getRegToken();
 }
 //getRegToken();


}).catch(function(err) {
  console.log('Unable to get permission to notify.', err);
});





///get the token 
function getRegToken(){
  // Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken().then(function(currentToken) {
  if (currentToken) {
      console.log(currentToken);
      save_token(currentToken)
      setTokenSentToServer(true);
    //sendTokenToServer(currentToken);
    //updateUIForPushEnabled(currentToken);
  } else {
    // Show permission request.
    console.log('No Instance ID token available. Request permission to generate one.');
    // Show permission UI.
    //updateUIForPushPermissionRequired();
    setTokenSentToServer(false);
  }
}).catch(function(err) {
   console.log('An error occurred while retrieving token. ', err);
   showToken('Error retrieving Instance ID token. ', err);
   setTokenSentToServer(false);
});
}




 function setTokenSentToServer(sent) {
    window.localStorage.setItem('sentToServer', sent ? '1' : '0');
  }


function isTokenSentToServer() {
    return window.localStorage.getItem('sentToServer') === '1';
  }




///save generated token in database to send the notification
function save_token(currentToken)
{
  $.ajax({
    url: 'save_token.php',
    method: 'post',
    data: 'token='  + currentToken
  }).done(function(result){
    alert(result);
  })
}




//to receive the notification
messaging.onMessage(function(payload) {
   console.log('Message received. ', payload);
    notificationTitle = payload.data.title;
    notificationOptions = {
       body: payload.data.body,
       icon: payload.data.icon
    };
    var notification = new Notification(notificationTitle,notificationOptions);
});




</script>
</head>
<body>


   <h1> <a href="index.php"> getting started with firebase </a> </h1>
  <hr />
</body>
</html>




create save_token.php file to save  token in database

<?php 
    $servername = "localhost";
    $username = "myun";
    $password = "mypass";
    $dbname = "mydb";
       
           $connection = new MySQLi($servername,$username,$password,$dbname);


   $token = $_POST["token"];
   $sql = "INSERT INTO fb_push(token)VALUES('$token')";
   $connection->query($sql);
?>





finally  create send.php file to send notification

<?php 
  define('SERVER_API_KEY','AAAABVqzQAo:APA91bGwEeHHIQjqTWqAdXf0PiNbx6HoaTQZXBty0z-oTYPM5_CphSAx72PvlaWVXDMfK50wvqJWyhm-HDy5ifsQTrrauUOpXhsp8zAvJSDcpX8qdAto62GQjULSd520fpyioDJP-ynl');
  

  $servername = "localhost";
  $username = "wpdinu";
  $password = "DInu12#$";
  $dbname = "darima";
     $connection = new MySQLi($servername,$username,$password,$dbname);

     $sql = "SELECT *FROM fb_push";
     $rows  = $connection->query($sql);
     while($res = $rows->fetch_assoc())
     {
           $registration_ids[]  = $res["token"];
     }
  // $tokens = ['dUE1xTMPkiA:APA91bEZGux5hT4Z_GCm_-mq1nqNyASi3eHvEpqyEUi_4ldwSbknoPDbaLzVxeWW25jMeWdV2Fw6tuRNmlAn41Nrd4GRDPkXF5plc6JwS_UF_-GexGSEai2zB03Va2sAoGIpP3nrcJeb'];
   //print_r($registration_ids);
 /*
 $header = array
(
    'Authorization: key=' . SERVER_API_KEY,
    'Content-Type: application/json'
);
  */
  $header = [
     'Authorization: Key='. SERVER_API_KEY,
     'Content-Type: Application/json'
    ]; 

$msg = [
 'title' => 'taohid ansari',
 'body' => 'hello world notification',
 'icon' => 'taohid.png',
 'image' => 'taohid.jpg',
];


$payload = [
  'registration_ids' => $registration_ids,
  'data' => $msg
];


    $curl = curl_init();
   curl_setopt_array($curl, array(
      CURLOPT_URL => "https://fcm.googleapis.com/fcm/send",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => json_encode($payload),
      CURLOPT_HTTPHEADER => $header 
   ));


    $response = curl_exec($curl);
    $err = curl_error($curl);
     curl_close($curl);


      if($err)
      {
           echo "curl error  :".$err;
      }
      else
      {
         echo $response;
      }


?>

just hit the url send.php , notification will be send to all the subscribed user's device , enjoy :)