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) => {
let request = new XMLHttpRequest()
request.timeout = 20000
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.onload = () => {

View File

@ -32,60 +32,72 @@
// E-Tags that we served for a given URL
// const ETAGS = new Map<string, string>()
// MyServiceWorker is the process that controls all the tabs in a browser.
class MyServiceWorker {
cache: MyCache
reloads: Map<string, Promise<Response>>
excludeCache: Set<string>
// MyCache is the cache used by the service worker.
class MyCache {
version: string
constructor() {
this.cache = new MyCache("v-6")
this.reloads = new Map<string, Promise<Response>>()
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")
}
}
// 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
// served cache-first and instead serve them via a network request.
// Note that the service worker URL is automatically excluded from fetch events
// and therefore doesn't need to be added here.
this.excludeCache = new Set<string>([
// API requests
"/api/",
// PayPal stuff
"/paypal/",
// List imports
"/import/",
// Infinite scrolling
"/from/",
// Chrome extension
"chrome-extension",
let excludeCache = new Set<string>([
"/api/", // API requests
"/paypal/", // PayPal stuff
"/import/", // List imports
"/from/", // Infinite scrolling
"chrome-extension", // Chrome extension
// 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)))
self.addEventListener("activate", (evt: any) => evt.waitUntil(this.onActivate(evt)))
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) {
// onInstall
async function onInstall(evt: InstallEvent) {
console.log("service worker install")
await self.skipWaiting()
await this.installCache()
await installCache()
}
onActivate(evt: any) {
// onActivate
function onActivate(evt: any) {
console.log("service worker activate")
// 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 => {
return Promise.all(keyList.map(key => {
@ -107,7 +119,7 @@ class MyServiceWorker {
// onRequest intercepts all browser requests.
// Simply returning, without calling evt.respondWith(),
// will let the browser deal with the request normally.
async onRequest(evt: FetchEvent) {
async function onRequest(evt: FetchEvent) {
let request = evt.request as Request
// If it's not a GET request, fetch it normally.
@ -117,12 +129,6 @@ class MyServiceWorker {
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.
// We are defaulting to the normal browser handler here
// so we can see the HTTP 206 partial responses in DevTools
@ -131,7 +137,7 @@ class MyServiceWorker {
return
}
return evt.respondWith(fetch(request))
return //evt.respondWith(fetch(request))
// // Exclude certain URLs from being cached.
// 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).
async onMessage(evt: ServiceWorkerMessageEvent) {
async function onMessage(evt: ServiceWorkerMessageEvent) {
let message = JSON.parse(evt.data)
let clientId = (evt.source as any).id
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(evt: PushEvent) {
function onPush(evt: PushEvent) {
var payload = evt.data ? evt.data.json() : {}
// Notify all clients about the new notification so they can update their notification counter
this.broadcast({
broadcast({
type: "new notification"
})
@ -253,11 +259,11 @@ class MyServiceWorker {
body: payload.message,
icon: payload.icon,
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)
.then(async subscription => {
console.log("send subscription to server...")
@ -294,7 +300,7 @@ class MyServiceWorker {
}
// onNotificationClick is called when the user clicks on a notification.
onNotificationClick(evt: NotificationEvent) {
function onNotificationClick(evt: NotificationEvent) {
let notification = evt.notification
notification.close()
@ -317,7 +323,7 @@ class MyServiceWorker {
}
// Broadcast sends a message to all clients (open tabs etc.)
broadcast(msg: object) {
function broadcast(msg: object) {
const msgText = JSON.stringify(msg)
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.
async installCache() {
async function installCache() {
let urls = [
"/",
"/scripts",
@ -345,7 +351,7 @@ class MyServiceWorker {
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)
}
@ -354,7 +360,7 @@ class MyServiceWorker {
// Serve network first.
// 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
try {
@ -364,7 +370,7 @@ class MyServiceWorker {
// console.log("Network MISS:", request.url, error)
try {
response = await this.cache.serve(request)
response = await cache.serve(request)
} catch(error) {
return Promise.reject(error)
}
@ -375,11 +381,11 @@ class MyServiceWorker {
// Serve cache first.
// 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
try {
response = await this.cache.serve(request)
response = await cache.serve(request)
// console.log("Cache HIT:", request.url)
} catch(error) {
// console.log("Cache MISS:", request.url, error)
@ -393,41 +399,6 @@ class MyServiceWorker {
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.
class MyClient {
@ -462,7 +433,7 @@ class MyClient {
case "broadcast":
message.type = message.realType
delete message.realType
serviceWorker.broadcast(message)
broadcast(message)
break
}
}
@ -488,5 +459,11 @@ function trimPrefix(text, prefix) {
return text
}
// Initialize the service worker
const serviceWorker = new MyServiceWorker()
// Register event listeners
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)))