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

    ".read": true,
    ".write": true

Full Source Code

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

  // Check Notification 
			alert('Not supported');
					alert('You denied to show notification');
				}else if(p=='granted'){
					alert('You allowed to show notification');

  // Add Data to users
	function writeUserData(name, message) {
	    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++){

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


  // Click btn to send push notification

  // click to remove notification from DB
            // alert();
  // Initialize Firebase
  // TODO: Replace with your project's customized code snippet
  var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  var database = firebase.database().ref().child("/users/");
  database.on('value', function(snapshot) {

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


Download Full Source-code

5052total visits,7visits today