Notification is a new API in HTML5 for configuring and displaying desktop notifications to users. Last time I saw other people’s notification popup on other websites, I was curious to know how to achieve it. In fact, it is not complicated, and can be said to be relatively simple, so I write a blog to share with you, hoping to help you understand this API.

NPM package:

I also sent a NPM package: Notification-Koro1. It is very lightweight and simple. If you like it, click Star

Under the chromeNotificationPerformance:

  1. Google, for example, initially required users to allow notifications:

  1. When notifications are allowed, the display will look like this:

Notificationfeatures

  1. The notification is browser-free and even if the user does not stay on the current TAB or even minimizes the browser, the notification will appear in the upper right corner of the home screen and then disappear after a certain period of time.

  2. We can listen for notifications to display, click, close, etc., such as clicking on a notification to open a page.

Blog, front-end accumulation of documents, public number, GitHub

Chestnut: Go to the console inside each website to run

The details of the API will come later, but first try this API

Here is a simple example of how Notification works by running it on the console of each website:

var options = {
  dir: "auto".// Text direction
  body: "Notice: OBKoro1 has commented on your moments.".// The notification body
  requireInteraction: true.// Notifications are not automatically turned off
  // Notification icon
  icon: "https://upload-images.jianshu.io/upload_images/5245297-818e624b75271127.jpg?imageMogr2/auto-orient/strip%7CimageView2/2 /w/1240"
};
notifyMe('This is the title of the notice.', options);
function notifyMe(title, options) {
  // Check whether the browser supports it
  if (!window.Notification) {
    console.log('Browser does not support notifications');
  } else {
    // Check whether the user has ever agreed to be notified
    if (Notification.permission === 'granted') {
      var notification = new Notification(title, options); // Display notifications
    } else if (Notification.permission === 'default') {
      // If the user has not selected it, the user can be asked if they agree to send the notification
      Notification.requestPermission().then(permission= > {
        if (permission === 'granted') {
          console.log('User agrees to authorize');
          var notification = new Notification(title, options); // Display notifications
        } else if (permission === 'default') {
          console.warn('Users can request authorization again before turning off authorization and refreshing the page');
        } else {
          // denied
          console.log('User refused authorization cannot display notification'); }}); }else {
      // denied user denied
      console.log('User has refused to display notifications'); }}}Copy the code

Browser support:

MDN: Currently, all browsers support desktop Notification except Internet Explorer. Mobile browsers do not support desktop Notification.

Before using Notification, we need to check whether the browser supports the Notification API:

if(window.Notification){
  // Desktop notification logic
}
Copy the code

Notification Permission:

To prevent sites from abusing notifications, users need to give their consent before displaying them.

Permission is used to indicate the authorization status of the current Notification display. It has three values:

  1. default: Default value. The user has not selected it
  2. granted: Users allow the site to send notifications
  3. denied: The user refused to send notifications to the site

Detection permission:

After checking whether the browser supports Notification, you need to check the user Notification permissions.

  if (Notification.permission === 'granted') {
    console.log('User has agreed to license');
     // Notifications can be displayed at any time
  } else if (Notification.permission === 'default') {
    console.log('User has not chosen to agree/reject');
    // Next request user authorization
  } else {
    console.log('User refused authorization cannot display notification');
  }
Copy the code

Request permission to

When Notification. Permission for the default, we need to use the Notification. The requestPermission () to request user permissions.

Notification. RequestPermission () based on the promise of grammar, then the callback function parameter is the state of the user permissions Notification. The value of the permission.

Notification.requestPermission().then(permission= > {
  if (permission === 'granted') {
    console.log('User agrees to authorize');
     // Notifications can be displayed at any time
  } else if (permission === 'default') {
    console.log('User closes authorization can request authorization again');
  } else {
    console.log('User refused authorization cannot display notification'); }});/ / the old version is using a callback function mechanism: Notification. RequestPermission (the callback); Parameters are the same
Copy the code

Push notification

When notification. permission is granted, notifications can be sent at any time, in any form, rather than immediately after the user’s permission is requested.

const options = {}; // Null configuration
const title = 'Here's the title.';
const notification = new Notification(title, options) // Display notifications
Copy the code

This code will display a simple notification if the user allows you to pop up.

NotificationThe parameters of the:

  • Title: The title of the notification
  • Options: notification Settings (optional).
    • Body: string. The body content of the notification.
    • Tag: Indicates the identification tag of the notification. For the same tag, only one notification window is opened.
    • Icon: string. The URL of the icon to display in the notification.
    • Data: The data that you want to associate with a notification can be found in thenew NotificationIs found in the returned instance.
    • Renotify: indicates a Boolean value. If the same tag appears, whether to replace the previous one (if this is enabled, the tag must be set).
    • RequireInteraction: Boolean value. Notifications do not turn off automatically and default to false(auto turn off).
    • Some of the less important configurations can be seen in Zhang Xinxu’s blog and MDN’s introduction

RequireInteraction: Keep notifications off automatically

