

要使用Notification API,有几个步骤:首先,要从用户那里获取显示通知的许可,只有当用户允许时,才能显示通知给用户。所以先要征求用户的许可而不是直接显示通知。然后,
获取用户许可之后,我们可以显示两种类型的信息:
Normal/Default Notification HTML Notification
最后执行通知代码。
我已经创建了一个显示通知的JavaScript函数,注意:函数仅限用于这篇文章,因为有很多种方式可以按照每个人的需求去扩展。
HTML:
<h2>Show Normal Notification</h2> <button class="btn btn-success" id="show_notification"> Normal Notification </button> <h2>Show HTML Notification</h2> <button class="btn btn-success" id="show_html_notification"> HTML Notification </button>
JavaScript:
// Function to show Notification
function createNotification(type)
{
if(type == '')
type = 'normal';
if(type != 'html')
{
var title ="You have received HTML 5 Notification";
var msg="Content Goes Here......";
var notification = window.Notifications.createNotification("1.png", title, msg);
}
else
{
var notification = window.Notifications.createHTMLNotification('content.html');
}
notification.show();
}
// Binding the Click event on buttons.
$(document).ready(function ()
{
if (window.webkitNotifications)
{
window.Notifications = window.webkitNotifications;
$('#show_notification').click(function ()
{
if (window.Notifications.checkPermission() == 0)
{
createNotification('normal');
}
else
{
window.Notifications.requestPermission();
}
});
$('#show_html_notification').click(function ()
{
if (window.Notifications.checkPermission() == 0)
{
createNotification('html');
}
else
{
window.Notifications.requestPermission();
}
});
}
else
{
alert('HTML 5 Notifications are not supported on this browser/OS.');
}
}); 总结
HTML 5 notification适用于像Google Chrome一样的Web Kit浏览器,对于HTML 5 notification,Mozilla Firefox有其自己的私有属性。我将在其它文章中介绍。
