-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
91 lines (86 loc) · 2.59 KB
/
Copy pathsw.js
File metadata and controls
91 lines (86 loc) · 2.59 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
81
82
83
84
85
86
87
88
89
90
91
/* Service Worker for WebOCR.
*
* Strategy: stale-while-revalidate for same-origin static assets.
* The app shell is precached on install. On every subsequent fetch, the
* cached response is served immediately for speed, and a network fetch runs
* in the background. If the network response differs from the cached one
* (compared byte-for-byte), the cache is updated and the service worker posts
* an UPDATE_AVAILABLE message to every client so they can prompt the user to
* reload and pick up the new version.
*
* Cross-origin requests (e.g. Tesseract.js from jsDelivr, language data) are
* ignored by this service worker and always go straight to the network/CDN.
*/
const CACHE_NAME = "webocr-1783977043";
const V = "1783977043";
const CORE_ASSETS = [
"./",
"./index.html",
"./favicon.svg",
"./css/styles.css?v=" + V,
"./js/languages.js?v=" + V,
"./js/db.js?v=" + V,
"./js/ocr.js?v=" + V,
"./js/app.js?v=" + V,
];
self.addEventListener("install", (event) => {
event.waitUntil(
(async () => {
const cache = await caches.open(CACHE_NAME);
await cache.addAll(CORE_ASSETS);
await self.skipWaiting();
})()
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
(async () => {
const keys = await caches.keys();
await Promise.all(
keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k))
);
await self.clients.claim();
})()
);
});
self.addEventListener("fetch", (event) => {
const req = event.request;
if (req.method !== "GET") return;
const url = new URL(req.url);
if (url.origin !== self.location.origin) return;
event.respondWith(
(async () => {
const cache = await caches.open(CACHE_NAME);
const cached = await cache.match(req);
const networkFetch = fetch(req)
.then(async (res) => {
if (res && res.ok) {
if (cached) {
const [oldText, newText] = await Promise.all([
cached.clone().text(),
res.clone().text(),
]);
if (oldText !== newText) {
await cache.put(req, res.clone());
notifyClients();
}
} else {
await cache.put(req, res.clone());
}
}
return res;
})
.catch(() => cached);
return cached || networkFetch;
})()
);
});
async function notifyClients() {
const clients = await self.clients.matchAll({
includeUncontrolled: true,
type: "window",
});
for (const client of clients) {
client.postMessage({ type: "UPDATE_AVAILABLE" });
}
}