【英文】JS向操作系统发送通知

Preface

Sending notifications to the operating system using JS

Request Permission for Notifications

  • Request authorization through the browser to allow sending system notifications

permission: Result after requesting

default: User has not taken any action
granted: User allows access to system notifications
denied: User prohibits access to system notifications

1
const permission = await Notification.requestPermission();

Sending Notifications

  • Create a notification object and immediately send the notification
1
const notification = new Notification("Notification Message Title");

Sending Additional Information with Notifications

body: Body of the notification message
icon: Icon of the notification
data: Data stored in the notification object, can store data of any type

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

Defining Whether the Notification Should Persist

requireInteraction: Whether the notification should persist

false: Default value, disappears automatically after 4 seconds
true: Notification persists until manually closed

1
2
3
const notification = new Notification("Notification Message Title", {
requireInteraction: true,
});

Defining the Notification Tag

tag: Defines the tag of the notification, notifications with the same tag will not be repeated

1
2
3
const notification = new Notification("Notification Message Title", {
tag: ""
});

Notification tag not defined

Notification tag defined

Conclusion

References

Bilibili- Qiuqiu’s Frontend Tea House