Realtime Web Push Notification Using Firebase

Introduction to Push Notifications?

A notification is a message that pops up on the user’s device. Notifications can be triggered locally by an open application, or they can be “pushed” from the server to the user even when the app is not running. They allow your users to opt-in to timely updates and allow you to effectively re-engage users with customized content.

Chrome currently uses Firebase Cloud Messaging (FCM) for web push notifications. By default we use our own FCM account for notifications, meaning that your subscribers are associated with our keys. Although not mandatory, a FCM account will help you get the subscribers end-point list.

Firebase Setup for Web Push?

Login to the Firebase Console and Create a New Project / Add Project.

Next, give a Project name to the project (eg. Web Push) and select a country or region. Then hit Create Project.

Next, go to database get started, create database, Select start in locked mode click – Enable

Click database rule and change To

{
  "rules": 
 {
    ".read": true,
    ".write": true
 }
}

Full Source Code

var dnperm = document.getElementById('dnperm');

  // Check Notification 
	dnperm.addEventListener('click',function(e){
		e.preventDefault();
		if(!window.Notification){
			alert('Not supported');
		}else{
			Notification.requestPermission().then(function(p){
				if(p=='denied'){
					alert('You denied to show notification');
				}else if(p=='granted'){
					alert('You allowed to show notification');
				}
			});
		}
	});


  // Add Data to users
	function writeUserData(name, message) {
	  database.push().set({
	    username: name,
	    message: message
	  });
	}

  // Remove data
    function removeUserData(userId) {
        firebase.database().ref('users/' + userId).remove();
    }


    // print to html
	function renderUI(obj){
		var html='';
		
		var keys = Object.keys(obj);
		for(var i=0;i<keys.length;i++){
            console.log(keys[0]);
			html+="



<li class='list-group-item'>ID: "+ keys[i] +", <b><i>"+obj[keys[i]].username+"</i></b> says: "+obj[keys[i]].message+" <button data-id='"+keys[i]+"' id='btnRemove' class='btn btn-danger'><i class='fa fa-remove'></i></button></li>




";
		}
		$('#comment').html(html);
	}

  // Click btn to send push notification
	$('#btnGetMessage').click(function()
  {
		writeUserData($('#username').val(),$('#message').val());
		$('#username').val('');
		$('#message').val('');
	});


  // click to remove notification from DB
    $(document).ready(function(){
        $('body').on('click','#btnRemove',function(){
            // alert();
		    removeUserData($(this).data('id'));
	    });
    });
    
  // Initialize Firebase
  // TODO: Replace with your project's customized code snippet
  var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  };
  firebase.initializeApp(config);
  var database = firebase.database().ref().child("/users/");
  
  database.on('value', function(snapshot) {
    renderUI(snapshot.val());
  });



  // On child added to db
  database.on('child_added', function(data) {
    	if(Notification.permission!=='default'){
					var notify;
					
						notify= new Notification('CodeWife - '+data.val().username,{
							'body': data.val().message,
							'icon': 'bell.png',
							'tag': data.getKey()
						});
						notify.onclick = function(){
							alert(this.tag);
						}
		}else{
			alert('Please allow the notification first');
		}
  });

 

Download Full Source-code

3306total visits,12visits today