Hi, I’m Daotin, front end team leader. If you want to get more front end highlights, follow me and unlock new front end growth poses.

The following text:

This article will take about 11 minutes to read.

Sometimes you’ll see something like this in the bottom right corner of your desktop:

This desktop prompt is a new addition to HTML5’s WebPushNotifications technology.

Web Notifications technology enables the page to issue Notifications that are displayed at the system level outside of the page. The ability to provide a better user experience allows users to receive notifications from the page even when they are busy with other tasks, such as a notification of a new email, or a message received in an online chat room, etc.

PS: With the exception of Internet Explorer, every modern browser has basic support for desktop push.

start

To create a message Notification, it is as simple as using the Notification class under the Window object:

var n = new Notification(Desktop Push, {
    icon: 'img/icon.png'.body: 'This is my first desktop notification. '.image:'img/1.jpg'
});
Copy the code

You’ll see a notification pop up on your system desktop with the screenshot I showed above.

PS: Message notification takes effect only when the page is accessed through the Web service. If you double-click the local file directly, it has no effect. This means that your files need to be opened on the server, not in the browser.

It’s also possible that you don’t see anything at all, so don’t worry about reading on.

The basic grammar

Of course, before you want to pop the above notification, it’s worth understanding the basic syntax of a notification:

let myNotification =  new Notification (title, options);
Copy the code

Title: Defines the title of a notification that, when triggered, will appear at the top of the notification window.

The Options (Optional) object contains any custom setting options applied to the notification.

Common options are:

  • Body: The body of the notification, which will appear below the title.

  • Tag: Similar to the ID of each notification so that notifications can be refreshed, replaced, or removed if necessary.

  • Icon: Indicates the notification icon

  • Image: URL of the image displayed in the notification body.

  • Data: Any data that you want to associate with the notification. This can be any data type.

  • Renotify: A Boolean that specifies whether the user should be notified after the new notification replaces the old one. The default is false, which means they are not notified.

  • RequireInteraction: Indicates that the notification should remain valid until the user clicks or closes it, not automatically. The default value is false.

When this code executes, the browser asks the user whether to allow the site to display message notifications, as shown in the following figure:

The notification will only be displayed if the user clicks permit to authorize the notification.

authorization

How do you know if a user clicked “allow” or “block”?

The Notification instance of the window has a requestPermission function to get the authorization status of the user:

// First, we check whether we have permission to display notifications
  // If not, we request permission
  if (window.Notification && Notification.permission ! = ="granted") {
      Notification.requestPermission(function (status) {
      //status Indicates the authorization status.
      // If the user clicks permit, status is 'granted'
      // If the user clicks deny, status is 'denied'

      // This will enable us to use notification. permission in Chrome/Safari
      if (Notification.permission !== status) {
        Notification.permission = status;
      }
    });
  }
Copy the code

Note: If the user clicks the Close button in the upper right corner of the license, the value of Status is default.

After that, we just need to determine whether the status value is GRANTED to display the notification.

Notification event

But simply displaying a message box is not attractive, so the message notification should be interactive, with events before and after the message is displayed.

Notification begins with a set of event functions that developers can use to handle user interactions:

There are: onshow, onclick, onError, onclose.

var n = new Notification(Desktop Push, {
    icon: 'img/icon.png'.body: 'This is my first desktop notification. '
});

// The onshow function fires when the message box is displayed
// You can record some data and close the message box periodically
n.onshow = function() {
    console.log('Show message box');
    // Close the message box after 5 seconds
    setTimeout(function() {
        n.close();
    }, 3000);
};

// The message box is called when it is clicked
// You can open the related view and close the message box
n.onclick = function() {
    console.log('Click message box');
    // Open the relevant view
    n.close();
};

// The onerror function is called when an error occurs
// If granted is not granted, the onError function is also executed when an instance of the Notification object is created
n.onerror = function() {
    console.log('Message box error');
    // Do something else
};

// The onclose function is called when a message box is closed
n.onclose = function() {
    console.log('Close message box');
    // Do something else
};
Copy the code

A simple example

<! DOCTYPEhtml>
<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 request 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 select whether to display notifications
        // Note: Because in Chrome we cannot determine whether the Permission attribute has a value, so
        It is not safe to check if 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 by using a normal-sized alert
            else {
              alert("Hi!"); }}); }// If the user refuses to accept the notification
        else {
          // We can compromise by using constant alert
          alert("Hi!"); }}); });</script>
</html>
Copy the code

When we open the screen, the authorization request will pop up. If we click Permit and then click the button, we can send a notification to the desktop, which we can see in the bottom right corner of the desktop.

Above we just display a message.

if (status === "granted") {
  var n = new Notification("Hi");
}
Copy the code

If we have a lot of messages, let’s say I’m using a for loop to simulate a lot of notifications.

for(var i=0; i<10; i++) {
    var n = new Notification("Hi,"+i);
}
Copy the code

You can see that 10 notifications are displayed. But in some cases, displaying a large number of notifications can be a pain for users.

For example, if an instant messaging application prompts the user for every incoming message. To avoid hundreds of unnecessary notifications covering a user’s desktop, you might want to take over a queue of pending messages. Therefore, you need to add a flag for the newly created notification.

If a new notification has the same token as the previous notification, the new notification will replace the previous notification, and only the latest notification will appear on the desktop.

Add a tag to the notification as in the previous example:

for (var i = 0; i < 10; I++) {// "Hi! Var n = new Notification("Hi! " + i, {tag: 'soManyNotification'}); }Copy the code

The last

Message notification is a good feature, but also does not exclude some sites malicious use of this function, once the user authorization, from time to time push some not very friendly messages, disturb the user’s work, this time we can remove the site’s permissions, disable its message notification function.

We can click on the exclamation mark to the left of the browser address box and have a notification option that allows us to change the authorization. Alternatively, the notification page also has the option to modify the notification, and you can modify the authorization notification according to the specific situation.

The most basic Web Notification is then implemented.


For more exciting content, follow me to get more front-end technology and personal growth related content, I believe interesting people will meet eventually! If you feel helpful, also welcome to like, share, add favorites!