-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
84 lines (75 loc) · 2.44 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
79
80
81
82
83
84
const cacheVersion = 'v21';
const cacheName = 'stereo-viewer-' + cacheVersion;
const cdnPrefix = 'https://cdn.skypack.dev/';
const urlsToCache = [
"/",
"/icons/icon.svg",
"https://cdn.jsdelivr.net/npm/webxr-polyfill@latest/build/webxr-polyfill.js",
cdnPrefix + "stereo-img@1.5.0",
];
// On install, cache critical offline resources.
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(cacheName)
.then((cache) => {
console.log('Caching URLs');
return cache.addAll(urlsToCache);
})
);
});
// On activate, delete old caches
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then(function (cacheNames) {
return Promise.all(
cacheNames
.filter((name) => {
return name != cacheName;
})
.map((name) => {
return caches.delete(name);
})
);
}),
);
});
self.addEventListener('fetch', async (event) => {
if (event.request.method === 'POST') {
// Share actions send a POST requests, intercept it and redirect to /
event.respondWith((async () => {
const formData = await event.request.formData();
const files = formData.getAll('files');
console.log('Received files from Share action:', files);
const allWindowsClients = await clients.matchAll();
if(allWindowsClients.length > 0) {
console.log("Found clients to send files");
for (const client of allWindowsClients) {
client.postMessage({
files: files
});
}
} else {
console.error('No clients found to send files to');
}
return Response.redirect('/', 303);
})());
} else {
// Look for the request in the cache
// If the request is in the cache, return it
// Otherwise, fetch from the network and if .js file from CDN, store in cache
event.respondWith(
caches.open(cacheName).then((cache) => {
return cache.match(event.request).then((response) => {
return response || fetch(event.request).then((response) => {
console.log(`Fetching from network: ${event.request.url}`);
if (event.request.url.endsWith('.js') && event.request.url.startsWith(cdnPrefix)) {
console.log(`Caching ${event.request.url}`);
cache.put(event.request, response.clone());
}
return response;
});
});
})
)
}
});