Wednesday 28 September 2016

Desktop Notification for Web Application

Creating desktop nofications is really easy. We are going to use the Notification API of the browser to create the desktop notifications.
Before creating the notification its better to check whether the Notification API is supported in the browser.
To check the notification is supported simply check the typeof the Notification Object
        if(typeof Notification !== 'undefined'){
            // Create the notification
        } 
    
Once the Notification is exist, then its necessary to ask the permission from the user, only if the permission is granted we can able to create the notification. To get the permission from the user.
        Notification.requestPermission();
    
After the user grants permission, we can able to create the notification.
        if(Notification.permission == 'granted'){
            // Create notification
        }
    
To create the notification, create the instance of the Notification with the title and required options, here we are going to give the body of the notification with the icon
        var title = "Notification";
            var options = {
                body: "Notification Content",
                icon: "icon url"
            };
        var notification = new Notification(title, options);
    
To close the notification, you can call the close method of the Notification.
        notification.close();
    
To close the notification after some given time, say 5 seconds.
        setTimeout(notification.close(), 5000);
    
We can create a click listerner for the notification.
        notification.onclick = function(){
            console.log("notification clicked");
        }
    

No comments:

Post a Comment