HTML5 Notification通知的使用

在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

163701_G4Bm_2256215.png

点击之后跳到百度搜索

转载于:https://my.oschina.net/ososchina/blog/346854

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值