Skip to content

Instantly share code, notes, and snippets.

@oceangravity
Created November 27, 2018 11:17
Show Gist options
  • Save oceangravity/0a5a6b57a78c9918efe400596db8788b to your computer and use it in GitHub Desktop.
Save oceangravity/0a5a6b57a78c9918efe400596db8788b to your computer and use it in GitHub Desktop.
WebsKit - E05
var CACHE_VERSION = 'WebsKit-CACHE-E05'
var CACHE_FILES = [
'./'
]
self.addEventListener('install', function (event) {
event.waitUntil(
caches.open(CACHE_VERSION)
.then(function (cache) {
console.log('Opened cache: ' + CACHE_VERSION)
return cache.addAll(CACHE_FILES)
}).then(function () {
return self.skipWaiting()
})
)
})
self.addEventListener('activate', function (event) {
// Just for debugging, list all controlled clients.
self.clients.matchAll({
includeUncontrolled: true
}).then(function (clientList) {
var urls = clientList.map(function (client) {
return client.url
})
console.log('[ServiceWorker] Matching clients:', urls.join(', '))
})
event.waitUntil(
// Delete old cache entries that don't match the current version.
caches.keys().then(function (cacheNames) {
return Promise.all(
cacheNames.map(function (cacheName) {
if (cacheName !== CACHE_VERSION) {
console.log('[ServiceWorker] Deleting old cache:', cacheName)
return caches.delete(cacheName)
}
})
)
}).then(function () {
// `claim()` sets this worker as the active worker for all clients that
// match the workers scope and triggers an `oncontrollerchange` event for
// the clients.
console.log('[ServiceWorker] Claiming clients for version', CACHE_VERSION)
return self.clients.claim()
})
)
})
self.addEventListener('fetch', event => {
event.respondWith(
caches.open(CACHE_VERSION)
.then(cache => cache.match(event.request))
.then(response => {
self.clients.matchAll()
.then(function (clientList) {
var senderID = event.clientID
clientList.forEach(function (client) {
client.postMessage({
client: senderID,
message: event.request.url
})
})
})
if (response) {
return Promise.resolve(response)
} else {
return fetch(event.request).then(res => {
if (res && res.status === 200 && event.request.method === 'GET') {
caches.open(CACHE_VERSION)
.then(cache => {
cache.put(event.request, res)
})
}
return res.clone()
})
}
})
)
})
// Listen for messages from clients.
self.addEventListener('message', function (event) {
// Get all the connected clients and forward the message along.
var promise = self.clients.matchAll()
.then(function (clientList) {
// event.source.id contains the ID of the sender of the message.
var senderID = event.source.id
clientList.forEach(function (client) {
// Skip sending the message to the client that sent it.
if (client.id === senderID) {
return
}
client.postMessage({
client: senderID,
message: event.data
})
})
})
// If event.waitUntil is defined, use it to extend the
// lifetime of the Service Worker.
if (event.waitUntil) {
event.waitUntil(promise)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment