当我们的网站收到一条新消息的时候,需要能通知给正在访问网页的人员
浏览器打开的情况下,可以展示在电脑桌面右下角
//浏览器桌面通知
function notify(title, options, callback) {// 先检查浏览器是否支持if (!window.Notification) {console.log("浏览器不支持notify");return;}options.body=replaceHtml(options.body);console.log("浏览器notify权限:", Notification.permission);// 检查用户曾经是否同意接受通知if (Notification.permission === 'granted') {var notification = new Notification(title, options); // 显示通知if (notification && callback) {notification.onclick = function(event) {callback(notification, event);}setTimeout(function () {notification.close();},3000);}} else {Notification.requestPermission().then( (permission) =>function(){console.log("请求浏览器notify权限:", permission);if (permission === 'granted') {notification = new Notification(title, options); // 显示通知if (notification && callback) {notification.onclick = function (event) {callback(notification, event);}setTimeout(function () {notification.close();}, 3000);}} else if (permission === 'default') {console.log('用户关闭授权 可以再次请求授权');} else {console.log('用户拒绝授权 不能显示通知');}});}}
并且同时可以响起声音提醒访客
//播放声音
function alertSound(id,src){var b = document.getElementById(id);if(src){b.src=src;}var p = b.play();p && p.then(function(){}).catch(function(e){console.log(e,b.src);});
}
以上两个函数是主要功能,还需要配合下面的调用方法
因为我是在vue下使用的,如没用vue可以酌情修改
html部分
<audio id="chatMessageAudio" style="display: none;" :src="require('@/assets/alert2.ogg')"></audio>
调用方法,tools是我的库名,酌情修改
//声音通知tools.alertSound("chatMessageAudio");//桌面通知tools.notify(msg.name, {body: msg.content,icon: msg.avator},function(notification) {window.focus();notification.close();});
标题闪动
var flashing = false;function flashTitle() {if (flashing) {return;}flashing = true;var originalTitle = document.title;var intervalId;var newTitle = "🔥✉️" + originalTitle;function changeTitle() {document.title = document.title == originalTitle ? newTitle : originalTitle;}intervalId = setInterval(changeTitle, 1000);window.onfocus = function () {clearInterval(intervalId);document.title = originalTitle;flashing = false;};
}