Home > Web Front-end > JS Tutorial > Displaying Dynamic Messages Using the Web Notification API

Displaying Dynamic Messages Using the Web Notification API

Jennifer Aniston
Release: 2025-02-17 13:06:09
Original
535 people have browsed it

Web Notifications API: Make website notifications out of browser restrictions

We are used to mobile notifications from favorite websites or applications, but now it is becoming more common for browsers to push notifications directly. For example, Facebook will send notifications when you have a new friend request or someone comments on a post you participate in; Slack will send notifications in conversations you are mentioned.

As a front-end developer, I'm curious how to use browser notifications to serve websites that don't handle a lot of information flow. How to add relevant browser notifications based on visitors’ interest in the website?

This article will demonstrate how to implement a notification system on the Concise CSS website to alert visitors every time a new version of the framework is released. I'll show how to use localStorage and browser Notification API to achieve this.

Displaying Dynamic Messages Using the Web Notification API

Notification API Basics

First of all, we need to determine whether the visitor's browser supports notifications. Most of the work in this tutorial will be done by the Notification object.

(function() {
  if ("Notification" in window) {
    // 代码在此处
  }
})();
Copy after login
Copy after login
Copy after login

At present, we only determine whether the browser supports notifications. After confirming, we need to know if we can display permission requests to the visitors.

We store the output of the permission property in a variable. If permission has been granted or denied, nothing is returned. If we have not requested permissions before, we use the requestPermission method to request permissions.

(function() {
  if ("Notification" in window) {
    var permission = Notification.permission;

    if (permission === "denied" || permission === "granted") {
      return;
    }

    Notification.requestPermission();
  }
})();
Copy after login
Copy after login
Copy after login

Displaying Dynamic Messages Using the Web Notification API

You should see prompts similar to the above image in your browser.

Now that we have requested permissions, let's modify the code so that the notification will be displayed if permissions are allowed:

(function() {
  if ("Notification" in window) {
    var permission = Notification.permission;

    if (permission === "denied" || permission === "granted") {
      return;
    }

    Notification
      .requestPermission()
      .then(function() {
        var notification = new Notification("Hello, world!");
      });
  }
})();
Copy after login
Copy after login

Displaying Dynamic Messages Using the Web Notification API

Although simple, it has an effective function.

We use the Promise-based syntax of the requestPermission() method here to display notifications after permission is granted. We use the Notification constructor to display notifications. This constructor takes two arguments, one for notification title and the other for options. Please refer to the documentation link for a complete list of options that can be passed.

Storage Framework Version

Above mentioned, we will use localStorage to help display notifications. Using localStorage is a recommended way to store persistent client information in JavaScript. We will create a localStorage key called conciseVersion that contains the current version of the framework (e.g. 1.0.0). We can then use this key to check for a new version of the framework.

How to update the value of the conciseVersion key using the latest version of the framework? We need a way to set the current version when someone visits a website. We also need to update the value when a new version is released. Every time the conciseVersion value changes, a notification needs to be displayed to the visitors to announce a new version of the framework.

We will solve this problem by adding a hidden element to the page. This element will have a class named js-currentVersion and will only contain the current version of the framework. Since this element exists in the DOM, we can easily interact with it using JavaScript.

This hidden element will be used to store the framework version in our conciseVersion key. We will also use this element to update the key when a new version of the framework is published.

(function() {
  if ("Notification" in window) {
    // 代码在此处
  }
})();
Copy after login
Copy after login
Copy after login

We can use a small amount of CSS to hide this element:

(function() {
  if ("Notification" in window) {
    var permission = Notification.permission;

    if (permission === "denied" || permission === "granted") {
      return;
    }

    Notification.requestPermission();
  }
})();
Copy after login
Copy after login
Copy after login

Note: Since this element does not contain anything meaningful, screen readers do not need to access this element. That's why I set the aria-hidden property to true and use display: none as a method to hide elements. For more information on hidden content, see this WebAIM article.

Now we can get this element and interact with it in JavaScript. We need to write a function to return the text inside the hidden element we just created.

(function() {
  if ("Notification" in window) {
    var permission = Notification.permission;

    if (permission === "denied" || permission === "granted") {
      return;
    }

    Notification
      .requestPermission()
      .then(function() {
        var notification = new Notification("Hello, world!");
      });
  }
})();
Copy after login
Copy after login

This function uses the textContent property to store the contents of the .js-currentVersion element. Let's add another variable to store the contents of the conciseVersion localStorage key.

<span class="js-currentVersion" aria-hidden="true">3.4.0</span>
Copy after login

Now we have the latest version of the framework in a variable and we store the localStorage key into a variable. It's time to add logic to determine if there is a new version of the framework available.

