search
HomeWeb Front-endH5 TutorialTutorial on making web notifications using HTML5 Notification API_html5 tutorial tips

When using the web version of Gmail, whenever a new email is received, a corresponding prompt box will pop up in the lower right corner of the screen. With the Notification API provided by HTML5, we can also easily implement such a function.
Make sure your browser supports it

If you are developing on a specific version of the browser, then I recommend that you first go to caniuse to check the browser's support for the Notification API to avoid wasting precious time on an unusable API.
How to get started

JavaScript CodeCopy content to clipboard
  1. var notification=new Notification('Notification Title',{
  2. body:'Your Message'
  3. });

The above code constructs a simple notification bar. The first parameter of the constructor sets the title of the notification bar, and the second parameter is an option object, which can set the following properties:

  • body: Set the body content of the notification bar.
    dir: Define the display direction of the notification bar text, which can be set to auto (automatic), ltr (left to right), or rtl (right to left).
    lang: Declares the language used for the text in the notification bar. (Annotation: The value of this attribute must belong to the BCP 47 language tag.)
    tag: Assign an ID value to the notification bar to facilitate retrieval, replacement or removal of the notification bar.
    icon: Set the URL of the image used as the notification bar icon

Get permission

Before displaying the notification bar, you need to apply for permission from the user. Only with the user's permission can the notification bar appear on the screen. The processing of permission application will have the following return value:

  • Default: The user processing result is unknown, so the browser will regard the user as refusing to pop up the notification bar. ("Browser: You didn't ask for notification, so I won't notify you")
    denied: The user refuses to pop up the notification bar. ("User: scroll away from my screen")
    granted: The user allows the notification bar to pop up. ("User: Welcome! I'm excited to use this notification feature")

JavaScript CodeCopy content to clipboard
  1. Notification.requestPermission(function(permission){
  2.  //display notification here making use of constructor  
  3. });

Create a button using HTML

XML/HTML CodeCopy content to clipboard
  1. button id="button" >Read your notificationbutton>

Don’t forget CSS

CSS CodeCopy content to clipboard
  1. #button{   
  2.   font-size:1.1rem;   
  3.   width:200px;   
  4.   height:60px;   
  5.   border:2px solid #df7813;   
  6.   border-radius:20px/50px;   
  7.   background:#fff;   
  8.   color:#df7813;   
  9. }   
  10. #button:hover{   
  11.   background:#df7813;   
  12.   color:#fff;   
  13.   transition:0.4s ease;   
  14. }   
  15.   

全部的Javascript代码如下:
 

JavaScript Code复制内容到剪贴板
  1. document.addEventListener('DOMContentLoaded',function(){   
  2.         document.getElementById('button').addEventListener('click',function(){   
  3.             if(! ('Notification' in window) ){   
  4.                 alert('Sorry bro, your browser is not good enough to display notification');   
  5.                 return;   
  6.             }       
  7.             Notification.requestPermission(function(permission){   
  8.                 var config = {   
  9.                               body:'Thanks for clicking that button. Hope you liked.',   
  10.                               icon:'https://cdn2.iconfinder.com/data/icons/ios-7-style-metro-ui-icons/512/MetroUI_HTML5.png',   
  11.                               dir:'auto'  
  12.                               };   
  13.                 var notification = new Notification("Here I am!",config);   
  14.             });   
  15.         });   
  16.     });   
  17.   

从这段代码可以看出,如果浏览器不支持Notification API,在点击按钮时将会出现警告“兄弟,很抱歉。你的浏览器并不能很好地支持通知功能”(Sorry bro, your browser is not good enough to display notification)。否则,在获得了用户的允许之后,我们自制的通知栏便可以出现在屏幕当中啦。

为什么要让用户手动关闭通知栏?

对于这个问题,我们可以借助setTimeout函数设置一个时间间隔,使通知栏能定时关闭。
 

JavaScript Code复制内容到剪贴板
  1. var config = {   
  2.                body:'Today too many guys got eyes on me, you did the same thing. Thanks',   
  3.                icon:'icon.png',   
  4.                dir:'auto'  
  5.              }   
  6. var notification = new Notification("Here I am!",config);   
  7. setTimeout(function(){   
  8.     notification.close(); //closes the notification   
  9. },5000);   
  10.   

该说的东西就这些了。如果你意犹未尽,希望更加深入地了解Notification API,可以阅读以下的页面:

    MDN
    Paul lund’s tutorial on notification API

在CodePen上查看demo

你可以在CodePen上看到由Prakash (@imprakash)编写的demo

Statement
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
H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.