代码如下
<html>
<head>
<meta charset="utf-8">
<title>David Notification</title>
</head>
<body>
<button id="notifyBtn">show Notification</button>
</body>
<script type="text/javascript">
document.getElementById('notifyBtn').onclick = function(){
console.log(Notification.permission);
if(window.Notification && Notification.permission==='granted'){
var info = {
lang:'zh-CN', //语言
body:'你有一条信息',//消息简介
tag:'222on4'+new Date().getTime(), //相当于通知的id,保证信息的唯一性和禁止重复发送
//icon:''//图片
};
var notification = new Notification('Notification Center',info);
if(!!notification){
notification.onclick = function(evt){
var e = evt || window.event;
window.location.href = e.currentTarget.tag;
};
notification.onshow = function(evt){
console.log("show",evt);
};
notification.onerror = function(evt){
console.log("error",evt);
};
notification.onclose = function(evt){
console.log("close",evt);
};
}
}
}
window.onload = function(){
if (window.Notification && Notification.permission!='granted'){
Notification.requestPermission();//申请授权
}
}
</script>
</html>
注意事项
1、如果不显示,注意下windows通知设置,右下角消息->右击->专注助手->关闭
2、浏览器兼容情况如下: