H5桌面消息通知Notification

H5桌面消息通知Notification

代码很简单,直接复制即可看到效果

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>html5桌面通知</title>
    </head>
    <body>
        <input type="button" value="开启桌面通知" onclick="showDeskTopNotice('通知','HTML5桌面消息');">
        <script>
            function showDeskTopNotice(title,msg){
                var Notification = window.Notification || window.mozNotification || window.webkitNotification;
                if(Notification){
                    Notification.requestPermission(function(status){
                        //status默认值'default'等同于拒绝 'denied' 意味着用户不想要通知 'granted' 意味着用户同意启用通知
                        if("granted" != status){
                            return;
                        }else{
                            var tag = "sds"+Math.random();
                            var notify = new Notification(
                                title,
                                {
                                    dir:'auto',
                                    lang:'zh-CN',
                                    tag:tag,//实例化的notification的id
                                    icon:'https://admin.hms.xin/group1/M00/00/01/rB_YCFsY0OeAX6Q8AAAQvnJ6aNc109.ico',//通知的缩略图,//icon 支持ico、png、jpg、jpeg格式
                                    body:msg //通知的具体内容
                                }
                            );
                            notify.onclick=function(){
                                //如果通知消息被点击,通知窗口将被激活
                                window.focus();
                            },
                            notify.onerror = function () {
                                console.log("HTML5桌面消息出错!!!");
                            };
                            notify.onshow = function () {
                                /*setTimeout(function(){
                                    notify.close();
                                },2000)*/
                            };
                            notify.onclose = function () {
                                console.log("HTML5桌面消息关闭!!!");
                            };
                        }
                    });
                }else{
                    console.log("您的浏览器不支持桌面消息");
                }
            };
        </script>
    </body>
</html>
posted @ 2018-12-20 17:58  leigq  阅读(343)  评论(0编辑  收藏  举报