Sometimes we will see this prompt in the lower right corner of the desktop:
This desktop prompt is the new Web Push Notifications technology of HTML5.
Web Notifications technology enables pages to issue notifications that will be displayed at a system level outside of the page. It can provide users with a better experience, and they can receive message notifications from the page even when they are busy with other tasks, such as a reminder of a new email, or a message reminder received in an online chat room, etc.
PS: In addition to IE, all major modern browsers have basic support for this desktop push.
start
To create a message notification, it is very simple. Just use the Notification class under the window object. The code is as follows:
var n = new Notification(Desktop push, { icon: 'img/icon.png', body: 'This is my first desktop notification.', image:'img/1.jpg'});
Then you will see the notification of the screenshot I took above pop up on the system desktop.
PS: The message notification will only take effect when the page is accessed through the Web service. If you directly double-click to open a local file, it will have no effect. That is to say, your file needs to be opened on the server instead of directly using the browser to open the local file.
Of course, it's possible that you don't see anything, so don't worry and continue reading.
basic grammarOf course, before you want to pop up the above notification, it is necessary to understand the basic syntax of a notification:
let myNotification = new Notification(title, options);
title: Defines a title for the notification that will be displayed at the top of the notification window when it is triggered.
The options (optional) object contains any custom setting options that apply to the notification.
Commonly used options are:body: The body of the notification, which will be displayed below the title.
tag: Similar to the ID of each notification so that the notification can be refreshed, replaced or removed when necessary.
icon: icon to display notifications
image: The URL of the image to display in the notification body.
data: Any data you want associated with the notification. This can be any data type.
renotify: A Boolean that specifies whether the user should be notified after a new notification replaces an old one. The default value is false, which means they will not be notified.
requireInteraction: indicates that the notification should remain active until the user clicks or closes it, rather than closing automatically. The default value is false.
When this code is executed, the browser will ask the user whether to allow the site to display message notifications, as shown in the following figure:
Notifications will be displayed only if the user clicks Allow and authorizes notifications.
AuthorizeHow to get whether the user clicks allow or block?
The Notification instance of window has a requestPermission function to obtain the user's authorization status:
// First, we check if we have permission to display notifications // If not, we apply for permission if (window.Notification && Notification.permission !== granted) { Notification.requestPermission(function (status) { //status is the authorization status . //If the user clicks Allow, the status is 'granted' // If the user clicks Disable, the status is 'denied' // This will allow us to use Notification.permission if in Chrome/Safari (Notification.permission !== status) { Notification.permission = status; } }); }
Note: If the user clicks the close button in the upper right corner of the authorization, the value of status is default.
After that, we only need to determine whether the value of status is granted to decide whether to display the notification.
notification eventBut simply displaying a message box is unattractive, so message notifications should have a certain degree of interactivity, and events should be involved before and after displaying the message.
Notification has formulated a series of event functions from the beginning. Developers can use these functions to handle user interactions in a comprehensive way:
There are: onshow, onclick, onerror, onclose.
var n = new Notification(Desktop push, { icon: 'img/icon.png', body: 'This is my first desktop notification.'}); //onshow function is triggered when the message box is displayed // OK Do some data recording and close the message box regularly n.onshow = function() { console.log('Display message box'); //Close the message box after 5 seconds setTimeout(function() { n.close(); } , 3000);};//Called when the message box is clicked //You can open the relevant view, close the message box and other operations at the same time n.onclick = function() { console.log('Click the message box'); // Open the relevant view n.close();};//When an error occurs, the onerror function will be called //If there is no granted authorization, the onerror function will also be executed when creating a Notification object instance n.onerror = function() { console.log('Message box error'); // Do other things}; // The onclose function will be called when a message box is closed n.onclose = function() { console.log('Close the message box') ; //Do something else};
a simple example
<!DOCTYPE html><html lang=en> <head> <meta charset=UTF-8 /> <title>Document</title> </head> <body> <button>Click to initiate notification</button> </ body> <script> window.addEventListener(load, function() { // First, let's check if we have permission to send notifications // If not, we ask for permission if (window.Notification && Notification.permission !== granted) { Notification.requestPermission(function(status) { if (Notification.permission !== status) { Notification.permission = status; } }); } var button = document.getElementsByTagName(button)[0]; button.addEventListener(click, function() { // Create a notification if the user agrees if (window.Notification && Notification.permission === granted) { var n = new Notification(Hi!); } // If the user does not choose whether to display notifications // Note: Because in Chrome we cannot determine whether the permission attribute has a value, it is unsafe to // check whether the value of this attribute is default else. if (window.Notification && Notification.permission !== denied) { Notification.requestPermission(function(status) { if (Notification.permission !== status) { Notification.permission = status; } // If the user agrees if (status === granted) { var n = new Notification(Hi!); } // Otherwise, we can compromise and use the regular mode alert else { alert(Hi!); } }); } // If the user refuses to accept the notification else { // We can compromise and use the regular mode alert alert(Hi!); } }); }); </script></html>
When we open the interface, an authorization application will pop up. If we click Allow and then click the button, a notification will be sent to the desktop, and we can see this notification in the lower right corner of the desktop.
Above we just display a message.
if (status === granted) { var n = new Notification(Hi);}
If we have a lot of messages, for example, I use a for loop to simulate a large number of notifications.
for(var i=0; i<10; i++) { var n = new Notification(Hi,+i);}
You can see that 10 notifications are displayed. But in some cases, displaying a large number of notifications can be painful for users.
For example, if an instant messaging app prompts the user for every incoming message. To avoid flooding a user's desktop with hundreds of unnecessary notifications, it may be necessary to take over a queue of pending messages.
Therefore, a tag needs to be added to the newly created notification.
If there is a new notification with the same tag as the previous notification, the new notification will replace the previous notification, and only the latest notification will be displayed on the desktop.
Still using the above example, you only need to add a tag attribute to the trigger notification:
for (var i = 0; i < 10; i++) { // Finally, only the notification with content Hi! 9 will be seen var n = new Notification(Hi! + i, {tag: 'soManyNotification'});}at last
Message notification is a good feature, but it does not rule out that some sites use this function maliciously. Once the user authorizes it, they will push some unfriendly messages from time to time and disturb the user's work. At this time, we can remove the site's permissions. Disable its message notification feature.
We can click the exclamation mark on the left side of the browser address input box and there will be a notification option, and we can modify the authorization. Or there is an option to modify the notification on the notification page, and you can modify the authorization notification according to the specific situation.
So the most basic Web Notification is implemented.
SummarizeThe above is the implementation method of the Web Notification desktop notification function in HTML5 introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank everyone for your support of the VeVb martial arts website!
If you think this article is helpful to you, you are welcome to reprint it, please indicate the source, thank you!