wang-steven
5/8/2015 - 3:07 AM

HTML5 web notification on desktop

HTML5 web notification on desktop

<html>
    <head></head>
    <body>
        <button>Show Desktop Notification</button>

        <script type="text/javascript">
            var btn = document.querySelector('button');
            var notifications = window.Notification;

            if (notifications) {
                btn.addEventListener('click', showMsg, false);
            } else {
                console.log('Desktop Notification does not support.');
            }

            function showMsg() {
                if (notifications.permission === 'granted') {
                    var demo = new Notification('Title', {
                        body: 'Hello'
                    });
                    demo.onshow = function() {
                        console.log('The notification is showed');
                        setTimeout(function() {
                            demo.close();
                        }, 10000);
                    };
                    demo.onclick = function() {
                        console.log('You click the notification');
                        window.focus();
                    };
                    demo.onclose = function() {};
                    demo.onerror = function() {};
                } else {
                    notifications.requestPermission();
                }
            }
        </script>
    </body>
</html>