在做websocket的时候有新消息推送需要一个闪烁功能,于是找到了下面这个原生写法,感觉可以用,先抄下来再封装一下。

在非当前页面的时候提示“您有新消息”功能的js:
// 窗体失焦的时候,标题就会闪。
// 这里有一个小的知识点,就是浏览器窗体获得焦点和失去焦点,Chrome和FireFox浏览器是window的onfocus, onblur方法;而IE浏览器则是document的onfocusin, onfocusout方法,因此有:
var titleInit = document.title, isShine = true;
setInterval(function() {
var title = document.title;
if (isShine == true) {
if (/新/.test(title) == false) {
document.title = '【你有新消息】';
} else {
document.title = '【 】';
}
} else {
document.title = titleInit;
}
}, 500);
// for Chrome and FireFox
window.onfocus = function() {
console.log(123);
isShine = false;
};
window.onblur = function() {
isShine = true;
};
// for IE
document.onfocusin = function() {
isShine = false;
};
document.onfocusout = function() {
isShine = true;
};桌面消息通证版:
suportNotify()
//判断浏览器是否支持Web Notifications API
function suportNotify(){
if (window.Notification) {
// 支持
console.log("支持"+"Web Notifications API");
//如果支持Web Notifications API,再判断浏览器是否支持弹出实例
showMess()
} else {
// 不支持
alert("不支持 Web Notifications API");
}
}
//判断浏览器是否支持弹出实例
function showMess(){
setTimeout(function () {
console.log('1:'+Notification.permission);
//如果支持window.Notification 并且 许可不是拒绝状态
if(window.Notification && Notification.permission !== "denied") {
//Notification.requestPermission这是一个静态方法,作用就是让浏览器出现是否允许通知的提示
Notification.requestPermission(function(status) {
console.log('2: '+status);
//如果状态是同意
if (status === "granted") {
var m = new Notification('收到信息', {
body: '这里是通知内容!你想看什么客官?', //消息体内容
icon:"images/img1.jpg" //消息图片
});
m.onclick = function () {
//点击当前消息提示框后,跳转到当前页面
window.focus();
}
} else{
alert('当前浏览器不支持弹出消息')
}
});
}else {
}
},1000);
}