Skip to content

Instantly share code, notes, and snippets.

@onsails
Created June 2, 2015 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onsails/1fb526ac1cbddcd63bef to your computer and use it in GitHub Desktop.
Save onsails/1fb526ac1cbddcd63bef to your computer and use it in GitHub Desktop.
Deferred notifications demo
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>notif</title>
</head>
<body id="notif" onload="">
<input id="new-notif" type="button" value="Show notification"/>
<script type="text/javascript">
'use strict';
var requestPermission = function(cb) {
Notification.requestPermission(function(result) {
switch(result) {
case 'denied':
alert("You don't want me to work");
case 'default':
alert("Hey, I want some permissions, look at my request near location bar");
default:
cb();
}
})
};
var counter = 0;
var peers = ['USER_1', 'USER_2', 'GROUP_20', 'GROUP_21'];
var randomPeer = function() {
return(peers[Math.floor(Math.random() * peers.length)]);
};
var messageText = function() {
counter += 1;
return("msg " + counter.toString());
};
var showNotification = function(title, body) {
var n = new Notification(title, {
body: body,
tag: 'new-message'
});
n.onclick = function() {
var span = document.createElement("span");
span.innerText = title + ": " + body;
document.body.appendChild(span);
window.focus();
this.close();
}
};
var MAX_DEFER = 3000;
var deferStart = null;
var deferredShow = null;
var createNotification = function(title, body) {
if (deferredShow === null) {
deferStart = Date.now();
} else {
clearTimeout(deferredShow)
}
if (Date.now() - deferStart > MAX_DEFER) {
deferredShow = null;
deferStart = null;
showNotification(title, body);
} else {
deferredShow = setTimeout(function () {
showNotification(title, body)
}, 1000)
}
};
var setEventListeners = function() {
var button = document.getElementById('new-notif');
button.addEventListener('click', function() {
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
} else if (Notification.permission === 'granted') {
createNotification(randomPeer(), messageText());
} else requestPermission(function() {
createNotification(randomPeer(), messageText());
});
})
};
setEventListeners();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment