- HTML5 Data and Services Cookbook
- Gorgi Kosev Mite Mitreski
- 827字
- 2021-08-06 16:50:01
Using the web notifications API
Web notifications are one of the newer features added into modern browsers. They are intended as alerts for the user outside of the web page context. The idea is for them to be browsers intended, for example, when using a mobile browser notification could go into the home screen of the device. On the desktop usually they show up on the right-corner of the screen, at least on most desktop environments.

Getting ready
For the purpose of this example, we will be using data derived from Project Gutenberg http://www.gutenberg.org/. The data are the tips from the chapter Use of spies from Sun Tzu's -Art of war and can be found in this recipe code example under data.json
.
How to do it...
To create this recipe we will create an HTML file, and use jQuery for simplicity.
- First, we can start with the HTML part, where we just create a simple
button
and adiv
element with the IDfallback
that we are going to use, if the browser does not support notifications.<body> <button id="show">Show quote</button> <div id="fallback" ></div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script src="js/notification.js"></script> <script src="js/display.js"></script> </body>
- Let's first create the
notification.js
file that we will use as utility to createsimpleNotifations.show(data)
. The first check we have to do is verify support forwebkitNotifications
, the only full implementation at the time of writing.var simpleNotification = (function () { var my = {}; my.show = function (data) { if (window.webkitNotifications) { //check if there is a support for webkitNotifications if (window.webkitNotifications.checkPermission()== 0) { var notification = webkitNotifications.createNotification(data.icon, data.title, data.body); notification.show(); //set timeout to hide it setTimeout(function(){ notification.cancel(); }, data.timeout); } else { webkitNotifications.requestPermission(function () { //call the same function again my.show(data); }); } }
- Next is the check for the real-standard-based web notification object, where in future, as browsers implement it more and more, it should be the first one.
else if (window.Notification) { if ("granted" === Notification.permissionLevel()) { var notification = new Notification(data.title, data); notification.show(); } else if ("default" === Notification.permissionLevel() ) { Notification.requestPermission(function () { //call the same function again my.show(data); }); } }
- Finally the case; if there is no support for any type of notification by the system we just use a callback to handle this case, where we also close the utility.
}else{ //Notifications not supported, going with fallback data.errorCallback(); } }; return my; }());
- Next, we can continue with creating the
display.js
file that will get a random quote from the data, and call the previously definedsimpleNotification.show()
method. First we will do the fetching.function fetchRandomQuote(location,data){ $.ajax( { url:location, dataType:'json', success: function(result){ var quoteNumber = Math.floor(Math.random()*26)+1; var obj = result.quotes[quoteNumber]; for(var key in obj){ data.title += key; data.body = obj[key]; } simpleNotification.show(data); }} ); };
- Because we want some default behavior for all the notifications, such as icon, default message, or fallback function, we do the callout with a default
data
object.$(document).ready(function() { $("#show").click(function (){ var data = { icon: "images/war.png", title: "The Art of War - The Use of Spies ", body: "text", timeout : 7000, errorCallback: function(){ $("#fallback").text(this.body); } }; fetchRandomQuote('js/data.json',data); });});
How it works...
We will take a deeper look at the notification.js
file, where most of the notification logic is. The check tests we did on the notifications if (window.webkitNotifications)
and if (window.Notification)
try to see if there is such object in the browser. If no such object is there, this means there is no support for that type of notification. While on the other hand, if the if
condition was met, this means we have support, and can ask for permission.
if (window.webkitNotifications.checkPermission() == 0)
After that, we are free to create the notification and show it with the given parameters for icon
, title
, and body
.
var notification = webkitNotifications.createNotification(data.icon, data.title, data.body); notification.show();
If we want the notification to hide after a given timeout, we add the following function:
setTimeout(function(){ notification.cancel() }, data.timeout);
On the other hand, if we do not have the permission to display a notification, we need to request it from the user, where we can do the call to our function once again.
webkitNotifications.requestPermission(function () { my.show(data); }
Tip
The request for the permission must come from a user-triggered event on some HTML element. In our case this is the onClick
function on the button. More specifically the jQuery click $("#show").click(function (){ ...}
.
We don't need to get into too much details for the fetching of the data, but in our default object we have the icon
parameter with the value images/war.png
that we will get used for the notification, as well as the fallback
function and the timeout
configuration.
var data = { icon: "images/war.png", title: "The Art of War - The Use of Spies ", body: "text", timeout : 7000, errorCallback: function(){ $("#fallback").text(this.body); } };
Note
At the time of writing, Chrome is the only browser with full support for the notifications for quite some time, but Safari 6.0 and Firefox 22 Aurora also have initial implementations.
The full specifications for web notifications can be found from http://www.w3.org/TR/notifications/.
- Learning Neo4j
- Building Modern Web Applications Using Angular
- 自己動(dòng)手實(shí)現(xiàn)Lua:虛擬機(jī)、編譯器和標(biāo)準(zhǔn)庫
- Oracle從新手到高手
- Java加密與解密的藝術(shù)(第2版)
- Java虛擬機(jī)字節(jié)碼:從入門到實(shí)戰(zhàn)
- Java Web開發(fā)技術(shù)教程
- Flux Architecture
- Learning Three.js:The JavaScript 3D Library for WebGL
- Web Development with MongoDB and Node(Third Edition)
- C#開發(fā)案例精粹
- HTML+CSS+JavaScript網(wǎng)頁設(shè)計(jì)從入門到精通 (清華社"視頻大講堂"大系·網(wǎng)絡(luò)開發(fā)視頻大講堂)
- Machine Learning for OpenCV
- Puppet:Mastering Infrastructure Automation
- JavaScript語法簡明手冊