Skip to content

Instantly share code, notes, and snippets.

@charisTheo
Created October 28, 2018 11:18
Show Gist options
  • Select an option

  • Save charisTheo/1674f3e2f9d506b7e5c331885ca0a282 to your computer and use it in GitHub Desktop.

Select an option

Save charisTheo/1674f3e2f9d506b7e5c331885ca0a282 to your computer and use it in GitHub Desktop.
Service Worker Template
// use a cacheName for cache versioning
var cacheName = 'v1:static';
// during the install phase you usually want to cache static assets
self.addEventListener('install', function(e) {
// once the SW is installed, go ahead and fetch the resources to make this work offline
e.waitUntil(
caches.open(cacheName).then(function(cache) {
return cache.addAll([
'./styles/css/',
'./fonts/',
'./js/',
'./404.html',
'./img/',
]).then(function() {
self.skipWaiting();
}).catch(function(e){ console.log("Error: ", e)})
})
);
});
// when the browser fetches a url
self.addEventListener('fetch', function(event) {
// either respond with the cached object or go ahead and fetch the actual url
event.respondWith(
caches.match(event.request).then(function(response) {
if (response) {
// retrieve from cache
return response;
}
// fetch as normal
return fetch(event.request);
})
);
});
self.addEventListener('push', function(event) {
let options = {};
if (event.data) {
const data = event.data.json();
options = {
...data,
title: "",
icon: 'img/logo/logo-96.png',
chrome_web_icon: 'img/logo/logo-96.png',
badge: 'img/logo/logo-badge-48x48.png',
chrome_web_badge: 'img/logo/logo-badge-48x48.png',
renotify: true
}
self.registration.showNotification(data.title, options);
}
});
self.addEventListener('notificationclick', function(event) {
event.notification.close();
const data = event.notification.data;
if (!event.action) {
// Was a normal notification click
if (event.notification.tag == "new_notifications") { // Ex: check notification tag name
event.waitUntil(clients.openWindow("/notification/showAll")); // and redirect
}
return;
}
switch (event.action) {
case 'show-all-notifications':
event.waitUntil(clients.openWindow("/notification/showAll"));
break;
case 'yes':
event.waitUntil(clients.openWindow(/userClickedYes));
break;
case 'no':
event.waitUntil(clients.openWindow('/userClickedNo'));
break;
case 'search':
event.waitUntil(clients.openWindow("/search"));
break;
default:
console.log(`Unknown action clicked: '${event.action}'`);
break;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment