The Notifications API surfaces messages to the user for events that happen with or without the page in focus. Typical uses are passive signals such as new email, tweets or calendar entries, but the API also works on user interactions. At the time of writing it is covered by a draft spec and is not part of any standard, which explains the vendor prefix on the entry point.
Detecting support and requesting access
Checking for webkitNotifications
Feature detection starts with webkitNotifications. The prefixed name reflects the draft status of the spec; the final version is expected to expose a notifications() function instead.
// check for notifications support
// you can omit the 'window' keyword
if (window.webkitNotifications) {
console.log("Notifications are supported!");
}
else {
console.log("Notifications are not supported for this Browser/OS version yet.");
}
Getting the user's permission
Constructing a notification without the user's explicit consent for the site throws a security error. The checkPermission method reports the current state and avoids relying on a try-catch around the constructor.
document.querySelector('#show_button').addEventListener('click', function() {
if (window.webkitNotifications.checkPermission() == 0) { // 0 is PERMISSION_ALLOWED
// function defined in step 2
window.webkitNotifications.createNotification(
'icon.png', 'Notification Title', 'Notification content...');
} else {
window.webkitNotifications.requestPermission();
}
}, false);
When the application is not yet permitted to show notifications, calling requestPermission raises an infobar:
Permission prompts are only honored inside event handlers tied to a user action, such as mouse or keyboard events — in the sample above, the click on the button with id show_button. This restriction exists to prevent unsolicited infobars. A requestPermission call that is not preceded by an explicit click on a button or link will never succeed.
Wiring up events
Once permission is in place, listeners and the remaining notification actions can be attached:
document.querySelector('#show_button').addEventListener('click', function() {
if (window.webkitNotifications.checkPermission() == 0) { // 0 is PERMISSION_ALLOWED
// function defined in step 2
notification_test = window.webkitNotifications.createNotification(
'icon.png', 'Notification Title', 'Notification content...');
notification_test.ondisplay = function() { ... do something ... };
notification_test.onclose = function() { ... do something else ... };
notification_test.show();
} else {
window.webkitNotifications.requestPermission();
}
}, false);
Encapsulating these events and actions in your own Notification class is a reasonable next step for keeping the code readable, though building that abstraction is outside the scope of this tutorial.



