亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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)

Hot Topics

PHP Tutorial
1488
72
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.

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

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

React vs Angular vs Vue: which js framework is best? React vs Angular vs Vue: which js framework is best? Jul 05, 2025 am 02:24 AM

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

JavaScript time object, someone builds an eactexe, faster website on Google Chrome, etc. JavaScript time object, someone builds an eactexe, faster website on Google Chrome, etc. Jul 08, 2025 pm 02:27 PM

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

Understanding Immediately Invoked Function Expressions (IIFE) in JavaScript Understanding Immediately Invoked Function Expressions (IIFE) in JavaScript Jul 04, 2025 am 02:42 AM

IIFE (ImmediatelyInvokedFunctionExpression) is a function expression executed immediately after definition, used to isolate variables and avoid contaminating global scope. It is called by wrapping the function in parentheses to make it an expression and a pair of brackets immediately followed by it, such as (function(){/code/})();. Its core uses include: 1. Avoid variable conflicts and prevent duplication of naming between multiple scripts; 2. Create a private scope to make the internal variables invisible; 3. Modular code to facilitate initialization without exposing too many variables. Common writing methods include versions passed with parameters and versions of ES6 arrow function, but note that expressions and ties must be used.

Handling Promises: Chaining, Error Handling, and Promise Combinators in JavaScript Handling Promises: Chaining, Error Handling, and Promise Combinators in JavaScript Jul 08, 2025 am 02:40 AM

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

What is the cache API and how is it used with Service Workers? What is the cache API and how is it used with Service Workers? Jul 08, 2025 am 02:43 AM

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.

See all articles