Created
June 2, 2015 17:16
-
-
Save onsails/1fb526ac1cbddcd63bef to your computer and use it in GitHub Desktop.
Revisions
-
onsails created this gist
Jun 2, 2015 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,91 @@ <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>