官网API说明:
https://developer.mozilla.org/en-US/docs/Web/API/notification
/*1、弹窗样式由浏览器决定,无法自定义
唯一破局方式:html生成图片,以图片方式插入
2、结合WebSocket实现后台对前台的消息推送
3、代码实例*/
/**
* 消息弹出
* @param data:用户数据
* @returns {*}
*/
function notifyMe(data) {
if (!data || !reqPermit4Notify()) {
return;
}
var data = JSON.parse(data);
var iconUrl = "/project/images/pic1.png";
var title = "Title";//标题
var options = {
body: "Content",//内容
lang: 'zh-CN',
dir: "ltr",//方向,从左向右
tag: data.tag,//多个标签页同时打开,会弹出多个相同内容弹窗,仅当各弹窗tag相同时,仅弹出一个
renotify: false,//复用弹窗
icon: iconUrl,
// image: imageUrl,
data: {
url: "www.baidu.com"
},
requireInteraction: true,//持续显示
// timestamp:"",指定时间推送
// vibrate: [200, 100, 200],震动模式
};
var notify = new Notification(title, options);
notify.onerror = function (event) {
console.log("Notification Error");
};
notify.onshow = function (event) {
console.log("Notification Show");
};
notify.ondisplay = function (event) {
console.log("Notification Display");
};
notify.onclick = function (event) {
console.log("Notification Click");
window.open(this.data.url, '_blank');
this.close();
};
notify.onclose = function (event) {
console.log("Notification Close");
};
return notify;
}
/**
* 请求浏览器弹出授权
*/
function reqPermit4Notify() {
if (!("Notification" in window)) {//浏览器支持
console.log("Browser not supported Html5 Notification");
return false;
}
if (Notification.permission == "denied") {//用户禁用
console.log("User refused to show Html5 Notification");
return false;
}
if (Notification.permission != "granted") {//用户未授权
Notification.requestPermission(function (permission) {
if (permission != 'granted') {
console.log("User forbit the Html5 Notification");
return false;
}
return true;
});
}
return true;
}