When developing a web application system or a website, when the user triggers an event, or the system wants to notify the user of an event, such as a new message, other people like or comment on the article, the system process has been approved In such scenarios, you may usually think of the in- app notification method, but this method has a limitation, that is, if the user switches to other tabs in the browser or other applications, they may not be able to see the notification of the application system in time. Then you can use the browser's Notification notification function at this time.
1. What is the browser's Notification ?
Notification is a browser-provided mechanism that allows web pages to display system notifications to the user outside of the top-level browsing context viewport, so even if the user has switched tabs or moved to a different application , and Notification -related APIs are designed to be compatible with existing notification systems on different platforms.
First, let's take a look at what the browser's Notification notification looks like. Take the SegmentFault website as an example. As long as a new user follows or an article is liked and collected, the SegmentFault website will automatically send a Notification notification (the premise of seeing the notification is to allow it The website sends a notice), the specific notice is as follows:
In addition to the SegmentFault website, you can also look at the system notifications of the web version of WeChat, which is similar.
2. How to use Notification ?
To display a system notification, it generally needs to be divided into two steps: the user grants the permission to display the notification , and the system notification is sent .
(1) User grants permission to display notifications
The system needs to send a notification to the user. If the user does not want to view the notification, that is, the corresponding permission is not granted, then even if the notification is sent, the user cannot see it.
How do I ask the user for permission to view system notifications? You can use the following method
Notification.requestPermission()
There are three return values for this method: granted , denied , default . The latest specification has updated this method to a promise-based syntax, which works as follows:
Notification.requestPermission().then(function(permission) { ... });
Let's take a look at a specific example, ask the permission to display system notifications on localhost, and print the corresponding log information according to different selection results. The code is as follows:
Notification.requestPermission().then(function(result) {
if (result === 'denied') {
console.log('拒绝显示系统通知');
return;
}
if (result === 'default') {
console.log('默认');
return;
}
console.log('允许显示系统通知')
});
Press F12 to open Chrome's console and copy the code above
After running, you can see that the browser will pop up a query box, as follows:
Different choices, the console will output different results
- Allow : The console will output Allow system notifications to be displayed . If Allow is selected, when the permission is requested again, the selection box will not pop up, but the console will directly output Allow system notifications to be displayed;
- Forbidden : The console will output Deny to display system notifications . If Deny is selected, when requesting permission again, the selection box will not pop up, but the console will directly output Deny to display system notifications;;
- x is closed : the console will output the default , if it is closed directly, when the permission is requested again, the selection box will still pop up;
After selecting [Allow], click the information button in the address bar at this time, and you can see that the notification has been turned on, as follows:
If you don't want to display the notification, you can close the notification directly here, or you can use the following statement to view the authorization status of the current user, as follows:
Notification.permission
After running, output the result
'granted'
(2) Send system notifications
When the user allows the system notification to be displayed, the notification can be sent. At this time, a new notification can be created using the Notification() constructor. This method can pass in two parameters, as follows:
title (required)
- Defines the title of a notification that will be displayed at the top of the notification window when it is fired.
options (optional)
The options object contains any custom settings options applied to the notification, commonly used options are:
-
dir
: 文字的方向;它的值可以是auto(自动)
,ltr(从左到右)
, orrtl
(从右到左); -
lang
: Specifies the language used in the notification. This string must be valid in the BCP 47 language tag document; -
body
: the additional string displayed in the notification; -
tag
: Give the notification an ID so that the notification can be refreshed, replaced or removed when necessary; -
icon
: The URL of an image that will be used to display the notification icon;
In addition to the above 5 common options, there are other badge , image , data , vibrate , renotify , requireInteraction , etc. For details, please refer to the introduction of the official website https://developer.mozilla.org/zh-CN/docs/Web/ API/notification/Notification
Let's test a simple notification, the code is as follows:
let notification = new Notification('有一条新通知');
This notification has only the title, after running, you can see
Add some options options and test the system notification again. The modified code is as follows:
let notification = new Notification('有一条新通知', {
dir: 'ltr',
lang: 'zh-CN',
body: '通知的正文内容:你的请假流程已批准',
icon: 'http://localhost/coder/favicon.ico'
});
After running, you can see the notification as follows
(3) Notification of events
Notification notification has four kinds of events. You can perform different operations by listening to the notification event. The specific events are as follows:
- Notification.onclick : The processing of the click event, which is triggered whenever the user clicks on the notification;
- Notification.onshow : The processing of the show event, which is triggered when the notification is displayed;
- Notification.onerror : The processing of the error event, triggered whenever the notification encounters an error;
- Notification.onclose : The handler for the close event, which is fired when the user closes the notification.
Let's test the monitoring of the notification event, the code is as follows:
let notification = new Notification('有一条新通知', {
dir: 'ltr',
lang: 'zh-CN',
body: '通知的正文内容:你的请假流程已批准',
icon: 'http://localhost/coder/favicon.ico'
});
// 监听通知显示事件
notification.onshow = () => console.log('通知已显示');
// 监听通知点击事件
notification.onclick = () => console.log('通知被点击');
// 监听通知被关闭事件
notification.onclose = () => console.log('通知被关闭');
// 监听通知错误事件
notification.onerror = () => console.log('通知出现错误');
When running, the console will directly output the following information
通知已显示
When the notification is clicked, it will output
通知被点击
When the notification is closed, it will output
通知被关闭
3. Send Notification notification code
Combined with the above introduction, the reference code for sending notifications is given below, as follows:
function sendNotification(title, body, icon, callback) {
// 先检查浏览器是否支持
if (!('Notification' in window)) {
// IE浏览器不支持发送Notification通知!
return;
}
if (Notification.permission === 'denied') {
// 如果用户已拒绝显示通知
return;
}
if (Notification.permission === 'granted') {
//用户已授权,直接发送通知
notify();
} else {
// 默认,先向用户询问是否允许显示通知
Notification.requestPermission(function(permission) {
// 如果用户同意,就可以直接发送通知
if (permission === 'granted') {
notify();
}
});
}
function notify() {
let notification = new Notification(title, {
icon: icon,
body: body
});
notification.onclick = function() {
callback && callback();
console.log('单击通知框')
}
notification.onclose = function() {
console.log('关闭通知框');
};
}
}
Let's test it out:
sendNotification('下班通知', '今天周五,还有十分钟下班', 'http://localhost/coder/favicon.ico');
After running, the effect of the notification is as follows:
References:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。