Papermashup

Subscribe


Tweets


"RT @bethgordon: .@Tesco Please rethink archaic 'Approved by Mums'. Pretty sure it's not just mothers who make childcare decisions. https://…"

@ashleyford 5 days ago

"Is there ever a time that @DFS doesn't have a sale on?"

@ashleyford 1 week ago

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Papermashup

Browser Notifications API

Allow your web app to display growl like notifications using the notifications browser API

AshleyAshley

The Notifications API lets a web page or app send notifications that are displayed outside the page at a system level. This lets web apps send information to a user even if the application is in the background or idle. It works in a similar way to Growl notifications. Each browser if supporting this feature will have their own design style. Lets take a look at how it works. You can find out more about the notifications API here.

The Code



function spawnNotification(theBody,theIcon,theTitle) {

if(window.Notification && Notification.permission === "granted") {

Notification.requestPermission(function(status) { // status is "granted", if accepted by user

// set some options like the body test
// and an app icon / image
var options = {
body: theBody,
icon: theIcon
};

// fire the notification
var n = new Notification(theTitle, options );

// close the notification after 5 seconds
setTimeout(n.close.bind(n), 5000);
});

}else if(Notification.permission === "denied"){
alert('Sad Face - Please allow notifications in your browser!');
}

}

// run the function
spawnNotification('You\'re reading the JavaScript notifications tutorial!', 'icon.png', 'Papermashup Demo');

One of the most obvious use cases for web notifications is either a web-based mail or Chat / IRC app that needs to notify the user when a new message is received, even if the user is doing something else with another application. Many real examples of this exist such as Slack.

Demo Download

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Comments 1
  • tiery
    Posted on

    tiery tiery

    Reply Author

    Hi, thanks for this article :)
    I just want to point out that if the permission is “granted”, then you don’t have to request it. You have to request it, only if permission is different of “denied” and “granted”.