美文网首页
浏览器消息通知(Notification)

浏览器消息通知(Notification)

作者: 此人已失联好几天 | 来源:发表于2020-04-17 16:46 被阅读0次

Notification对象

        function NotificationComm(title, option){
            // 判断浏览器是否兼容Notification消息通知
            if('Notification' in window){
                // 获取用户是否允许通知权限
                window.Notification.requestPermission(function(res){
                    // 允许
                    if(res === 'granted'){
                        var notification = new Notification(title || '这是一条新消息', Object.assign({}, {
                            dir: "auto", // 字体排版,auto,lt,rt
                            icon: '', // 通知图标
                            body: '请尽快处理该消息', // 主体内容
                            renotify: false // 当有新消息提示时,是否一直关闭上一条提示
                        }, option || {}));
                        // error事件处理函数
                        notification.onerror = function(err){
                            throw err;
                        }
                        // show事件处理函数
                        notification.onshow = function(ev){
                            console.log(ev);
                        }
                        // click事件处理函数
                        notification.onclick = function(ev){
                            console.log(ev);
                            notification.close();
                        }
                        // close事件处理函数
                        notification.onclose = function(ev){
                            console.log(ev);
                        }
                    } else {
                        alert('已不允许消息通知');
                    }
                });
            } else {
                // 兼容当前浏览器不支持Notification的情况
                var documentTitle = document.title,
                    index = 0;
                var time = setInterval(function(){
                    index++;
                    if(index % 2){
                        document.title = '【   】' + documentTitle;
                    } else {
                        document.title = '【新消息】' + documentTitle;
                    }
                }, 1000);
                var fn = function(){
                    if(!document.hidden && document.visibilityState === 'visible'){
                        clearInterval(time);
                        document.title = documentTitle;
                    }
                }
                fn();
                document.addEventListener('visibilitychange', fn, false);
            }
        }
        // 启用消息通知
        NotificationComm('hello word!!', { body: '新消息呀新消息' });
桌面提示

相关文章

网友评论

      本文标题:浏览器消息通知(Notification)

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