Implement the realtime push notification using google firebase

I have integrated firebase in my project last week, and i feel really like it, so, today, i will make a simple application to introduce about firebase to you — maybe you will like it too.

Logic

Whenever user visit our website, we will create a connect to firebase. And then, we can push a notification to the user whenever we want. Of course, the user had left our website before can’t see that.

Implement

Firstly, we need to create a new project. After that, we get the API key and bunch of stuff like below.

Your firebase API information

And then, we create a html file which play the role to connect user to our firebase project. It’s just a simple html file, i have command out the important part, then you can understand it easily.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="Using firebase to implement realtime notification">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Realtime Notification</title>

<!-- Disable tap highlight on IE -->
<meta name="msapplication-tap-highlight" content="no">

<!-- Web Application Manifest -->
<link rel="manifest" href="manifest.json">

<!-- Add to homescreen for Chrome on Android -->
<meta name="mobile-web-app-capable" content="yes">
<meta name="application-name" content="Realtime Notification">
<meta name="theme-color" content="#303F9F">

<!-- Add to homescreen for Safari on iOS -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="Realtime Notification">
<meta name="apple-mobile-web-app-status-bar-style" content="#303F9F">

<!-- Tile icon for Win8 -->
<meta name="msapplication-TileColor" content="#3372DF">
<meta name="msapplication-navbutton-color" content="#303F9F">

<!-- App Styling -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&amp;lang=en">
</head>
<body>
<div style="text-align:center;">
<h1>Push notification</h1>
<form id="message-form" action="#">
<input type="text" name="message" id="message">
<button id="submit" disabled type="submit">
Send
</button>
</form>
</div>

<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/3.3.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyBVqfmstwgSRmzRpHYW87EF8J7JTUB8UXU",
authDomain: "realtime-push-notificati-2a832.firebaseapp.com",
databaseURL: "https://realtime-push-notificati-2a832.firebaseio.com",
storageBucket: "realtime-push-notificati-2a832.appspot.com",
};
firebase.initializeApp(config);
</script>
<script src="scripts/main.js"></script>
</body>
</html>

Next, we will create a class that handle a connection with firebase.

'use strict';

function RealtimeNotification() {

firebase.auth().signInAnonymously().catch(function (error) {
// Handle Errors here.
var errorCode = error.code
var errorMessage = error.message
console.log(errorCode, errorMessage)
})

this.database = firebase.database()
}

window.onload = function() {
window.RealtimeNotification = new RealtimeNotification()
};

It this tutorial, we will using a anonymous, you must enable it on the firebase console.

Enable anonymous sign-in method

Next, we will listen to the firebase database, whenever database have new records, we will display it to the user. Update our class like below.

function RealtimeNotification() {

firebase.auth().signInAnonymously().catch(function (error) {
// Handle Errors here.
var errorCode = error.code
var errorMessage = error.message
console.log(errorCode, errorMessage)
})

this.database = firebase.database()
this.newItems = false

this.loadMessages()
}

// Listen to the change of firebase database
RealtimeNotification.prototype.loadMessages = function() {
this.messagesRef = this.database.ref('messages')
this.messagesRef.off()

let setMessage = function (data) {
if (!this.newItems) return
let message = data.val()
alert(message.text)
}.bind(this)

this.messagesRef.on('child_added', setMessage)
this.messagesRef.on('value', function(messages) {
this.newItems = true
}.bind(this))
};

You will notice that i put the newItems flag to the code. It will help me to just display a new message since the firebase database get the old message also.

Our app is nearly done, but we cannot send a notification for testing, so, i put the text box on the html file to help me do that. Because i was added it on the top, so i will using it by now.

Create a function to handle the events when user interact with our text box and submit button by adding the lines to RealtimeNotification function.

this.messageForm = document.getElementById('message-form')
this.messageInput = document.getElementById('message')
this.submitButton = document.getElementById('submit')
this.messageForm.addEventListener('submit', this.saveMessage.bind(this))

Next, we will handle the function helping user saving the data to firebase database. Since our firebase database is realtime database, so, the another user will get an update, and they will see our message.

// Push notification to firebase database
RealtimeNotification.prototype.saveMessage = function(e) {
e.preventDefault()
if (this.messageInput.value) {
this.messagesRef.push({
text: this.messageInput.value,
}).then(function() {
this.messageInput.value = ''
this.toggleButton()
}.bind(this)).catch(function(error) {
console.error('Error writing new message to Firebase Database', error)
})
}
};

Finally, we make some functions to validate the user input. And we got the completed file like this.

'use strict';

function RealtimeNotification() {
this.checkSetup()

firebase.auth().signInAnonymously().catch(function (error) {
// Handle Errors here.
var errorCode = error.code
var errorMessage = error.message
console.log(errorCode, errorMessage)
})

this.database = firebase.database()
this.newItems = false

this.messageForm = document.getElementById('message-form')
this.messageInput = document.getElementById('message')
this.submitButton = document.getElementById('submit')
this.messageForm.addEventListener('submit', this.saveMessage.bind(this))

var buttonTogglingHandler = this.toggleButton.bind(this)
this.messageInput.addEventListener('keyup', buttonTogglingHandler)
this.messageInput.addEventListener('change', buttonTogglingHandler)

this.loadMessages()
}

// Listen to the change of firebase database
RealtimeNotification.prototype.loadMessages = function() {
this.messagesRef = this.database.ref('messages')
this.messagesRef.off()

let setMessage = function (data) {
if (!this.newItems) return
let message = data.val()
alert(message.text)
}.bind(this)

this.messagesRef.on('child_added', setMessage)
this.messagesRef.on('value', function(messages) {
this.newItems = true
}.bind(this))
};

// Push notification to firebase database
RealtimeNotification.prototype.saveMessage = function(e) {
e.preventDefault()
if (this.messageInput.value) {
this.messagesRef.push({
text: this.messageInput.value,
}).then(function() {
this.messageInput.value = ''
this.toggleButton()
}.bind(this)).catch(function(error) {
console.error('Error writing new message to Firebase Database', error)
})
}
};

// Only enable submit button whenever input field not empty
RealtimeNotification.prototype.toggleButton = function() {
if (this.messageInput.value) {
this.submitButton.removeAttribute('disabled')
} else {
this.submitButton.setAttribute('disabled', 'true')
}
};

// Checks that the Firebase SDK has been correctly setup and configured.
RealtimeNotification.prototype.checkSetup = function() {
if (!window.firebase || !(firebase.app instanceof Function) || !window.config) {
window.alert('You have not configured and imported the Firebase SDK. ' +
'Make sure you go through the codelab setup instructions.')
} else if (config.storageBucket === '') {
window.alert('Your Firebase Storage bucket has not been enabled. Sorry about that. This is ' +
'actually a Firebase bug that occurs rarely. ' +
'Please go and re-generate the Firebase initialisation snippet (step 4 of the codelab) ' +
'and make sure the storageBucket attribute is not empty. ' +
'You may also need to visit the Storage tab and paste the name of your bucket which is ' +
'displayed there.')
}
};

window.onload = function() {
window.RealtimeNotification = new RealtimeNotification()
};

You can test by input the message and click on submit button, it will delivery our message to all another user who visiting our web application also. I have deploy the code and you can testing it easily in here:

And github repo:

Thanks for reading, hope you guys can make some interesting apps with firebase.