-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathservice-worker.js
71 lines (63 loc) · 1.49 KB
/
service-worker.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
// 캐시 이름
const CACHE_NAME = "cache-v1";
// 캐싱할 파일
const FILES_TO_CACHE = [
"/",
"/index.html",
"/offline.html",
"/shareTarget.html",
];
// 상술한 파일 캐싱
self.addEventListener("install", (event) => {
event.waitUntil(
caches
.open(CACHE_NAME)
.then((cache) => cache.addAll(FILES_TO_CACHE))
);
});
// CACHE_NAME이 변경되면 오래된 캐시 삭제
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then((keyList) =>
Promise.all(
keyList.map((key) => {
if (CACHE_NAME !== key)
return caches.delete(key);
})
)
)
);
});
// 요청에 실패하면 오프라인 페이지 표시
self.addEventListener("fetch", (event) => {
if ("navigate" !== event.request.mode) return;
event.respondWith(
fetch(event.request).catch(() =>
caches
.open(CACHE_NAME)
.then((cache) =>
cache.match(
"https://dadamda.me/offline.html"
)
)
)
);
});
self.addEventListener("fetch", async (event) => {
// If this is an incoming POST request for the
// registered "action" URL, respond to it.
if (event.request.method !== "POST") {
return;
}
event.respondWith(Response.redirect(`https://dadamda.me/bookmark`));
event.waitUntil(
(async function () {
const data = await event.request.formData();
const client = await self.clients.get(
event.resultingClientId || event.clientId
);
const url = data.get("link") || data.get("description");
client.postMessage({ url });
})()
);
});