网站在线客服系统新消息提醒功能,支持浏览器桌面通知提醒,网页新消息声音,标题闪动效果功能实现
分类:vue
当我们的网站收到一条新消息的时候,需要能通知给正在访问网页的人员
浏览器打开的情况下,可以展示在电脑桌面右下角
//浏览器桌面通知
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;
};
}

一线大厂高级前端编写,前端初中阶面试题,帮助初学者应聘,需要联系微信:javadudu