Skip to content

Instantly share code, notes, and snippets.

@onsails
Created June 2, 2015 17:16
Show Gist options
  • Select an option

  • Save onsails/1fb526ac1cbddcd63bef to your computer and use it in GitHub Desktop.

Select an option

Save onsails/1fb526ac1cbddcd63bef to your computer and use it in GitHub Desktop.

Revisions

  1. onsails created this gist Jun 2, 2015.
    91 changes: 91 additions & 0 deletions gistfile1.html
    Original 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>