How to do Push Notification in Web Applications.
Why use Push Notification?
There are few apps nowadays for which real time notifications are not a core feature. From friend requests to pull requests, keeping users updated is key to their experience. Users want to be in the know about the content that interests them, and receive current information without the need for a browser refresh. It improves peer interactions between friends and colleagues, increases social reach, and triggers important conversations that could be invaluable to your app experience. we can do by using below JavaScript function
function notifyMe(msg,link) { // Let's check if the browser supports notifications if (!("Notification" in window)) { alert("This browser does not support desktop notification"); } // Let's check whether notification permissions have already been granted else if (Notification.permission === "granted") { // If it's okay let's create a notification spawnNotification(msg, 'images/logo', 'application says', link); } // Otherwise, we need to ask the user for permission else if (Notification.permission !== 'denied') { Notification.requestPermission(function (permission) { // If the user accepts, let's create a notification if (permission === "granted") { //var notification = new Notification(msg); spawnNotification(msg, 'images/logo', 'application says', link); } }); } // At last, if the user has denied notifications, and you // want to be respectful there is no need to bother them any more. } Notification.requestPermission().then(function (result) { console.log(result); });
// this function create notification and show
function spawnNotification(theBody, theIcon, theTitle, theLink) { var options = { body: theBody, icon: theIcon } var n = new Notification('application says', options); n.onclick = function () {
//if user clicks on notification, the given URL will open in new tab.
window.open(theLink); }; playSound('alert2') // Plays sound. setTimeout(n.close.bind(n), 5000); // close the notification after 5 sec } function playSound(filename) { document.getElementById("sound").innerHTML = '<audio autoplay="autoplay"><source src="Audio/' + filename + '.mp3" type="audio/mpeg" />
<source src="Audio/' + filename + '.ogg" type="audio/ogg" /><embed hidden="true" autostart="true" loop="false" src="Audio/' + filename + '.mp3" /></audio>'; }
In HTML
<a
href="javascript:void(0);" onclick="notifyMe('This is sample
application','www.example.com')"> Show Notification </a>
<div id="sound"></div>
If you are want to run it on background
// run every 10 sec
setInterval(notifyMe('This is sample application','www.example.com'), 10000);
No comments:
Post a Comment