-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsw.js
78 lines (73 loc) · 2.71 KB
/
sw.js
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
const CACHE_NAME = "offline-demo";
const STABLE_EJS_VER = "4.2.1";
const OFFLINE_FILES = [
"index.html",
"404.html",
"favicon.ico",
"manifest.json",
"img/icon.png",
"img/logo.png",
"img/logo-light.png",
"img/screenshot.png",
"img/mobile_screenshot.png",
"https://cdn.emulatorjs.org/versions.json",
// Only cache stable assets offline...?
"https://cdn.emulatorjs.org/stable/data/loader.js",
"https://cdn.emulatorjs.org/stable/data/emulator.min.js",
"https://cdn.emulatorjs.org/stable/data/emulator.min.css",
"https://cdn.emulatorjs.org/stable/data/compression/extract7z.js",
"https://cdn.emulatorjs.org/stable/data/compression/extractzip.js",
"https://cdn.emulatorjs.org/stable/data/compression/libunrar.js",
"https://cdn.emulatorjs.org/stable/data/compression/libunrar.wasm"
];
self.addEventListener("install", (event) => {
event.waitUntil(
(async () => {
const cache = await caches.open(CACHE_NAME);
await cache.addAll(OFFLINE_FILES);
})()
);
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
self.clients.claim();
});
function getCacheUrl(url) {
if (url === "/") {
return "index.html";
} else if (url === "/versions") {
return "https://cdn.emulatorjs.org/versions.json";
} else if (url.startsWith("/")) {
return url.slice(1);
}
return url.replace(STABLE_EJS_VER, "stable");
}
self.addEventListener("fetch", (event) => {
event.respondWith(
(async () => {
const requestURL = new URL(event.request.url);
let url = (requestURL.hostname === "cdn.emulatorjs.org") ? event.request.url : requestURL.pathname;
const cache = await caches.open(CACHE_NAME);
if (requestURL.hostname === "cdn.emulatorjs.org" && !OFFLINE_FILES.includes(event.request.url.replace(STABLE_EJS_VER, "stable")) && !event.request.url.includes("reports/")) {
return await fetch(event.request);
}
try {
const req = (url === "/versions") ? "https://cdn.emulatorjs.org/versions.json" : event.request;
const res = await fetch(req);
if (!res.ok && res.status !== 0) {
throw new Error('status code not ok');
}
cache.put(getCacheUrl(url), res.clone());
return res;
} catch(e) {
console.log("error:", e);
url = getCacheUrl(url);
let rv = await cache.match(url);
if (rv === undefined) {
rv = await cache.match("404.html");
}
return rv;
}
})()
);
});