We first check whether the conciseVersion key exists. If it does not exist, we will show the notification to the user as this may be their first visit. If the key exists, we check if its value (stored in the currentVersion variable) is greater than the current version's value (stored in the latestVersion variable). If the latest version of the framework is larger than the last version seen by the visitor, we know that the new version has been released.

Note: We use the semver-compare library to handle comparing two version strings.

After knowing this, we will show the notification to the visitors and update our conciseVersion key appropriately.

[aria-hidden="true"] {
  display: none;
  visibility: hidden;
}
Copy after login

To use this function, we need to modify the following permission code.

function checkVersion() {
  var latestVersion = document.querySelector(".js-currentVersion").textContent;
}
Copy after login

This allows us to display notifications when the user has granted permissions before or just granted permissions.

Show notification

So far, we have only shown users simple notifications that do not contain much information. Let's write a function that allows us to create browser notifications dynamically and control many different aspects of notifications.

This function has parameters for body text, icon, title, and optional link and notification duration. Internally, we create an option object to store our notification body text and icons. We also create a new instance of the Notification object, passing in our notification title as well as the option object.

Next, if we want to link to our notifications, we will add an onclick handler. We use setTimeout() to turn off notifications after a specified time. If the time is not specified when this function is called, the default five seconds are used.

(function() {
  if ("Notification" in window) {
    // 代码在此处
  }
})();
Copy after login
Copy after login
Copy after login

Now, let's modify checkVersion() to display notifications of more information to the user.

(function() {
  if ("Notification" in window) {
    var permission = Notification.permission;

    if (permission === "denied" || permission === "granted") {
      return;
    }

    Notification.requestPermission();
  }
})();
Copy after login
Copy after login
Copy after login

We use the displayNotification function to provide description, image, title and link to our notifications.

Note: We use ES6 template literals to embed expressions into our text.

Full code and test

The following is the complete code written in this tutorial.

(CodePen link or full code block should be inserted here)

Running this code should generate the following notification in your browser.

Displaying Dynamic Messages Using the Web Notification API

To perform testing, you need to be familiar with the notification permissions of your browser. Here are some quick references to managing notifications in Google Chrome, Safari, FireFox, and Microsoft Edge. Additionally, you should be familiar with using the developer console to delete and modify localStorage values ​​for easy testing.

You can test the example by running the script once and changing the value of the js-currentVersion HTML element to the script to see the difference. You can also rerun with the same version to confirm that you will not receive unnecessary notifications.

Go a step further

This is everything we need to have dynamic browser notifications! If you are looking for more flexible browser notifications, it is recommended that you understand the Service Worker API. Service Worker can be used to respond to push notifications, allowing users to receive notifications regardless of whether they are currently visiting your website, thus enabling more timely updates.

Browser Notification API FAQ

What is the browser notification API and how does it work?

The browser notification API allows web applications to display system notifications to users. These notifications are similar to push notifications on mobile devices and can be displayed even if the webpage is not in focus. The API works by requesting user permissions to display notifications. Once permission is obtained, web applications can create and display notifications using Notification objects.

How to request permission to display notifications?

To request permission, you can use the Notification.requestPermission() method. This method will show the user a dialog box asking them whether they allow notifications to be displayed. This method returns a Promise, which resolves to a permission status, which can be "granted", "denied", or "default".

How to create and display notifications?

Once permission is obtained, notifications can be created and displayed using the Notification constructor. This constructor accepts two parameters: the title of the notification and an option object. The option object can contain properties such as body (the text of the notification), icon (the icon to be displayed), and tag (the identifier of the notification).

Can I display notifications even if the web page is not in focus?

Yes, the browser notification API allows you to display notifications even if the web page is not in focus. This is very useful for web applications that need to notify users of important events, even if they are not actively using the application.

How to deal with click events on notifications?

You can handle click events on notifications by adding an event listener to the notification object. When the user clicks on the notification, the event listener function is called.

Can I turn off notifications programmatically?

Yes, you can programmatically close notifications by calling the close() method on the notification object. This is useful if you want to automatically turn off notifications after a while.

Does all browsers support browser notifications?

Most modern browsers support browser notifications, including Chrome, Firefox, Safari, and Edge. However, support may vary between different versions of these browsers, and some older browsers may not support notifications at all.

Can I customize the appearance of notifications?

The appearance of notifications depends heavily on the operating system and browser. However, you can customize certain aspects of the notification using the option object passed to the Notification constructor, such as title, body text, and icons.

How to check if the user has granted permission to display notifications?

You can check the current permission status by accessing the Notification.permission property. This property will be "granted" if the user has granted permissions; "denied" if they have denied permissions, and "default" if they have not responded to permission requests.

Can I use the browser notification API in my worker script?

Yes, the browser notification API can be used in the worker script. This allows you to display notifications from background tasks, even if the main page is not in focus.

The above is the detailed content of Displaying Dynamic Messages Using the Web Notification API. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template