html5的消息通知

这里介绍一个HTML5的notification demo:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>notification</title>
    </head>
    <body>
        <button id="button">消息通知</button>
        <script>
            // var button = document.getElementById('#button');
            var button = document.querySelector('#button'); //上面那样写不可以
            button.addEventListener('click', function() {
                if (!("Notification" in window)) {
                    alert("不支持notification");
                } else if (Notification.permission === "granted") { // 允许通知
                    notice();
                } else if (Notification.permission !== "denied") {
                    // 用户没有选择是否显示通知,向用户请求许可
                    Notification.requestPermission(function(permission) {
                        if(permission === "granted") {
                            notice();
                        }
                    });
                }
            }, false)

            function notice() {
                var notification = new Notification("你好,JavaScript", {
                    body: '微信订阅号'
                });
                notification.onclick = function() {
                    notification.close();
                }
            }
        </script>
    </body>
</html>

将该demo部属在nginx上(详见上一篇随笔),在谷歌浏览器(支持HTML5 notification的浏览器就可以)中打开页面,会看到pc端右下角弹出消息通知。

posted on 2017-04-08 21:33  萌动  阅读(214)  评论(0编辑  收藏  举报