初次尝试web浏览器消息通知,并震动提示

 

注意的是,本地测试服务是完全可以看到消息通知的,如果线上环境,必须要求https协议,否则自动视为拒绝。

通知API可能不再从不安全的来源使用。您应该考虑将应用程序切换到安全源,比如HTTPS。见https://goo.gl/rStTGz了解更多细节。

 

js代码:

;(function(window){

    var _notification = function(){
        if(Notification){
            return Notification;
        }
        else if(navigator.webkitNotifications){
            return navigator.webkitNotifications;
        }
        else if(navigator.mozNotification){
            navigator.mozNotification.createNotification
        }
        else{
            return null;
        }
    }
    
    var requestPermission = function(notification){
        //console.log(notification)
        notification.requestPermission().then(function(permission) { 
    
            
            if (permission === 'denied') {
                alert('您已拒绝消息通知,可能会影响到您的用户体验哦!');
                return;
            }
            if (permission === 'default') {
                alert('请选择允许消息通知,否则可能会影响到您的用户体验哦!');
                return;
            }
    
            // Do something with the granted permission.
            var NoticeFun = function(){ }
            NoticeFun.prototype.show = function(options){
                try{
                    window.navigator.vibrate([200, 100, 200]);
                }finally{
                    return new notification(options.title, options);
                }
            }
    
            var $notice = function(options){
                return new NoticeFun(options);
            }
    
            window.$notice = $notice();
            
    
        });
    }
    
    var notif = _notification();
    if(notif){
        requestPermission(notif);
    }

})(window);

 

html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    消息通知测试,提示时尝试震动提示。
    
    <script src="./js/worker.js"></script>
    <script>

        setTimeout(function(){
            console.log(window.$notice)
            if(window.$notice){
                var not = window.$notice.show({
                    icon: "http://img0.imgtn.bdimg.com/it/u=188877350,2916594130&fm=26&gp=0.jpg",
                    title: "订单通知",
                    body: "您的订单已被接单,请点击前往查看!"
                })
                not.onclick = function(){
                    alert();
                }
            }
        }, 3000)

        setTimeout(function(){
            console.log(window.$notice)
            if(window.$notice){
                var not = window.$notice.show({
                    title: "支付通知",
                    body: "您的订单支付已成功!"
                })
                not.onclick = function(){
                    alert();
                }
            }
        }, 5000)

    </script>
</body>
</html>

效果如下:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章