HTML5 Desktop Notifications Example

Share this article

G’day mate. So today I did a quick demo to show you an example of desktop notifications using HTML5
and a little JavaScript. View Project on GitHub html5-desktop-notification

Background info on HTML5 Desktop Alerts

A notification allows alerting the user outside the context of a web page of an occurrence, such as the delivery of email.

You can display, queue and replace notifications. You can also add an icon to the alert which appears left of the message body. Also also you can use the tag member for multiple instances (The result of this situation is a single notification; the second one replaces the first having the same tag). Read more about the W3C Web Notifications API.

From my testing only 4 alerts show at any one time, they get queued so when you close one the next one will show and so on. Also you cannot put hyperlinks in them (which would be nice to have). This is what the desktop alert looks like. desktop-alert And like most features like this for security reasons you’re prompted for access. allow-deny 4alerts

The Script

The script is pretty simple it just uses the webkitNotifications to generate a desktop alert with a title and message.
/*
   @Copyright: jQuery4u 2012
   @Author: Sam Deering
   @Script: html5desktopalert.js
*/
(function($,W,D,undefined)
{
    W.JQUERY4U = W.JQUERY4U || {};

    W.JQUERY4U.HTML5DESKTOPALERT = {

        name: "jQuery HTML5 DESKTOP ALERT",

        namespace: "W.JQUERY4U.HTML5DESKTOPALERT",

        settings:
        {
           //turn into plugin? ...
        },

        cache:
        {
            //runtime data, dom elements etc...
        },

        init: function(settings)
        {
            this.settings = $.extend({}, this.settings, settings);
            this.cache.notifications = window.webkitNotifications;
            this.testBrowserSupport();
            this.setupEventHandlers();
        },

        setupEventHandlers: function()
        {
           var _this = this;
           $('#alert-me-btn').bind('click', function(e)
           {
               _this.checkPermission("desktopAlert");
           });
        },

        //tests HTML5 browser support and permission request
        testBrowserSupport: function()
        {
            var $browserMsg = $('#browser-support-msg');
            if(this.cache.notifications)
            {
                $browserMsg.html("Yay! Notifications are supported on this browser.").parent().addClass('alert-success');
            }
            else
            {
                $browserMsg.html("Sorry. Notifications aren't supported on this browser.").parent().addClass('alert-error');
            }
        },

        checkPermission: function(callback)
        {
            var _this = this;
            if (this.cache.notifications.checkPermission() == 0)
            {
                _this[callback]();
            }
            else
            {
                this.cache.notifications.requestPermission(function()
                {
                    if (this.cache.notifications.checkPermission() == 0) _this[callback]();
                });
            }
        },

        desktopAlert: function()
        {
            console.log('sending alert...');
            var notification = window.webkitNotifications.createNotification("", $('#da-title').val(), $('#da-message').val());
            notification.show();
        }
    }

    $(D).ready( function()
    {
        //start up the form events
        W.JQUERY4U.HTML5DESKTOPALERT.init();
    });


})(jQuery,window,document);

Frequently Asked Questions (FAQs) about HTML5 Desktop Notifications

How can I request permission for HTML5 desktop notifications?

To request permission for HTML5 desktop notifications, you need to use the Notification.requestPermission() method. This method prompts the user to allow or block notifications from your webpage. It’s important to note that this method should be triggered by a user action, such as clicking a button, to avoid being blocked by browsers that disallow permission requests not initiated by user interactions.

Can I customize the appearance of HTML5 desktop notifications?

Yes, you can customize the appearance of HTML5 desktop notifications. You can set the title, body text, icon, and even the vibration pattern for mobile devices. However, the level of customization may vary depending on the browser and the operating system.

Are HTML5 desktop notifications supported by all browsers?

No, not all browsers support HTML5 desktop notifications. Most modern browsers like Chrome, Firefox, and Safari do support them, but Internet Explorer does not. It’s always a good idea to check the compatibility of the feature with different browsers.

How can I close an HTML5 desktop notification?

You can close an HTML5 desktop notification programmatically by calling the close() method on the Notification instance. Alternatively, most desktop notifications will have a close button that the user can click.

Can I send HTML5 desktop notifications when the browser is not active?

Yes, you can send HTML5 desktop notifications even when the browser is not active or minimized. However, this requires the use of Service Workers and the Push API, which are more advanced topics.

How can I handle click events on HTML5 desktop notifications?

You can handle click events on HTML5 desktop notifications by adding an event listener for the ‘click’ event on the Notification instance. Inside the event handler, you can define what should happen when the notification is clicked.

Can I use HTML5 desktop notifications in a mobile browser?

Yes, you can use HTML5 desktop notifications in a mobile browser. However, the behavior and appearance of the notifications may vary depending on the operating system and the browser.

Are there any limitations or restrictions on using HTML5 desktop notifications?

Yes, there are some limitations and restrictions on using HTML5 desktop notifications. For example, the user must grant permission for your webpage to show notifications. Also, some browsers may limit the frequency of notifications to prevent spamming.

Can I use HTML5 desktop notifications in a web worker?

Yes, you can use HTML5 desktop notifications in a web worker. However, you need to use the self.registration.showNotification() method instead of the Notification constructor.

How can I check if the user has granted permission for HTML5 desktop notifications?

You can check if the user has granted permission for HTML5 desktop notifications by checking the value of Notification.permission. If it’s ‘granted’, then the user has given permission. If it’s ‘denied’, then the user has blocked notifications. If it’s ‘default’, then the user has not made a choice yet.

Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

jQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week