Last active
May 8, 2020 15:14
-
-
Save abdulloooh/00847da75afb219a62e284659a2e6ca3 to your computer and use it in GitHub Desktop.
Displaying Dynamic Messages Using the Web Notification API to Inform the Users of Your Website when A New Version of Your App is Deployed
This file contains 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 characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Document</title> | |
<style> | |
[aria-hidden="true"] { | |
display: none; | |
visibility: hidden; | |
} | |
</style> | |
</head> | |
<body> | |
<span class="js-currentVersion" aria-hidden="true">2.9</span> //version 2.9 as example | |
//the value 2.9 will be changed in new deploys to the latest version which will be greater than the previous | |
<script src="script.js"></script> | |
</body> | |
</html> |
This file contains 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 characters
(function() { | |
// Check permissions | |
if ("Notification" in window) { | |
var permission = Notification.permission; | |
if (permission === "denied" || permission === "default") { | |
Notification.requestPermission().then(function(permission) { | |
if (permission === "granted") checkVersion(); | |
}); | |
} else if (permission === "granted") { | |
return checkVersion(); | |
} | |
} | |
function checkVersion() { | |
// Retrieve current version | |
//using localstorage to track version | |
var latestVersion = document.querySelector(".js-currentVersion").textContent; | |
var currentVersion = localStorage.getItem("version"); | |
if (currentVersion === null || latestVersion > currentVersion ) { | |
displayNotification( | |
`Click to see what's new in v${latestVersion}`, | |
"link_to_your_icon/or/leave/it/empty/as/it/is/optional", | |
"A new version of myAppName is available", | |
`https://github.com/link/to/my/app/releases/v${latestVersion}` | |
); | |
localStorage.setItem("version", latestVersion); | |
} | |
} | |
function displayNotification(body, icon, title, link, duration) { | |
link = link || 0; // Link is optional | |
duration = duration || 5000; // Default duration is 5 seconds | |
var options = { | |
body: body, | |
icon: icon | |
}; | |
var n = new Notification(title, options); | |
if (link) { | |
n.onclick = function () { | |
window.open(link); | |
}; | |
} | |
setTimeout(n.close.bind(n), duration); | |
} | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment