forked from mxx1111/remote-code-mobile
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-worker.js
More file actions
80 lines (71 loc) · 2.14 KB
/
Copy pathservice-worker.js
File metadata and controls
80 lines (71 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const CACHE_PREFIX = "remote-shell-mobile-";
const CACHE_NAME = `${CACHE_PREFIX}v1`;
const APP_SHELL = [
"/manifest.webmanifest",
"/icons/apple-touch-icon.png",
"/icons/favicon-32.png",
"/icons/icon-192.png",
"/icons/icon-512.png",
"/icons/maskable-512.png",
];
async function installAppShell() {
const cache = await caches.open(CACHE_NAME);
const pageResponse = await fetch("/");
if (!pageResponse.ok) {
throw new Error("Unable to cache the app shell");
}
const pageHtml = await pageResponse.clone().text();
const assetUrls = [...pageHtml.matchAll(/(?:src|href)="(\/assets\/[^"]+)"/g)]
.map((match) => match[1]);
await cache.put("/", pageResponse);
await cache.addAll([...APP_SHELL, ...assetUrls]);
}
self.addEventListener("install", (event) => {
event.waitUntil(
installAppShell()
.then(() => self.skipWaiting()),
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys()
.then((keys) => Promise.all(
keys
.filter((key) => key.startsWith(CACHE_PREFIX) && key !== CACHE_NAME)
.map((key) => caches.delete(key)),
))
.then(() => self.clients.claim()),
);
});
async function fetchAndCache(request, cacheKey = request) {
const response = await fetch(request);
if (response.ok) {
const cache = await caches.open(CACHE_NAME);
await cache.put(cacheKey, response.clone());
}
return response;
}
self.addEventListener("fetch", (event) => {
const { request } = event;
if (request.method !== "GET") return;
const url = new URL(request.url);
if (url.origin !== self.location.origin || url.pathname.startsWith("/api/")) return;
if (request.mode === "navigate") {
event.respondWith(
fetchAndCache(request, "/").catch(async () => {
const cachedPage = await caches.match(request);
return cachedPage ?? caches.match("/");
}),
);
return;
}
if (
url.pathname.startsWith("/assets/")
|| url.pathname.startsWith("/icons/")
|| url.pathname === "/manifest.webmanifest"
) {
event.respondWith(
caches.match(request).then((cached) => cached ?? fetchAndCache(request)),
);
}
});