The default value is false, and notifications are automatically turned off after three or four seconds.

When set to true and there are more than two notifications (new Notification(title, options)), the Notification overlay state shown below appears.

In this case, of course, we can only default to the last notification, unless you save the instance returned by each notification.

The NPM package I released, notification-koro1, can be customized to automatically turn off notifications that are not automatically turned off at certain intervals, or to turn off all notifications at once

PS: If stacking is not triggered, it is probably because you have the same tag configuration item for both notifications (only one popover for the same tag).

PS: Safari does not support this option and is automatically disabled by default

The same renotify:

The default value is false. In chorme, notifications with the same tag will not be replaced

If set to true, two notifications with the same tag will replace the previous notification.

Note: To use renotify, you must also set the tag option, otherwise an error will be reported.

PS: Safari does not support this option. By default, two notifications with the same tag are sent. The new notification replaces the old one.

NotificationExamples:

Generates a notification that returns an instance like this:

const instanceNotification = new Notification(title, options)
Copy the code

InstanceNotification is an instance of the current notification, on which you can query the configuration of the notification, listen for events, and call instance methods.

Examples of notifications returned are referred to in instanceNotification below.

Notification configuration:

On the notification instance you can read all the configuration when setting the notification, such as:

Notification title: instanceNotification. Title, notification content: instanceNotification. Body, notification icon: instanceNotification.

PS: These attributes are read-only and cannot be deleted, modified, or traversed.

Event handling:

We can use an instance of a notification to listen for notification events:

  • click: Triggered when the user clicks the notification
  • show: Triggered when the notification is displayed
  • error: Notification is triggered when an error is encountered
  • close: Triggered when the user disables notification
instanceNotification.onclick = e= > {
  // Do something can be: open a url, send a request, close a notification, etc
}
Copy the code

Note: It is best to listen for events as soon as notifications are issued, otherwise some events may not be triggered in the first place or may never be triggered.

For example, if the timer is used to monitor the click and display event of the notification after 5 seconds, the callback of the notification display will never be triggered. The click event can work normally after 5 seconds, but it will error the user’s click before 5 seconds.

Close to inform

instanceNotification.close()
Copy the code

Without this option, Chrome notifications will automatically turn off notifications in about 4.5 seconds and Safari in 5 seconds (you can’t turn off notifications automatically).

Notification does not have the function to periodically control how long a notification will disappear. When multiple notifications occur, they cannot be closed uniformly.

Both of these issues are addressed in the NPM package I released, Notification-Koro1, and provide clearer callbacks

Application scenarios

  • Instant messaging software (email, chat room)
  • Sporting event results Lottery/raffle results
  • News website major news notice
  • Major updates to the website, major news, etc.

Notification of other

Here are some API/ browser details and the problems you might encounter, so you can skip them and come back to them when you do.

User refuses to display notification:

Once the user disables the site from displaying notifications, the site can no longer request permission to display notifications, requiring the user to change the notification in Settings.

In Chrome, choose Settings > Advanced > Content Settings > Notification

Saafari Browser: Preferences > Sites > Notifications > Find Sites > Modify Permissions/Restore Defaults

To disable request permissions:

In The Chrome browser: When the user closes the request permission popup (the cross in the upper right corner), the page is not refreshed, we can ask the user for permission again. After the page is refreshed, the default browser user rejects it.

In Safari, there is no option to turn off the request permission, and the user must choose to agree or refuse.

Icon does not display the problem:

Github is not the image below the domain name, so an error will be reported and cannot be called.

Tag:

  1. tagOnly one notification can appear at the same time. Whether the old notification will be overwritten depends on:renotifyConfiguration and browser.
  2. In Chrome: After the notification is disabled, the tag that appeared last time cannot appear again for a period of time, such as refreshing the page and requesting the notification with the same tag. (Normal in Safari)

Icon cannot be displayed under Safari

Under Safari, with the same site (Google, for example) and the same code, Chrome can display icon normally, but Safari has no icon and no error.

Google later found that on Stack Overflow safari only supports the body and tag options and does not support the icon option.

Continuous trigger

When notifications are triggered consecutively for short periods of time (no tag, no requireInteraction) in Safari and Chrome, the following behavior occurs:

This representation, without icon, title, or content, would be meaningless, and the browser would restrict the developer from constantly disturbing the user.

Notification – Koro1:

Check out Notification-Koro1 for continuous maintenance


conclusion

This article is written in detail, you can first mark, and then really use this API, you can first through the chestnuts in the article, and then find the corresponding content.

The other thing is to pay attention to the differences between browsers. I tried Chrome and Safari myself, and there are a lot of differences in implementation details between the two browsers, so pay attention when developing them.

I hope the friends can click like/follow, your support is the biggest encouragement to me.

Blog, front-end accumulation of documents, public number, GitHub

The above 2019.02.17

References:

notification-Koro1

Learn about Web Notification desktop notifications in HTML5

Notification MDN

HTML5 Desktop Notification: Notification API