Notifications API 允许网页或应用程序在系统级别发送在页面外部显示的通知;这样即使应用程序空闲或在后台,Web应用程序也会向用户发送信息。
可以在MDN文档查看:https://developer.mozilla.org/zh-CN/docs/Web/API/notification/Using_Web_Notifications
一、实例代码
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
function testnotification(){
var notification = new Notification("how are you", {
dir: 'ltr',
body: 'Test web Notification API',
tag: 'test',
icon: 'https://timgsa.baidu.com/timg?
image&quality=80&size=b9999_10000&sec=1591963791675&di=78915703b3b62722aa3d822f7b156f5b&imgt
ype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages
%2F20180827%2F9b015779123143f18362556b1a02061a.jpeg'
});
notification.onclick = function(e) {
console.log( e);
console.log('点击通知时被触发');
this.close();
}
notification.onshow = function() {
console.log('通知显示的时候被触发');
}
notification.onerror = function() {
console.log('当通知遇到错误时被触发');
}
notification.onclose = function() {
console.log('用户关闭通知时被触发');
}
}
function run() {
if ('Notification' in window) {
// 查看是否有权限
if (Notification.permission == 'granted') {
testnotification();
} else if(Notification.permission == 'denied' || Notification.permission == 'default') {
// 主动提出需要权限
Notification.requestPermission(permission => {
if (permission == 'granted') {
testnotification();
}
})
}
}
}
</script>
</head>
<body>
<button onclick="run()">Notify me!</button>
</body>
</html>
二、属性
`dir`是一个只读属性,它表示Notification中显示的文本方向
auto: 继承浏览器的语言设置里制定的方向 (默认)
ltr:从左到右
rtl : 从右到左
属性body内容主体了
属性icon图标,一张图片的URL
属性tag标签标明是否为同一通知
三、兼容性问题
Chrome 、Edge、Firefox、Opera、Safari等浏览器在不同版本中都开始支持 IE不支持
不同浏览器上支持略有差异
HTML5 Desktop Notifications是一个小型开源库,可以在不同的浏览器中统一HTML5 Notifications API
Github:https://github.com/ttsvetko/HTML5-Desktop-Notifications
因为IE的限制可以试一试另一个开源插件(在IE11上试过可以的)
Github:http://ie-web-notifications.github.io/开源代码:https://github.com/ie-web-notifications/ie-web-notifications