美文网首页
Web Notification桌面消息推送

Web Notification桌面消息推送

作者: 会飞的猪l | 来源:发表于2018-06-04 16:57 被阅读208次

    HTML5特性之Notification桌面消息推送

    兼容Chrome和Firefox

    消息推送会默认需要授权,对一些不安全的网页默认关闭
    主要通过Notification下面的permission属性:permission只读属性

    default 用户没有接收或拒绝授权 不能显示通知
    granted 用户接受授权 允许显示通知
    denied 用户拒绝授权 不允许显示通知
    在浏览器载入的时候就可以判断

    if(window.Notification.permission=="default"){
    
    //如果没有开启,something
    
    }
    

    具体实现代码

    <!DOCTYPE html>  
    <html>  
        <head>  
            <meta charset="UTF-8">  
            <title></title>  
        </head>  
        <script src="js/jquery-1.11.3.js" type="text/javascript" charset="utf-8"></script>
        <body>  
            <button id="showNoti">显示通知</button>
        </body>  
        <script type="text/javascript">  
            $(function () {
                $("#showNoti").click(function () {
                    if (!window.Notification) {
                        alert("浏览器不支持通知!");
                    }
                    console.log(window.Notification.permission);
             if (window.Notification.permission != 'granted') {
                            Notification.requestPermission(function (status) {
                            //status是授权状态,如果用户允许显示桌面通知,则status为'granted'
                            console.log('status: ' + status);
                            //permission只读属性:
                            //  default 用户没有接收或拒绝授权 不能显示通知
                            //  granted 用户接受授权 允许显示通知
                            //  denied  用户拒绝授权 不允许显示通知
                            var permission = Notification.permission;
                            console.log('permission: ' + permission);
                        });
                    }
                    var n = new Notification("您有一条消息!", { "icon": "", "body": "您一分钟后将有好运气" }); 
                    n.onshow = function () { 
                        console.log("显示通知"); 
                        setTimeout(function () { n.close() }, 3000); };
                            n.onclick = function () { alert("打开相关视图"); 
                        window.open("/Home/about"); n.close();
                        };
                    n.onclose = function () { console.log("通知关闭"); };
                    n.onerror = function () { console.log('产生错误');   }; 
                });
            });
    </script>  
    
    </html>
    
    image.png

    相关文章

      网友评论

          本文标题:Web Notification桌面消息推送

          本文链接:https://www.haomeiwen.com/subject/lxeysftx.html