Categories

HTML5 Desktop Notifications

Posted on: June 4, 2016 by Dimitar Ivanov

Web notifications

Thanks to HTML5 specification modern browsers are able to display desktop notifications. If you ever have seen such a popup, that is because user-agent asks for permission to display web notifications from current domain.

Web notification request permission

Granting permission the domain for notifications, allows the website to display notifications, that looks like this:

Web notification

The icon at the bottom right corner of the notification, allows you to manage the notification exceptions.

Notifications exceptions

In Chrome, navigate to Settings » Privacy » Content settings... » Notifications » Manage exceptions...

Notification API

  • How to check whether notifications are supported:
    if ('Notification' in window) {
    
    }
    
  • To find out the current permission to display notifications, use the permission static property. Possible values are: granted, denied and default.
    if (Notification.permission !== 'denied') {
    
    }
    
  • How to ask for permission:
    Notification.requestPermission(function (permission) {
        if (permission === 'granted') {
            // create notification
        }
    });
    
  • How to create notification:
    var note = new Notification('Hooray!', {
        icon: 'https://example.com/notification-icon.png',
        body: 'Lorem ipsum dolor sit amet.'
    });
    
  • The notification object supports onclick and onerror event handlers.
    note.onclick = function(e) {
        e.preventDefault();
        window.open('https://zinoui.com', '_blank');
    }
    
  • How to close notification:
    note.close();
    

Browser Compatibility

Edge 14+, Firefox 22+, Chrome 22+, Safari 6+, Opera 25+

Conclusion

Web notifications are great addition to the web platform and could be used practically anywhere. That makes them extremely useful.

See also
References
Share this post

If you have any questions or toughts about the HTML5 Desktop Notifications, leave a comment below. Ah, don't forget to share this article.


2 Comments

Matthew
Can I use web notifications in an async way?
Dimitar Ivanov
Dimitar Ivanov July 3, 2016 at 05:13 am
@Matthew actually, the Web Notification API supports Promises through his requestPermission method:

Notification.requestPermission().then(function(permission) {
if (permission === 'granted') {
// create notification
}
});

Leave a comment

Captcha