【笔记】JS向操作系统发送通知

前言

JS向操作系统发送通知

请求允许通知

  • 通过浏览器请求授权允许发送系统通知

permission:请求后的结果

default:用户没有操作
granted:用户允许访问系统通知
denied:用户禁止访问系统通知

1
const permission = await Notification.requestPermission();

发送通知

  • 创建通知对象并立即发送通知
1
const notification = new Notification("通知消息标题");

发送通知时携带消息其他信息

body:消息通知正文
icon:消息通知的图标
data:消息通知对象存储的数据,可以存储任意数据类型的数据

1
2
3
4
5
const notification = new Notification("通知消息标题", {
body: "",
icon: "https://loli.fj.cn/dist/images/apple-touch-icon.png",
data: "",
});

定义通知是否保持常驻

requireInteraction:通知是否保持常驻

false:缺省值,4秒自动消失
true:通知保持常驻,除非手动关闭

1
2
3
const notification = new Notification("通知消息标题", {
requireInteraction: true,
});

定义通知标签

tag:定义通知的标签,标签值相同的通知不会反复出现

1
2
3
const notification = new Notification("通知消息标题", {
tag: ""
});

没有定义通知标签

定义了通知标签

完成

参考文献

哔哩哔哩——球球的前端奶茶屋