Sunday, April 1, 2018

Send Browser Notifications from Website

Many web applications use browser push notifications to notify their users. These notifications are useful to send reminders or notify users instantly even if the browser window is not active. In this tutorial we will implement this push notification to be sent after every five minutes.

Send Browser Notifications from Website

The Notifications API is an API which allows websites to control the system notifications displayed to end user. These notifications work outside the current viewport which means even if the current page document isn't active it will still send notifications to user. 

We will be using Notifications interface of this Notifications API. Notifications are supported by almost all latest browsers.  We will create following files:

  1. index.html: Holds the main web page elements which will initiate notifications.
  2. javascript.js: Which will check if browser supports notifications then trigger notifications at a specific interval.
  3. style.css: Will contain document styles.

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Send Browser Notification from Website - Demo</title>
        <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
        <script type="text/javascript" src="js/javascript.js"></script>
        <link rel="stylesheet" href="css/style.css" />
    </head>
    <body>
        <div class="main-container">
            <div class="section">
                <button type="button" class="btn btn-green show-notification">Show Notification</button>
            </div>
            <div class="popup-chip hide">
                <span class="close" data-dismiss="popup-chip">&times;</span>
                Your browser does not support notifications
            </div>
        </div>
    </body>
</html>

We will set four static notifications in an object and show them every five minutes. We will be using two functions init_notification() and send_notification() and an object variable notifications which will hold the notification settings like notification's title,icon and body. 

The init_notification will be triggered when document is loaded or for demo purpose when show notification button is clicked. This function will check if the browser supports notifications it will request permission to show notifications, Otherwise it will show a popup to user that the browser doesn't support notifications. 

The send_notifications will show the notification after every five minutes and increment the counter which is the pointer of current of notification being displayed from notifications object. We will current notification to display from notifications variable based on counter.

javascript.js

var count = 0;
var icon = "https://3.bp.blogspot.com/-fOCV4rGnTbE/XbqUeDH2IUI/AAAAAAAAAIw/UoDpM8m0LVIM1-GKURDLc_GQZYraOEwRgCK4BGAYYCw/s1600/codestacked-logo.png";
window.addEventListener("load", function () {
// Initiate notification on page load
init_notification();
document.querySelector("span.close").onclick = function () {
this.parentElement.classList.add("hide");
}
document.querySelector(".show-notification").onclick = function () {
// Initiate notification on button click
init_notification();
}
});

// Set notification settings
var notifications = {
0: {
title: "Notification 1",
body: "Notification message body 1",
url: "https://www.codestacked.info"
},
1: {
title: "Notification 2",
body: "Notification message body 2",
url: "https://www.codestacked.info"
},
2: {
title: "Notification 3",
body: "Notification message body 3",
url: "https://www.codestacked.info"
},
3: {
title: "Notification 4",
body: "Notification message body 4",
url: "https://www.codestacked.info"
}
};

// Function to initiate notification
function init_notification() {
// Check if browser allows notificatons
if ("Notification" in window) {
// If notifications are allowed in browser request permission
Notification.requestPermission(function (permission) {
if (permission === "granted") {
// If permission is granted show notification
send_notification(notifications[count]);
}
});
} else {
document.querySelector(".popup-chip").classList.remove("hide");
}
}

// Function to show notification
function send_notification(notification) {
if (Notification.permission === "granted") {
count++;
if (count >= (Object.keys(notifications).length)) {
count = 0;
}
var notes = new Notification(notification.title, {icon: icon, body: notification.body});
notes.onclick = function () {
window.location.assign(notification.url);
}
}
}

// Show notification every five minutes
window.setInterval(function () {
send_notification(notifications[count]);
}, (60000 * 5));

style.css

*{
    box-sizing: border-box;
}
.section{
    padding: 15px;
}
.main-container{
    max-width: 1024px;
    margin: 0px auto;
}
.btn{
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #ddd;
}
.btn-green{
    background: #360;
    color: #fff !important;
}
.popup-chip{
    max-width: 300px;
    background: #222;
    color: #fff;
    padding: 10px;
    box-shadow: 0px 0px 10px rgba(100,100,100,0.5);
    position: fixed;
    bottom: 10px;
    left: calc((100% - 300px)/2);
    text-align: center;
    animation: moveUp .5s;
}
span.close{
    position: absolute;
    top: 2px;
    right: 5px;
    font-size: 20px;
    line-height: 20px;
    cursor: pointer;
}
.hide{
    display: none;
}
@keyframes moveUp{
    from{
        bottom: -50%;
    }
    to{
        bottom: 10px;
    }
}