Skip to content

Instantly share code, notes, and snippets.

@kayluhb
Forked from deanhume/offline-notification.js
Last active August 24, 2016 15:49
Show Gist options
  • Save kayluhb/59ade30255f71ce9781a4c1eb3f91bcb to your computer and use it in GitHub Desktop.
Save kayluhb/59ade30255f71ce9781a4c1eb3f91bcb to your computer and use it in GitHub Desktop.
Offline toast notifications
var urlToCheck = 'https://deanhume.github.io/beer' + createStyleUrl(styleId, pageId, false);
/**
* Display the offline notification.
* @return {void}
**/
function showOfflineNotification() {
// return if there is no service worker
if (!'serviceWorker' in navigator) {
return;
}
// Open the cache and check if we have this page saved
caches.open('beer-data').then(checkURL);
}
/**
* Callback function to check the URL in the cache
* @param {String} the service worker cache to match
* @return {void}
**/
function checkURL(cache) {
cache.match(urlToCheck).then(updateCachedPageUI);
}
/**
* Callback function to update the page UI based on the state of the cache
* @param {Object} The response from the cache match
* @return {void}
**/
function updateCachedPageUI(response) {
// return if we found nothing
if (response == undefined || !(response.ok && window.localStorage.getItem(urlToCheck) === null) {
return;
}
// We found the resource in cache
var offlineNotification = document.querySelector('#offline-notification');
var data = { message: 'This page is now available offline' };
offlineNotification.MaterialSnackbar.showSnackbar(data);
// Save the message into storage
window.localStorage.setItem(urlToCheck, true);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment