-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdebugSW.js
135 lines (124 loc) · 3.6 KB
/
debugSW.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/*
Service Worker context is:
ServiceWorkerGlobalScope: clients
WindowOrWorkerGlobalScope: caches
*/
'use strict'
let CACHE_NAME = "DEBUG_CACHE";
// Logging/messaging utilities
let timestampFormat = Intl.DateTimeFormat('en-us', {
hour12: false, minute: "2-digit", second: "2-digit", fractionalSecondDigits: 3});
let oldMessages = [];
let debug = true;
let RANDOM_PREFIX = String.fromCharCode(Math.round(65+Math.random()*26));
function messageClient(msg) {
if (debug) console.log(msg);
let tsMessage = `${RANDOM_PREFIX} ${timestampFormat.format(new Date())} ${msg}`;
clients.matchAll({includeUncontrolled: true})
.then(myClients => {
if (myClients.length == 0) { // save messages for later
oldMessages.push(tsMessage);
} else {
while (oldMessages.length > 0) {
for (let c of myClients)
c.postMessage(oldMessages.shift());
}
for (let c of myClients)
c.postMessage(tsMessage);
}
})
.catch(err => { //
console.error("Error in messageClient", err);
})
}
// SW events
self.addEventListener("install", ev => {
messageClient("sw install");
// deleteOldCaches()
self.skipWaiting(); // activates new service worker immediately
// ev.waitUntil(precacheResources());
});
self.addEventListener("activate", ev => {
messageClient("sw activate");
clients.claim();
// .then(deleteOldCaches);
});
self.addEventListener("fetch", ev => {
messageClient(`sw fetch ${ev.request.url}`);
ev.respondWith(
(async () => {
let cache = await caches.open(CACHE_NAME);
let response = await cache.match(ev.request.url);
if (response) {
messageClient(`sw fetch success ${ev.request.url}`);
return response;
}
messageClient(`sw fetch miss ${ev.request.url}`);
response = await fetch(ev.request);
if (response.ok) {
messageClient(`sw fetch storing ${ev.request.url}`);
cache.put(ev.request.url, response.clone());
messageClient(`sw fetch remote success ${ev.request.url}`);
return response;
}
messageClient(`sw fetch remote failure ${ev.request.url}`);
return response;
})()
);
});
// Message handlers
async function listCache() {
let cache = await caches.open(CACHE_NAME);
let requests = await cache.keys();
let listMsg = `list cache ${CACHE_NAME}<br>`;
if (requests.length == 0)
listMsg += "empty!";
for (let r of requests)
listMsg += `${r.url}<br>`;
messageClient(listMsg);
}
async function clearCache() {
let wasDeleted = await caches.delete(CACHE_NAME);
if (wasDeleted)
messageClient(`${CACHE_NAME} deleted`);
else
messageClient(`${CACHE_NAME} not found`);
}
async function addToCache(path) {
let cache = await caches.open(CACHE_NAME);
try {
await cache.add(path);
messageClient(`success adding ${path}`);
} catch(err) {
try {
let response = await fetch(path);
if (!response.ok) {
console.error(response);
debugger;
}
} catch(err) {
messageClient(`additional error trying fetch ${path}: ${err}`);
}
messageClient(`error adding ${path}: ${err}`);
}
}
// Message events are only used for testing
self.addEventListener("message", ev => {
// if (debug)
// console.log(ev.data);
if (!ev.data) {
messageClient("got message, no data");
return;
}
if (ev.data.type == "listCache") {
listCache();
} else if (ev.data.type == "clearCache") {
clearCache();
} else if (ev.data.type == "addToCache") {
addToCache(ev.data.path);
} else {
messageClient(`unknown message ${ev.data}`);
}
if (!ev.data)
return;
});