Thursday, April 22nd, 2010
Desktop Notifications with Webkit
<>p>Mohit Muthanna has a nice blog post explaining how you can create desktop notifications with the latest Webkit/Chrome.
There are essentially three API calls you use:
- window.webkitNotifications.requestPermission(callback) - Request access to Desktop Notifications for this domain.
- window.webkitNotifications.checkPermission() - Returns 0 if this domain has Desktop Notification access.
- window.webkitNotifications.createNotification(icon,title,body) - Returns a popup notification instance, which you can display by calling show() on it.
The demo code is pretty straight forward:
-
-
function Notifier() {}
-
-
// Request permission for this page to send notifications. If allowed,
-
// calls function "cb" with "true" as the first argument.
-
Notifier.prototype.RequestPermission = function(cb) {
-
window.webkitNotifications.requestPermission(function() {
-
if (cb) { cb(window.webkitNotifications.checkPermission() == 0); }
-
});
-
}
-
-
// Popup a notification with icon, title, and body. Returns false if
-
// permission was not granted.
-
Notifier.prototype.Notify = function(icon, title, body) {
-
if (window.webkitNotifications.checkPermission() == 0) {
-
var popup = window.webkitNotifications.createNotification(
-
icon, title, body);
-
popup.show();
-
return true;
-
}
-
-
return false;
-
}
-
The user request happens the same way the W3C geo location API requests access - a toolbar popping up asking you if you are OK to see Desktop Notifications. This is good as I can see this being used by people to fake IM messages - much like they do now in the browser.
The notifications animate in from top right and have the originating URL and a "block" link - which makes it hard to use them for phishing.
Interesting concept and if it could use native systems like Growl it would spell the end of awkward alerts and hand-rolled notification windows in the document.
Related Content:











Don’t forget to hide the popup after a few seconds:
After
popup.show();
Insert
setTimeout(function(){
popup.cancel();
}, ’15000′);
One of the intentions of this is to check for growl support and fallback to in browser notifications if the user doesn’t have growl or other specified notification tools.
Since it can be disabled (pretty much like popups), I think it’s fine. Hope people will not abuse it – and no, skinning support sounds bad enough: I’d rather have a stock growl-like notification message, than a pink rounded box.