Web Notifications for New HTML5 Features

Original address: http://blog.csdn.net/liuhe688/article/details/41971215

Today, let's talk about desktop notifications, the Web Notifications technology.

Web Notifications are HTML5 One of the exciting new features is that it allows developers to configure and display desktop notifications to provide users with a better experience. Most commendably, even when users are busy with other tasks, they can receive notifications from pages, such as a new email alert, or a message alert received in an online chat room, etc.

Next, we try to create our own notifications step by step.

To create a message notification, we first need to create a message box, which is very simple. Just use the Notification class under the window object directly. The code is as follows:

  1. var n = new Notification("sir, you got a message", {  
  2.     icon: 'img/icon.png',  
  3.     body: 'you will have a meeting 5 minutes later.'  
  4. });  

In the constructor of Notification class, there are two important parameters: the first is the title of the message, and the second is the body object, which includes the icon of the message box and the body of the message.

After executing the above code, we succeeded in creating an instance of a message box that will eventually appear under Chrome as follows:


Half of our success has been achieved here, but whether this message box can be displayed correctly depends ultimately on the user's authorization. In view of the browser's security mechanism, only when the user agrees that the message notification box pops up on the web page, can the message notification really be displayed. So now all we have to do is apply for user authorization.

The Notification class provides a requestPermission method to request user authorization, which is coded as follows:

  1. Notification.requestPermission(function(status) {  
  2.     //Status is the authorization status, and if the user is allowed to display desktop notifications, status is'granted'  
  3.     console.log('status: ' + status);  
  4.   
  5.     //permission read-only property  
  6.     var permission = Notification.permission;  
  7.     //default. Users cannot display notifications without receiving or rejecting authorization requests  
  8.     //granted. User accepts authorization request and allows display notification  
  9.     //Users refuse authorization requests and are not allowed to display notifications  
  10.   
  11.     console.log('permission: ' + permission);  
  12. });  

When this code is executed, the browser asks the user if the site is allowed to display message notifications, as shown in the following figure:


If the user clicks the Block button on the left, no matter how we create the Notification instance, the message will never be displayed; only when the user chooses the Allow button can the code execute correctly and the message box be displayed.

As described in the code above, after the request Permission function is executed, it enters a callback function, which can pass a status parameter to indicate the final authorization status after the user has made a choice. If the user clicks the closing button on the right side of the authorization prompt, it is equivalent to ignoring the authorization request, when status is default, the message cannot be displayed in the default state; if the user clicks the Block button to reject the authorization request, status will be denied state, which is naturally unable to display the message; if the user clicks the Allow button to accept the authorization request, then status will change. In the granted state, the message can be displayed correctly only in the granted state.

At the same time, after the authorization request is executed, the browser assigns the permission status to the permission attribute of Notification, which is read-only for developers and has the same value as the status value mentioned above. So if we want to display a message notification, we can first determine whether we have permissions:

  1. if (Notification.permission === 'granted') {  
  2.     //show notification  
  3. }  

As described above, when the permission is granted, we can display the message notification. But simply displaying a message box is not attractive, so the message notification should be interactive, and events should be involved before and after displaying the message. Notification started with a series of event functions that developers can use to handle user interactions in a very specific way:

  1. var n = new Notification("sir, you got a message", {  
  2.     icon: 'img/icon.png',  
  3.     body: 'you will have a meeting 5 minutes later.'  
  4. });  
  5.   
  6. //onshow function is called when the message box is displayed  
  7. //Can do some data recording and timing operations, etc.  
  8. n.onshow = function() {  
  9.     console.log('notification shows up');  
  10.     //Close the message box in 5 seconds  
  11.     setTimeout(function() {  
  12.         n.close();  
  13.     }, 5000);  
  14. };  
  15.   
  16. //Message box is called when clicked  
  17. //You can open the relevant view and close the message box, etc.  
  18. n.onclick = function() {  
  19.     alert('open the associated view');  
  20.     //opening the view...  
  21.     n.close();  
  22. };  
  23.   
  24. //The onerror function is called when an error occurs  
  25. //If there is no granted authorization, the onerror function is also executed when an instance of Notification object is created.  
  26. n.onerror = function() {  
  27.     console.log('notification encounters an error');  
  28.     //do something useful  
  29. };  
  30.   
  31. //The onclose function is called when a message box closes  
  32. n.onclose = function() {  
  33.     console.log('notification is closed');  
  34.     //do something useful  
  35. };  
As we can see, Notification has four commonly used functions to handle event interaction, onshow function can be executed when the message is displayed, onclick function can be called after the user clicks on the message, onclose function is called when the message box is closed, onerror function is called when an error occurs, as mentioned above, if not authorized, continue to create a message pass. Knowing, the onerror function is also executed. After mastering the application of these functions, we can basically deal with message events very well.

Finally, we will organize these steps to form a simple example to better demonstrate this new feature.

First, create the following file structure:


