search
HomeWeb Front-endH5 Tutorial使用HTML5 Notication API实现一个定时提醒工具

       在本文中将利用封装过的API实现一个定时提醒工具。

       工具的主要目的是:自己经常坐在电脑前,一坐就是好几个小时,希望有工具能够每小时提醒自己起来活动休息一会。

       主要功能有:用户可以设置周期性的提醒时间,比如设置每1小时提醒一次,1小时后将弹出通知框提醒用户时间到。

       其他包括:用户能够设置对话框的持续时间,比如持续15秒,15秒后对话框消失,以及提醒内容等。


      HTML&CSS

      首先先创建基本的HTML结构如下:



  1.        
  2.                
  3.                 时间提醒
  4.                
  5.                         div {
  6.                                 margin:40px 15px;
  7.                         }
  8.                        
  9.                         #main {                               
  10.                                 margin:0 auto;
  11.                                 width:360px;
  12.                                 border: 2px solid green;
  13.                         }
  14.                        
  15.                         .operation {
  16.                                 text-align:center;
  17.                         }
  18.                        
  19.                
  20.        
  21.        
  22.                

  23.                

  24.                

  25.                

  26.                

  27.                        
  28.                        
  29.                

  •                

  •                
  •                
  •        
  • 复制代码

          desktopNotify.js是前面提到的封装过的Notification API, desktop-notification.js则是相关的业务逻辑JS,后面会说到。基本的效果如下,虽然是丑陋了点- -!!

    0000.png


          程序的逻辑比较简单,设置各个字段,点击"开始"按钮,程序开始计时,到指定时间,弹出通知框。

          JavaScrip


          desktopNotify.js的功能主要是对原生Notification API做一些基本封装,代码如下:

    1. //desktopNotify.js
    2. void function() {
    3.         var _instance = null,
    4.                 _permissionStatus = -1,
    5.                 _eventTable = {
    6.                         "show": 1,
    7.                         "error": 1,
    8.                         "close": 1,
    9.                         "click": 1
    10.                 };
    11.        
    12.        
    13.         /**
    14.          *调用例子:
    15.          * var DN = window.XX.DesktopNotify;
    16.          * DN.requestPermission(function(){
    17.          *           DN.show("http://xxx", "hello", "world");
    18.          * });
    19.          */       
    20.         var DesktopNotify = {
    21.                
    22.                 /**
    23.                  *检测是否支持Notification,支持返回true
    24.                  */
    25.                 isSupport : function() {
    26.                         return 'Notification' in window || 'webkitNotifications' in window;
    27.                 },

    28.                 /**
    29.                  *弹出一个文本桌面通知
    30.                  *
    31.                  * @param {String} iconURL:图标资源
    32.                  * @param {String} title: 标题
    33.                  * @param {String} content: 内容
    34.                  */
    35.                 show : function(iconURL, title, content) {
    36.                         _instance = this.create(iconURL, title, content);
    37.                         _instance.show();
    38.                 },

    39.                
    40.                 /**
    41.                  *弹出一个 HTML桌面通知
    42.                  *
    43.                  * @param {String} url:html链接资源
    44.                  */
    45.                 showHTML : function(url) {
    46.                         _instance = this.createHTML(url);
    47.                         _instance.show();
    48.                 },

    49.                 /***
    50.                  * 关闭一个桌面通知
    51.                  *
    52.                  * @param {Object} cb: 隐藏后的回调函数
    53.                  *
    54.                  */
    55.                 hide : function(cb) {
    56.                         _instance && _instance.close();
    57.                         cb && cb();
    58.                 },
    59.                
    60.                 /**
    61.                  * 释放通知对话框引用
    62.                  */
    63.                 destroy: function() {
    64.                         _instance = null,
    65.                         _permissionStatus = -1;
    66.                 },

    67.                 /**
    68.                  * 检查权限状态
    69.                  * @return {Number}: 0为允许,1为不允许, 2为禁止
    70.                  */
    71.                 checkPermission : function() {
    72.                         return _permissionStatus = webkitNotifications.checkPermission();
    73.                 },
    74.                
    75.                 /**
    76.                  * 检查是否得到授权
    77.                  * @return {Boolean}: true表示得到授权
    78.                  */
    79.                 isPermitted: function() {
    80.                         return this.checkPermission() === 0;
    81.                 },
    82.                
    83.                
    84.                 /**
    85.                  * 请求授权
    86.                  * @param {Object} cb:得到授权后的回调函数
    87.                  */
    88.                 requestPermission: function(cb) {
    89.                         if(this.isPermitted()) {
    90.                                 cb && cb();
    91.                         } else {
    92.                                 webkitNotifications.requestPermission(cb);
    93.                         }
    94.                 },
    95.                
    96.                 /**
    97.                  * 创建一个文本性质的通知对话框,但不展示
    98.                  * @param {Object} iconURL
    99.                  * @param {Object} title
    100.                  * @param {Object} content
    101.                  * @return {Object} Notification实例
    102.                  */
    103.                 create: function(iconURL, title, content) {
    104.                         return webkitNotifications.createNotification(iconURL, title, content);
    105.                 },
    106.                
    107.                 /**
    108.                  * 创建一个HTML性质的通知对话框,但不展示
    109.                  * @param {Object} url: 指向html页面的链接
    110.                  * @return {Object} Notification实例
    111.                  */
    112.                 createHTML: function(url) {
    113.                         return webkitNotifications.createHTMLNotification(url);
    114.                 },
    115.                
    116.                 /**
    117.                  * 添加事件监听函数
    118.                  * @param {Object} type: 事件类型
    119.                  * @param {Object} fn: 监听函数
    120.                  */
    121.                 on: function(type, fn) {
    122.                         _eventTable[type] && _instance && _instance.addEventListener(type, fn, false);
    123.                 },
    124.                
    125.                 /**
    126.                  * 移除事件监听函数
    127.                  * @param {Object} type: 事件类型
    128.                  * @param {Object} fn: 监听函数
    129.                  */
    130.                 un: function(type, fn) {
    131.                                 _eventTable[type] && _instance && _instance.removeEventListener(type, fn, false);
    132.                 }
    133.         };

    134.         window.XX || (window.XX = {});
    135.         window.XX.DesktopNotify = DesktopNotify;
    136. }();
    复制代码

          desktop-notification.js则是业务代码,如下:

    1. //desktop-notification.js
    2. void function() {
    3.     var TITLE = '时间到啦~~!亲!!',
    4.             //图标路径
    5.         ICONURL = 'icon.png';

    6.     var DN = window.XX.DesktopNotify;

    7.    /**
    8.     * 通知函数,根据设置的时间间隔,周期的弹出通知框
    9.     */
    10.     function notify(content, duration) {
    11.         DN.show(ICONURL, TITLE, content);
    12.         setTimeout(function() {
    13.             DN.hide();
    14.         }, duration);
    15.     }

    16.     if (!DN.isSupport()) {
    17.         alert('浏览器不支持桌面通知!');
    18.         return;
    19.     }

    20.     var startEl = document.getElementById('start'),//开始按钮
    21.         stopEl = document.getElementById('stop'),//停止按钮
    22.         intervalEl = document.getElementById('interval'),//提醒时间间隔输入框
    23.         contentEl = document.getElementById('content'),//提醒内容输入框
    24.         durEl = document.getElementById('duration'),//通知框持续时间输入框
    25.         timer = null;

    26.     startEl.addEventListener('click', function(evt) {
    27.         /**
    28.          * 点击“开始”,先申请用户授权,经过授权后,获取相关的提醒时间间隔,以及内容,周期的调用notify函数弹出通知框
    29.          */
    30.         DN.requestPermission(function() {
    31.             timer = setInterval(notify, intervalEl.value * 60 * 1000, contentEl.value, durEl.value * 60 * 1000);
    32.             startEl.disabled = true;
    33.         });
    34.     }, false);

    35.     stopEl.addEventListener('click', function(evt) {
    36.         /**
    37.          * 点击“停止”,清除周期调用
    38.          */
    39.         clearInterval(timer);
    40.         startEl.disabled = false;
    41.     }, false);
    42. }();
    复制代码

          运行效果

          注意,网页必须在HTTP或HTTPS协议下打开,而不能直接用File协议打开,否则无法运行(若用户设置了浏览器接收任何通知,倒是可以直接打开运行)。运行的效果如下:

    000.png


          即便当浏览器最小化,或者未在高亮状态,通知框一样会定时弹出。

          总结

          在本文中,利用了HTML5 Notification做了一个简单的小工具,用于提醒自己不要久坐,按时休息= =!虽然界面是丑陋了点,不过效果还可以。


    完整代码点击:https://github.com/Exodia/jsdemo/tree/master/desktop-notifications


    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
    How do I use viewport meta tags to control page scaling on mobile devices?How do I use viewport meta tags to control page scaling on mobile devices?Mar 13, 2025 pm 08:00 PM

    The article discusses using viewport meta tags to control page scaling on mobile devices, focusing on settings like width and initial-scale for optimal responsiveness and performance.Character count: 159

    How to Add Audio to My HTML5 Website?How to Add Audio to My HTML5 Website?Mar 10, 2025 pm 03:01 PM

    This article explains how to embed audio in HTML5 using the <audio> element, including best practices for format selection (MP3, Ogg Vorbis), file optimization, and JavaScript control for playback. It emphasizes using multiple audio f

    How to Create Interactive Games with HTML5 and JavaScript?How to Create Interactive Games with HTML5 and JavaScript?Mar 10, 2025 pm 06:34 PM

    This article details creating interactive HTML5 games using JavaScript. It covers game design, HTML structure, CSS styling, JavaScript logic (including event handling and animation), and audio integration. Essential JavaScript libraries (Phaser, Pi

    How do I handle user location privacy and permissions with the Geolocation API?How do I handle user location privacy and permissions with the Geolocation API?Mar 18, 2025 pm 02:16 PM

    The article discusses managing user location privacy and permissions using the Geolocation API, emphasizing best practices for requesting permissions, ensuring data security, and complying with privacy laws.

    How to Use HTML5 Forms for User Input?How to Use HTML5 Forms for User Input?Mar 10, 2025 pm 02:59 PM

    This article explains how to create and validate HTML5 forms. It details the <form> element, input types (text, email, number, etc.), and attributes (required, pattern, min, max). The advantages of HTML5 forms over older methods, incl

    How do I use the HTML5 Page Visibility API to detect when a page is visible?How do I use the HTML5 Page Visibility API to detect when a page is visible?Mar 13, 2025 pm 07:51 PM

    The article discusses using the HTML5 Page Visibility API to detect page visibility, improve user experience, and optimize resource usage. Key aspects include pausing media, reducing CPU load, and managing analytics based on visibility changes.

    How do I use the HTML5 Drag and Drop API for interactive user interfaces?How do I use the HTML5 Drag and Drop API for interactive user interfaces?Mar 18, 2025 pm 02:17 PM

    The article explains how to use the HTML5 Drag and Drop API to create interactive user interfaces, detailing steps to make elements draggable, handle key events, and enhance user experience with custom feedback. It also discusses common pitfalls to a

    How do I use the HTML5 WebSockets API for bidirectional communication between client and server?How do I use the HTML5 WebSockets API for bidirectional communication between client and server?Mar 12, 2025 pm 03:20 PM

    This article explains the HTML5 WebSockets API for real-time, bidirectional client-server communication. It details client-side (JavaScript) and server-side (Python/Flask) implementations, addressing challenges like scalability, state management, an

    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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools