国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
What is the browser notification API and how does it work?
How to request permission to display notifications?
How to create and display notifications?
Can I display notifications even if the web page is not in focus?
How to deal with click events on notifications?
Can I turn off notifications programmatically?
Does all browsers support browser notifications?
Can I customize the appearance of notifications?
How to check if the user has granted permission to display notifications?
Can I use the browser notification API in my worker script?
Home Web Front-end JS Tutorial Displaying Dynamic Messages Using the Web Notification API

Displaying Dynamic Messages Using the Web Notification API

Feb 17, 2025 pm 01:06 PM

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) {
    // 代碼在此處
  }
})();

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();
  }
})();

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!");
      });
  }
})();

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) {
    // 代碼在此處
  }
})();

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();
  }
})();

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!");
      });
  }
})();

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>

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;
}

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

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

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) {
    // 代碼在此處
  }
})();

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();
  }
})();

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

How can you reduce the payload size of a JavaScript application? How can you reduce the payload size of a JavaScript application? Jun 26, 2025 am 12:54 AM

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

How to make an HTTP request in Node.js? How to make an HTTP request in Node.js? Jul 13, 2025 am 02:18 AM

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS Jul 02, 2025 am 01:28 AM

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.

How does garbage collection work in JavaScript? How does garbage collection work in JavaScript? Jul 04, 2025 am 12:42 AM

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

var vs let vs const: a quick JS roundup explainer var vs let vs const: a quick JS roundup explainer Jul 02, 2025 am 01:18 AM

The difference between var, let and const is scope, promotion and repeated declarations. 1.var is the function scope, with variable promotion, allowing repeated declarations; 2.let is the block-level scope, with temporary dead zones, and repeated declarations are not allowed; 3.const is also the block-level scope, and must be assigned immediately, and cannot be reassigned, but the internal value of the reference type can be modified. Use const first, use let when changing variables, and avoid using var.

See all articles