Then we need to organize the code of the above steps into one JavaScript Object, as shown in the following code:

  1. var NotificationHandler = {  
  2.     isNotificationSupported: 'Notification' in window,  
  3.     isPermissionGranted: function() {  
  4.         return Notification.permission === 'granted';  
  5.     },  
  6.     requestPermission: function() {  
  7.         if (!this.isNotificationSupported) {  
  8.             console.log('the current browser does not support Notification API');  
  9.             return;  
  10.         }  
  11.   
  12.         Notification.requestPermission(function(status) {  
  13.             //Status is the authorization status, and if the user is allowed to display desktop notifications, status is'granted'  
  14.             console.log('status: ' + status);  
  15.   
  16.             //permission read-only property  
  17.             var permission = Notification.permission;  
  18.             //default. User does not receive or refuse authorization. Notification cannot be displayed  
  19.             //Grand User Accepts Authorization and Allows Display Notification  
  20.             //User Denies Authorization No Display Notification  
  21.   
  22.             console.log('permission: ' + permission);  
  23.         });  
  24.     },  
  25.     showNotification: function() {  
  26.         if (!this.isNotificationSupported) {  
  27.             console.log('the current browser does not support Notification API');  
  28.             return;  
  29.         }  
  30.         if (!this.isPermissionGranted()) {  
  31.             console.log('the current page has not been granted for notification');  
  32.             return;  
  33.         }  
  34.   
  35.         var n = new Notification("sir, you got a message", {  
  36.             icon: 'img/icon.png',  
  37.             body: 'you will have a meeting 5 minutes later.'  
  38.         });  
  39.   
  40.         //onshow function is called when the message box is displayed  
  41.         //Can do some data recording and timing operations, etc.  
  42.         n.onshow = function() {  
  43.             console.log('notification shows up');  
  44.             //Close the message box in 5 seconds  
  45.             setTimeout(function() {  
  46.                 n.close();  
  47.             }, 5000);  
  48.         };  
  49.   
  50.         //Message box is called when clicked  
  51.         //You can open the relevant view and close the message box, etc.  
  52.         n.onclick = function() {  
  53.             alert('open the associated view');  
  54.             //opening the view...  
  55.             n.close();  
  56.         };  
  57.   
  58.         //The onerror function is called when an error occurs  
  59.         //If there is no granted authorization, the onerror function is also executed when an instance of Notification object is created.  
  60.         n.onerror = function() {  
  61.             console.log('notification encounters an error');  
  62.             //do something useful  
  63.         };  
  64.   
  65.         //The onclose function is called when a message box closes  
  66.         n.onclose = function() {  
  67.             console.log('notification is closed');  
  68.             //do something useful  
  69.         };  
  70.     }  
  71. };  
  72.   
  73. document.addEventListener('load'function() {  
  74.     //try to request permission when page has been loaded.  
  75.     NotificationHandler.requestPermission();  
  76. });  

As we can see, the above code creates an object of Notification Handler to manage the event logic associated with the message. Usually our process is as follows: after the page is loaded, we call the request Permission function to request user authorization, and then after the page code is executed for a period of time, when a message needs to be displayed, we call the showNotification function to display the message. For example:

  1. setTimeout(function() {  
  2.     //if there has new mail, show notification  
  3.     NotificationHandler.showNotification();  
  4. }, 5000);  
Note that not all browsers support Notification, so we added an isNotification Supported attribute to identify whether message notification is supported by browsers. In the above code, if the browser does not support this API, it will return directly. Of course, in actual development, we can choose other forms to do it. Wake up users.

Then let's look at the index.html file:

  1. <!DOCTYPE html>  
  2. <html>  
  3.     <body>  
  4.         <button onclick="NotificationHandler.showNotification()">show notification</button>  
  5.     </body>  
  6.     <script type="text/javascript" src="js/main.js"></script>  
  7. </html>  
This document is extremely simple and straightforward, so there is no need to say more. Finally, let's take a look at the actual effect.

1. Click the button, pop up the message, then close it directly, or wait for 5 seconds, the console will print the following message:

2. Click on the button, pop up the message, and then click on the content of the message, the pop-up box will pop up:

It looks good. In the actual development, the application may be more complex, but as long as you understand the basic mode of operation, everything will become simple.

Finally, it should be noted that the message notification takes effect only when the page is accessed through a Web service, and that if you double-click to open the local file directly, it has no effect. So when you do exercises in normal times, you also need to put the file directory into the Web container, remember.

Message notification is a good feature, but it also does not rule out that some sites maliciously use this function. Once the user authorizes, from time to time push some unfriendly messages to disturb the work of the user. At this time, we can remove the site's authority and disable its message notification function. We can click the Settings tab to open the settings in turn, then click on the display advanced settings at the bottom, click on the content settings in the privacy item, and finally pop up a content panel, slide down to find a message to inform one, how to change, it is presumably needless to say more.

Speaking of this, the basic application of message notification is almost covered. I hope you can understand it carefully. Finally, you can apply this new feature to the actual project, which will certainly add a lot of color.

Keywords: Javascript Attribute html5

Added by herrin on Sun, 09 Jun 2019 00:45:37 +0300