Simplified service worker

This commit is contained in:
Eduard Urbach 2019-04-18 23:44:45 +09:00
parent 45643bdd92
commit 08186a9c92
2 changed files with 344 additions and 366 deletions

View File

@ -49,6 +49,7 @@ export default class Application {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let request = new XMLHttpRequest() let request = new XMLHttpRequest()
request.timeout = 20000
request.onerror = () => reject(new Error("You are either offline or the requested page doesn't exist.")) request.onerror = () => reject(new Error("You are either offline or the requested page doesn't exist."))
request.ontimeout = () => reject(new Error("The page took too much time to respond.")) request.ontimeout = () => reject(new Error("The page took too much time to respond."))
request.onload = () => { request.onload = () => {

View File

@ -32,60 +32,72 @@
// E-Tags that we served for a given URL // E-Tags that we served for a given URL
// const ETAGS = new Map<string, string>() // const ETAGS = new Map<string, string>()
// MyServiceWorker is the process that controls all the tabs in a browser. // MyCache is the cache used by the service worker.
class MyServiceWorker { class MyCache {
cache: MyCache version: string
reloads: Map<string, Promise<Response>>
excludeCache: Set<string>
constructor() { constructor(version: string) {
this.cache = new MyCache("v-6") this.version = version
this.reloads = new Map<string, Promise<Response>>() }
clear() {
return caches.delete(this.version)
}
async store(request: RequestInfo, response: Response) {
try {
// This can fail if the disk space quota has been exceeded.
let cache = await caches.open(this.version)
await cache.put(request, response)
} catch(err) {
console.log("Disk quota exceeded, can't store in cache:", request, response, err)
}
}
async serve(request: RequestInfo): Promise<Response> {
let cache = await caches.open(this.version)
let matching = await cache.match(request)
if(matching) {
return matching
}
return Promise.reject("no-match")
}
}
// Globals
let cache = new MyCache("v-7")
let reloads = new Map<string, Promise<Response>>()
// When these patterns are matched for the request URL, we exclude them from being // When these patterns are matched for the request URL, we exclude them from being
// served cache-first and instead serve them via a network request. // served cache-first and instead serve them via a network request.
// Note that the service worker URL is automatically excluded from fetch events // Note that the service worker URL is automatically excluded from fetch events
// and therefore doesn't need to be added here. // and therefore doesn't need to be added here.
this.excludeCache = new Set<string>([ let excludeCache = new Set<string>([
// API requests "/api/", // API requests
"/api/", "/paypal/", // PayPal stuff
"/import/", // List imports
// PayPal stuff "/from/", // Infinite scrolling
"/paypal/", "chrome-extension", // Chrome extension
// List imports
"/import/",
// Infinite scrolling
"/from/",
// Chrome extension
"chrome-extension",
// Authorization paths /auth/ and /logout are not listed here because they are handled in a special way. // Authorization paths /auth/ and /logout are not listed here because they are handled in a special way.
]) ])
self.addEventListener("install", (evt: InstallEvent) => evt.waitUntil(this.onInstall(evt))) // onInstall
self.addEventListener("activate", (evt: any) => evt.waitUntil(this.onActivate(evt))) async function onInstall(evt: InstallEvent) {
self.addEventListener("fetch", (evt: FetchEvent) => evt.waitUntil(this.onRequest(evt)))
self.addEventListener("message", (evt: any) => evt.waitUntil(this.onMessage(evt)))
self.addEventListener("push", (evt: PushEvent) => evt.waitUntil(this.onPush(evt)))
self.addEventListener("pushsubscriptionchange", (evt: any) => evt.waitUntil(this.onPushSubscriptionChange(evt)))
self.addEventListener("notificationclick", (evt: NotificationEvent) => evt.waitUntil(this.onNotificationClick(evt)))
}
async onInstall(evt: InstallEvent) {
console.log("service worker install") console.log("service worker install")
await self.skipWaiting() await self.skipWaiting()
await this.installCache() await installCache()
} }
onActivate(evt: any) { // onActivate
function onActivate(evt: any) {
console.log("service worker activate") console.log("service worker activate")
// Only keep current version of the cache and delete old caches // Only keep current version of the cache and delete old caches
let cacheWhitelist = [this.cache.version] let cacheWhitelist = [cache.version]
let deleteOldCache = caches.keys().then(keyList => { let deleteOldCache = caches.keys().then(keyList => {
return Promise.all(keyList.map(key => { return Promise.all(keyList.map(key => {
@ -107,7 +119,7 @@ class MyServiceWorker {
// onRequest intercepts all browser requests. // onRequest intercepts all browser requests.
// Simply returning, without calling evt.respondWith(), // Simply returning, without calling evt.respondWith(),
// will let the browser deal with the request normally. // will let the browser deal with the request normally.
async onRequest(evt: FetchEvent) { async function onRequest(evt: FetchEvent) {
let request = evt.request as Request let request = evt.request as Request
// If it's not a GET request, fetch it normally. // If it's not a GET request, fetch it normally.
@ -117,12 +129,6 @@ class MyServiceWorker {
return return
} }
// DevTools opening will trigger these "only-if-cached" requests.
// https://bugs.chromium.org/p/chromium/issues/detail?id=823392
if((request.cache as string) === "only-if-cached" && request.mode !== "same-origin") {
return
}
// Video files are always loaded over the network. // Video files are always loaded over the network.
// We are defaulting to the normal browser handler here // We are defaulting to the normal browser handler here
// so we can see the HTTP 206 partial responses in DevTools // so we can see the HTTP 206 partial responses in DevTools
@ -131,7 +137,7 @@ class MyServiceWorker {
return return
} }
return evt.respondWith(fetch(request)) return //evt.respondWith(fetch(request))
// // Exclude certain URLs from being cached. // // Exclude certain URLs from being cached.
// for(let pattern of this.excludeCache.keys()) { // for(let pattern of this.excludeCache.keys()) {
@ -231,7 +237,7 @@ class MyServiceWorker {
} }
// onMessage is called when the service worker receives a message from a client (browser tab). // onMessage is called when the service worker receives a message from a client (browser tab).
async onMessage(evt: ServiceWorkerMessageEvent) { async function onMessage(evt: ServiceWorkerMessageEvent) {
let message = JSON.parse(evt.data) let message = JSON.parse(evt.data)
let clientId = (evt.source as any).id let clientId = (evt.source as any).id
let client = await MyClient.get(clientId) let client = await MyClient.get(clientId)
@ -240,11 +246,11 @@ class MyServiceWorker {
} }
// onPush is called on push events and requires the payload to contain JSON information about the notification. // onPush is called on push events and requires the payload to contain JSON information about the notification.
onPush(evt: PushEvent) { function onPush(evt: PushEvent) {
var payload = evt.data ? evt.data.json() : {} var payload = evt.data ? evt.data.json() : {}
// Notify all clients about the new notification so they can update their notification counter // Notify all clients about the new notification so they can update their notification counter
this.broadcast({ broadcast({
type: "new notification" type: "new notification"
}) })
@ -253,11 +259,11 @@ class MyServiceWorker {
body: payload.message, body: payload.message,
icon: payload.icon, icon: payload.icon,
data: payload.link, data: payload.link,
badge: "https://media.notify.moe/images/brand/64.png" badge: "https://media.notify.moe/images/brand/256.png"
}) })
} }
onPushSubscriptionChange(evt: any) { function onPushSubscriptionChange(evt: any) {
return self.registration.pushManager.subscribe(evt.oldSubscription.options) return self.registration.pushManager.subscribe(evt.oldSubscription.options)
.then(async subscription => { .then(async subscription => {
console.log("send subscription to server...") console.log("send subscription to server...")
@ -294,7 +300,7 @@ class MyServiceWorker {
} }
// onNotificationClick is called when the user clicks on a notification. // onNotificationClick is called when the user clicks on a notification.
onNotificationClick(evt: NotificationEvent) { function onNotificationClick(evt: NotificationEvent) {
let notification = evt.notification let notification = evt.notification
notification.close() notification.close()
@ -317,7 +323,7 @@ class MyServiceWorker {
} }
// Broadcast sends a message to all clients (open tabs etc.) // Broadcast sends a message to all clients (open tabs etc.)
broadcast(msg: object) { function broadcast(msg: object) {
const msgText = JSON.stringify(msg) const msgText = JSON.stringify(msg)
self.clients.matchAll().then(function(clientList) { self.clients.matchAll().then(function(clientList) {
@ -328,7 +334,7 @@ class MyServiceWorker {
} }
// installCache is called when the service worker is installed for the first time. // installCache is called when the service worker is installed for the first time.
async installCache() { async function installCache() {
let urls = [ let urls = [
"/", "/",
"/scripts", "/scripts",
@ -345,7 +351,7 @@ class MyServiceWorker {
mode: "cors" mode: "cors"
}) })
let promise = fetch(request).then(response => this.cache.store(request, response)) let promise = fetch(request).then(response => cache.store(request, response))
promises.push(promise) promises.push(promise)
} }
@ -354,7 +360,7 @@ class MyServiceWorker {
// Serve network first. // Serve network first.
// Fall back to cache. // Fall back to cache.
async networkFirst(request: Request, network: Promise<Response>, onResponse: (r: Response) => Response): Promise<Response> { async function networkFirst(request: Request, network: Promise<Response>, onResponse: (r: Response) => Response): Promise<Response> {
let response: Response | null let response: Response | null
try { try {
@ -364,7 +370,7 @@ class MyServiceWorker {
// console.log("Network MISS:", request.url, error) // console.log("Network MISS:", request.url, error)
try { try {
response = await this.cache.serve(request) response = await cache.serve(request)
} catch(error) { } catch(error) {
return Promise.reject(error) return Promise.reject(error)
} }
@ -375,11 +381,11 @@ class MyServiceWorker {
// Serve cache first. // Serve cache first.
// Fall back to network. // Fall back to network.
async cacheFirst(request: Request, network: Promise<Response>, onResponse: (r: Response) => Response): Promise<Response> { async function cacheFirst(request: Request, network: Promise<Response>, onResponse: (r: Response) => Response): Promise<Response> {
let response: Response | null let response: Response | null
try { try {
response = await this.cache.serve(request) response = await cache.serve(request)
// console.log("Cache HIT:", request.url) // console.log("Cache HIT:", request.url)
} catch(error) { } catch(error) {
// console.log("Cache MISS:", request.url, error) // console.log("Cache MISS:", request.url, error)
@ -393,41 +399,6 @@ class MyServiceWorker {
return onResponse(response) return onResponse(response)
} }
}
// MyCache is the cache used by the service worker.
class MyCache {
version: string
constructor(version: string) {
this.version = version
}
clear() {
return caches.delete(this.version)
}
async store(request: RequestInfo, response: Response) {
try {
// This can fail if the disk space quota has been exceeded.
let cache = await caches.open(this.version)
await cache.put(request, response)
} catch(err) {
console.log("Disk quota exceeded, can't store in cache:", request, response, err)
}
}
async serve(request: RequestInfo): Promise<Response> {
let cache = await caches.open(this.version)
let matching = await cache.match(request)
if(matching) {
return matching
}
return Promise.reject("no-match")
}
}
// MyClient represents a single tab in the browser. // MyClient represents a single tab in the browser.
class MyClient { class MyClient {
@ -462,7 +433,7 @@ class MyClient {
case "broadcast": case "broadcast":
message.type = message.realType message.type = message.realType
delete message.realType delete message.realType
serviceWorker.broadcast(message) broadcast(message)
break break
} }
} }
@ -488,5 +459,11 @@ function trimPrefix(text, prefix) {
return text return text
} }
// Initialize the service worker // Register event listeners
const serviceWorker = new MyServiceWorker() self.addEventListener("install", (evt: InstallEvent) => evt.waitUntil(onInstall(evt)))
self.addEventListener("activate", (evt: any) => evt.waitUntil(onActivate(evt)))
self.addEventListener("fetch", (evt: FetchEvent) => evt.waitUntil(onRequest(evt)))
self.addEventListener("message", (evt: any) => evt.waitUntil(onMessage(evt)))
self.addEventListener("push", (evt: PushEvent) => evt.waitUntil(onPush(evt)))
self.addEventListener("pushsubscriptionchange", (evt: any) => evt.waitUntil(onPushSubscriptionChange(evt)))
self.addEventListener("notificationclick", (evt: NotificationEvent) => evt.waitUntil(onNotificationClick(evt)))