3197891abd2c7abb0c8381c7f3b5de282a415e58

Implementing HTML5 Desktop Notification

image

  • HTML5 provides desktop notification API for use by the developer to generate notification.
  • In this demo, "We will learn to create a desktop notification using HTML5 API".
  • A desktop notification object is created using Notification() class with new keyword.
  • In this demo we have created a button for subscribing notification.When user click on the button browser asked for permission.If user allows the notification then the permission becomes granted.If user blocking it then permission becomes denied.
  • We can check the support of Notification in the browser by detection Notification property presence in Window object.
  • We can also check the support of notification using Can I use online tool.The following screenshot is taken from can I use online tool as of today.The screenshot shows the support of notification API by different browsers.

image

  • The HTML code for rendering a button is as follows:
<button onclick="notifyMe()">
 Subscribe TutorialSavvy Notification
</button>
  • The JavaScript code for requesting permission and generating notification are as follows.
document.addEventListener('DOMContentLoaded', function () {
 if (Notification.permission !== "granted"){
 Notification.requestPermission();
 }
});
function notifyMe() {
 if (!Notification) {
 alert('Desktop notifications not available in your browser.'); 
 return;
 }
 if (Notification.permission !== "granted")
 Notification.requestPermission();
 else {
 var notification = new Notification('TutorialSavvy Notification', {
 icon: 'http://www.tutorialsavvy.com/wp-content/uploads/2015/02/favicon.png',
 body: "Hey there! Welcome TutorialSavvy Site",
 tag :'Example'
 });
 notification.onclick = function () {
 window.open("http://www.tutorialsavvy.com/"); 
 }; 
 }
}
  • The demo code is also available in the following embedded JSBIN link.

JS Bin on jsbin.com

  • The notification looks like following screenshot.

image

Sandeep Patel
Getting Started With Backbone JS Part1 Electron Desktop Notification Using Node Notifier
Sandeep Patel
10 years ago HTML 1,259

AltStyle によって変換されたページ (->オリジナル) /