Hello friends,
Today we are going to implement Push Notifications for desktop.
Copy below code and run in your localhost or live:
Code of JS:
var articles = [
["Laravel 5.4 Socialite Facebook Login", "https://devat73.wordpress.com/2017/05/31/dynamic-desktop-push-notifications-using-the-notifications-api/"],
["How to migrate single database table in laravel", "https://devat73.wordpress.com/2017/05/24/how-to-migrate-single-database-table-in-laravel/"],
["How to solve the phpmyadmin not found issue", "https://devat73.wordpress.com/2017/05/18/how-to-solve-the-phpmyadmin-not-found-issue/"],
["localhost is not working?", "https://devat73.wordpress.com/2017/05/18/localhost-is-not-working/"],
["Un-install and Re-install PHP", "https://devat73.wordpress.com/2017/05/15/un-install-and-re-install-php/"]
];
setTimeout(function () {
var x = Math.floor((Math.random() * 5) + 1);
var title = articles[x][0];
var desc = 'Most popular article.';
var url = articles[x][1];
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 = 'Most popular article.';
var url = articles[x][1];
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: 'https://lh3.googleusercontent.com/-aCFiK4baXX4/VjmGJojsQ_I/AAAAAAAANJg/h-sLVX1M5zA/s48-Ic42/eggsmall.png',
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');
};
}
}
Code of 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;}
Code of HTML:
Dynamic desktop push notifications using the Notifications API Demo
Click notification button
Notification
Enjoy…cheers…friends.