How To Implement Notification In Html5 Web Application

This article will tell you how to implement web browser notification in the Html5 web application, then when your website user browses your website page, your website can send notifications to the client user instead of an alert dialog. This is more user-friendly and elegant.

1. What Is Web Browser Notification.

  1. The browser notification is a popup dialog that has a title, body, icon, etc, it is more beautiful than the alert dialog.
  2. Before it can be shown when you browse a website page, the website must obtain your grant permission to allow it to show the notification to you.
  3. It will pop up a small dialog ( at the beginning of the web browser address bar ) to let you choose whether Allow or Block the notifications.
  4. If you click the Allow button, then the website can send notifications to you, if you click the Block button, then the website can not send notifications to you.
  5. The notification dialog always is shown on the bottom right corner of the web browser ( when you use the browser on Windows, macOS, Linux .etc).

2. How To Process Notification In Html5 Web Application.

  1. How to check whether your web browser supports notifications or not? You can use the below source code.
     /* W3C Specification */
    if( "Notification" in window || window.Notificatiom){
    
    
    }
    
    /* old WebKit Browsers */
    if( window.webkitNotifications ){
    
    }
    
    /* Firefox for Android and Firefox OS */
    if( navigator.mozNotification ){
    
    }
  2. How to check whether you have granted the website send notification permission or not? You can use the Notification.permission property’s value.
    The Notification.permission property may return 3 string value.
    
    'default': means you have not configured the notification permission.
    
    'granted': you have allowed the website to create notification.
    
    'denied': you have denied the website to create notification.
  3. How to request the user to allow or deny the website to send notifications? You can use the Notification.requestPermission() method.
    // the promise based version.
    Notification.requestPermission().then((permission) => {           
        ......
    });
    
    
    // the callback function version.
    Notification.requestPermission(function(permission) {
       ......
    });
  4. How to create & send a notification in Html5? You can create an instance of the Notification class, and provide the notification’s title, body, tag, and icon values.
    var notificationObject = {tag: tagVal, body: textVal, icon: imgVal};
    
    var notification = new Notification(titleVal, notificationObject);
  5. If you send multiple notifications ( that do not specify the tag value or specify different tag values ) then all those notifications will popup one above one, this may spam the client user.
  6. To fix this issue, you need to provide the same tag value to the multiple notifications, then the later notification will override the former notification, you will only see one notification dialog.
  7. To send the notification, you should upload the HTML file to a real HTTPS web server that enables the SSL.
  8. How to close the notification programmatically? You can call the Notification object’s close() method to close it.
  9. The Notification object supports the below events, such as click, error, close, and show events. You can define the process function ( onclick, onerror, onclose, onshow ) to handle the events.

3. How To Implement Notification In Html5 Web Application Example.

  1. This example only has one source file html5-notification-example.html.
  2. If you want to run it, you should upload the file to a real HTTPS web server otherwise the notification dialog will not pop up as expected.
  3. There are 5 buttons on the web page.
  4. Click the button Support Notification? will show a text message on the web page, the text will tell you whether your web browser support notification or not, the text message is like below.
    Your web browser support notification, browser info is Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36
  5. Click the button Notification Enabled? will show a text message to show whether you have granted, denied, or not-configured the notification permission to the website.
    You have denied the notification permission to this website, the website can not send notification to you.
  6. Click the button Request Notification Permission? will show the Show notifications dialog (which has a small bell ) at the beginning of the web browser address bar to let you choose Allow or Block the website notifications. After your selection, it will pop up an alert dialog to tell your selection.
  7. Click the button Send Notifications will send a notification every one second, you can see the popup dialog on the bottom right corner of the web browser.
  8. Click the button Close All Notifications will close all the popup notifications.
  9. Below is the html5-notification-example.html source code.
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>Html5 Notification Example</title>
    <script type="text/javascript">
    
    var messageDiv;
    
    var browserInfo;
    
    var notificationPermission;
    
    var notificationArray = new Array();
    
    function init(){
    
        messageDiv = document.getElementById('message');
    
        browserInfo = navigator.userAgent;
    }
    
    function isBrowserSupportNotification(){
    
        var browserInfo = navigator.userAgent;
    
        var message = '';
    
        if("Notification" in window || window.Notification || window.webkitNotifications || navigator.mozNotification){
    
            message = 'Your web browser support notification, browser info is ' +  browserInfo;
        }else{
    
            message = 'Your web browser do not support notification, browser info is ' +  browserInfo;
        }
    
        messageDiv.innerHTML = message;
    
    }
    
    function isNotificationEnabled(){
    
        var message = '';
    
        var permission = Notification.permission;
    
        //alert(permission);
    
        if('default' == permission){
    
            message = 'You have not enable or disable the notification permission to this website, so the website can not send notification to you.';
        }else if('granted' == permission){
    
            message = 'You have granted the notification permission to this website, the website can send notification to you.';
        }else if('denied' == permission){
    
            message = 'You have denied the notification permission to this website, the website can not send notification to you.';
        }
    
        messageDiv.innerHTML = message;
    }
    
    
    function requestNotificationPermission(){
    
        var message = '';
    
        var permission = Notification.permission;
    
        try {
    
            // if the server support the promise version.
            Notification.requestPermission().then((permission) => {
               
                processNotificationPermission(permission);
            });
    
        } catch(e) {
            
            console.log('Error occurred while request notification permission.');
    
            console.log(e);
    
            // for some web browser that do not support the promise version, you need to use the below callback function to grant or deny notification permission.
            Notification.requestPermission(function(permission) {
    
                processNotificationPermission(permission);
            
            });
        }
    
        messageDiv.innerHTML = message;
    }
    
    
    function processNotificationPermission(permission)
    {
    
        // save the notification permission in a global variable.
        notificationPermission = permission;
    
        if (permission === "granted") {
        
            alert("You have granted the notificaiton permission, you can send notification now.");   
        }
        else {
            alert("Hello, you denied the notification permission request.");
        }    
    
    }
    
    
    // This function will be invoked by the 'Send Notifications' button.
    function sendNotifications(){
    
        var i = 0;
    
        // send multiple notifications every 1 second.
        var interval = window.setInterval(function () {
        
            sendOneNotification('Hello Notification-' + i, 'This is a notification from the page.', '', 'tag1');
        
            i++;
    
            if (i == 3) {
    
                window.clearInterval(interval);
    
            }
    
        }, 1000); 
    }
    
    
    
    function sendOneNotification(titleVal, textVal, imgVal, tagVal){
    
        var notificationObject = {tag: tagVal, body: textVal, icon: imgVal};
    
        var notification = new Notification(titleVal, notificationObject);
    
        notification.onclick = function(event){
    
            alert('The notification is clicked. Notification title is : ' + notification.title);
        }
    
        notification.onerror = function(event){
    
            alert('The notification meet an error. Notification title is : ' + notification.title);
        }
    
        notification.onclose = function(event){
    
            alert('The notification is closed. Notification title is : ' + notification.title);
        }
    
        notification.onshow = function(event){
    
            alert('The notification will be shown. Notification title is : ' + notification.title);
        }
    
    
        notificationArray.push(notification);
    
    }
    
    
    function closeAllNotifications(){
    
        var len = notificationArray.length;
    
        for(var i=0;i < len; i++){
    
            notificationArray[i].close();
        }
    }
    
    </script>
    
    
    <style>
        .block{
            display:block; 
            margin: 10px;
        }
    </style>
    </head>
    <body onload="init()">
    <h3>Html5 Notification Example.</h3>
    <div id="message" class="block"></div>
    <button onclick="isBrowserSupportNotification()">Support Notification?</button>
    <button onclick="isNotificationEnabled()">Notification Enabled?</button>
    <button onclick="requestNotificationPermission()">Request Notification Permission?</button>
    <button onclick="sendNotifications()">Send Notifications</button>
    <button onclick="closeAllNotifications()">Close All Notifications</button>
    </body>
    </html>
  10. Below is this example demo video.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Clicky