使用HTML5的Notification API制作web通知的教程

2019-01-28 16:20:40王冬梅
  •                 var notification = new Notification("Here I am!",config);                });   
  •         });        });   
  •   

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

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

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

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

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

        MDN
        Paul lund’s tutorial on notification API

    在CodePen上查看demo

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