首页  编辑  

HTML5 网页通知功能 Notification

Tags: /计算机文档/网页制作/   Date Created:
HTML5网页通知功能JS函数:
使用方法:
showNotification("新消息", "收到了 5 条新消息!", "/favicon.ico");

function showNotification(title, message, ico) {
	var ability = window.Notification || window.mozNotification || window.webkitNotification;
	var canNotify = false;
	if (ability) {
		if(Notification.permission === 'granted'){
			canNotify = true;
		}else if(Notification.permission === 'denied'){
			console.log('用户拒绝通知');
		}else{
			Notification.requestPermission().then(function(permission) {
				canNotify = permission === 'granted';
			});
		}

		if (canNotify && !document.hasFocus()) {
			var notice = new Notification(title, {body: message, icon: ico});
			notice.onclick = function() {
				window.focus();
				notice.close();
			};
			setTimeout(function() { notice.close();}, 10 * 1000);
		}
	} else {
		var change = false;
		var oldTitle = document.title;
		var timer = setInterval(function(){
			change = !change;
			document.title = change ? title : message;
		}, 500);
		setTimeout(function() {clearInterval(timer); document.title=oldTitle;}, 10 * 1000);
	}
}