logo

桌面通知 - Notification API

Notification API 是 HTML5 中用于推送桌面通知的 API,通过这个 API 我们就可以向用户推送消息,拓展了 Web 应用的功能,从后台及时向用户推送桌面信息。
兼容性信息:

虽然兼容性不怎么样,但是对于支持的 API 用户可以渐进增强我们的应用。

详细信息可参考Notifications API Live Standard

Notification API

构造方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
new Nofication(title, {
/*通知推送方向*/
dir: "auto|ltr|rtl",
/*通知语言*/
lang: "zh|en|...",
/*推送的消息*//
body: "i miss you",
/*附带的数据*/
data: { info: "123" },
/*震动设备震动,停止震动时间的数组,震动与停止交替,
比如这里震动100ms,停止150ms,震动120ms*/
vibrate: [100, 150, 120],
/*这条通知的标识,相同的Tag会被认为是同一条消息*/
tag: "notifi233",
/*默认为false,表示通知信息堆叠起来
设置为true,表示相同通知标识(tag),会被替换而不是堆叠
因此设置为true必须同时设置tag标识*/
renotify: false,
/*展示图片的url*/
icon: "https://placehold.it/100x100",
/*默认false,是否需要交互才隐藏,分为自动隐藏,用户点击隐藏。*/
requireInteraction: false,
/*是否有通知音效,默认false,标识静音*/
slient: false
});

属性

静态属性

  • Notification.permission(read only),只读属性表示是否获取了推送桌面通知的权限,’denied|granted|default’,其中default与denied行为相同。

实例属性

  • Notification.prototype.title/dir/body/tag/icon…,实例化 Notificaiton option 中设置的属性。
  • Notifcation.prototype.onclick,点击通知事件
  • Notifcation.prototype.onshow,通知显示事件
  • Notifcation.prototype.onerror,通知错误事件
  • Notifcation.prototype.onclose,通知关闭事件

方法

静态方法

Notification.requestPermission(status=>{}) 向用户请求通知权限。

实例方法

  • Notification.prototype.close() 关闭通知
  • Notification.prototype.addEventLisener/removeEventLisener/dispatchEvent 注册/移除/触发事件方法。

写个试试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function notify() {
if (Notification) {
if (Notification.permission !== 'granted') {
//请求权限回调
Notification.requestPermission(st=>console.log(st));
} else {
let msg = new Notification('weiwei', {
dir: 'auto',
body: 'i miss you',
data: { info: 'i miss you too' },
vibrate: [100,100,100],
tag: 'msg1',
renotify:false,
icon: "https://placehold.it/100x100",
requireInteraction: true,
slient:false
});
['click','show','error','close'].forEach(eventName=>{
msg.addEventListener(eventName,(e)=>{
console.log(e.type)
if(e.type === 'click'){
//点击跳转网页
window.open('https://www.baidu.com')
}
})
});
//定时通知关闭
// setTimeout(()=>{
// msg.close()
// },3000)
}
} else {
alert('浏览器不支持Notification')
}
}

以上代码在PC上测试可以正常工作,虽然can i use中有部分浏览器支持,但是如在Android Chorme浏览器中确会报错(Failed to construct Notification: Illegal constructor),由于系统机制的原因废弃了这个API,因此在移动端Notification API就不要想了。,
具体issues
摘要:
new Notification() is on the path to deprecation, because it implicitly assumes that the page will outlive the notification, which is very unlikely on mobile (and far from guaranteed on desktop too).
Hence we will never implement it on Android. We might one day remove it on desktop too, after a deprecation period.
Websites should use ServiceWorkerRegistration.showNotification() (see spec) instead whenever it is available.
The best way I can think of to feature-detect new Notification() is to try it (before you have permission) and catch the error:

1
2
3
4
5
6
7
8
9
10
11
12
13
function isNewNotificationSupported() {
if (!window.Notification || !Notification.requestPermission)
return false;
if (Notification.permission == 'granted')
throw new Error('You must only call this *before* calling Notification.requestPermission(), otherwise this feature detect would bug the user with an actual notification!');
try {
new Notification('');
} catch (e) {
if (e.name == 'TypeError')
return false;
}
return true;
}

You could then use it like this:

1
2
3
4
5
6
7
8
if (window.Notification && Notification.permission == 'granted') {
// We would only have prompted the user for permission if new
// Notification was supported (see below), so assume it is supported.
doStuffThatUsesNewNotification();
} else if (isNewNotificationSupported()) {
// new Notification is supported, so prompt the user for permission.
showOptInUIForNotifications();
}

这里还有一个服务器结合Web Push推送桌面消息的文章[向网络应用添加推送通知],(https://developers.google.com/web/fundamentals/codelabs/push-notifications/)

参考链接

Notificaiton-MDN
简单了解 HTML5 中的 Web Notification 桌面通知