Skip to content

Instantly share code, notes, and snippets.

@mahedi2014
Created December 4, 2015 09:26
Show Gist options
  • Select an option

  • Save mahedi2014/80d860edac8faaf4cbe8 to your computer and use it in GitHub Desktop.

Select an option

Save mahedi2014/80d860edac8faaf4cbe8 to your computer and use it in GitHub Desktop.
Real time desktop notification with vanilla js
<!DOCTYPE html>
<html>
<head>
<title>Desktop notification</title>
<script type="text/javascript">
var articles = [
["Md. Mahedi Azad","Programmer and Web Developer","http://mahediazad.me"],
["Md. Mahedi Azad","Programmer and Web Developer","http://mahediazad.me"],
["Md. Mahedi Azad","Programmer and Web Developer","http://mahediazad.me"],
["Md. Mahedi Azad","Programmer and Web Developer","http://mahediazad.me"]
];
setTimeout(function(){
var x = Math.floor((Math.random() * 10) + 1);
var title = articles[x][0];
var desc = articles[x][1];
var url = articles[x][2];
notifyBrowser(title,desc,url);
}, 200000);
document.addEventListener('DOMContentLoaded', function () {
if (Notification.permission !== "granted") {
Notification.requestPermission();
}
document.querySelector("#notificationButton").addEventListener("click", function(e) {
var x = Math.floor((Math.random() * 10) + 1);
var title = articles[x][0];
var desc = articles[x][1];
var url = articles[x][2];
notifyBrowser(title,desc,url);
e.preventDefault();
});
});
function notifyBrowser(title,desc,url) {
if (!Notification) {
console.log('Desktop notifications not available in your browser..');
return;
}
if (Notification.permission !== "granted") {
Notification.requestPermission();
} else {
var notification = new Notification(title, {
icon:'http://mahediazad.me/avatar.jpg',
body: desc,
});
// Remove the notification from Notification Center when clicked.
notification.onclick = function () {
window.open(url);
};
// Callback function when the notification is closed.
notification.onclose = function () {
console.log('Notification closed');
};
}
}
</script>
<style type="text/css">
.hover{background-color: #cc0000}
#container{ margin:0px auto; width: 800px}
.button {
font-weight: bold;
padding: 7px 9px;
background-color: #5fcf80;
color: #fff !important;
font-size: 12px;
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
cursor: pointer;
text-decoration: none;
text-shadow: 0 1px 0px rgba(0,0,0,0.15);
border-width: 1px 1px 3px !important;
border-style: solid;
border-color: #3ac162;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: -moz-inline-stack;
display: inline-block;
vertical-align: middle;
zoom: 1;
border-radius: 3px;
box-sizing: border-box;
box-shadow: 0 -1px 0 rgba(255,255,255,0.1) inset;
}
.authorBlock{border-top:1px solid #cc0000;}
</style>
</head>
<body>
<div id="container">
<a href="#" id="notificationButton" class="button">Click notification</a>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment