在html中使用通知
注意事项,必须在网络环境下打开,也就是说需要在服务器下打开,不能双击打开
<html>
<head>
<meta charset="utf-8">
<title>Notification</title>
<meta http-equiv="X-UA-Compatible" content="IE=7">
</head>
<body>
<button id="notifyBtn">show Notification</button>
<script type="text/javascript">
document.getElementById('notifyBtn').onclick = new function()
{
return function()
{
console.log(Notification.Permission);
if(window.Notification &&Notification.permission==='granted')
{
var info = {
lang:'zh-CN', //语言
body:'你有一条信息',//消息简介
tag:'http://www.baidu.com/s?wd=html5+notification', //相当于通知的id,保证信息的唯一性和禁止重复发送
icon:'http://y0.ifengimg.com/2014/11/19/17134118.jpg'//图片
};
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){};
notification.onerror = function(evt){};
notification.onclose = function(evt){};
}
}
}
}
window.onload = function()
{
if (window.Notification &&Notification.permission!='granted')
{
Notification.requestPermission();
}
}
</script>
</body>
</html>
当然,还有另一种比较时尚的写法
if (Notification.permission === "granted") {
var notification = new Notification("Hi there!");
} else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
if(!('permission' in Notification)) {
Notification.permission = permission;
}
if (permission === "granted") {
var notification = new Notification("Hi there!");
}
});
}
输入地址:http://localhost/html5/notification.html
点击之后跳到百度搜索