-
Notifications
You must be signed in to change notification settings - Fork 3
/
sw.js
138 lines (130 loc) · 4.47 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
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
136
137
138
'use strict';
let staticName = `static-cache-2`;
let dynamicName = 'dynamic-cache-1';
let listOfStaticFiles = [
'/',
'/index.html',
'/404.html',
'/css/app.css',
'/js/app.js',
'/favicon.ico',
'/img/icon-144x144.png',
'/img/icon-192x192.png',
'/img/icon-512x512.png',
'/img/offline.png',
'/manifest.json',
'https://picsum.photos/id/1/300/300',
'https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css',
'https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js',
'https://fonts.googleapis.com/icon?family=Material+Icons',
'https://fonts.gstatic.com/s/materialicons/v50/flUhRq6tzZclQEJ-Vdg-IuiaDsNcIhQ8tQ.woff2',
];
//we can add the materialize css and js too
let baseURL = null;
//listen for SW events
self.addEventListener('install', onInstall); // installing the service worker
self.addEventListener('activate', onActivate); // activating the service worker after install
self.addEventListener('message', onMessage); //isOnline, isLoggedIn
self.addEventListener('fetch', onFetch); //request from webpage
function onInstall(ev) {
ev.waitUntil(
caches.open(staticName).then((cache) => {
console.log('saving all the static files');
cache.addAll(listOfStaticFiles);
})
);
//don't wait for the old SW to stop working before installing
//self.skipWaiting();
console.log(`Service Worker installed`);
}
function onActivate(ev) {
ev.waitUntil(
caches.keys().then((keys) => {
//console.log(keys);
return Promise.all(
keys
.filter((key) => key !== staticName && key !== dynamicName)
.map((key) => caches.delete(key))
);
})
);
console.log(`Service Worker activated`);
}
function onFetch(ev) {
//the webpage has asked for a resource
//ev.request is the request for the resource
console.log(`Webpage asked for ${ev.request.url}`);
ev.respondWith(
caches
.match(ev.request)
.then((cacheRes) => {
//we are checking ALL the static and dynamic caches
//cacheRes could be "undefined"
return (
cacheRes ||
fetch(ev.request).then((fetchRes) => {
//url is the full URL, not just the path
console.log('was not in cache', ev.request);
if (fetchRes.status != 404) {
return caches.open(dynamicName).then((cache) => {
if (
ev.request.url.indexOf('giftr.mad9124.rocks/') == -1 ||
(ev.request.url.indexOf('giftr.mad9124.rocks/api/people') >
-1 &&
ev.request.method == 'GET')
) {
//cache the request if it does NOT come from our API
//OR it comes from our API and uses 'GET'
console.log('PUTTING IN DYNAMIC', ev.request.url);
}
//need to use clone if we are going to return the file to the browser
cache.put(ev.request.url, fetchRes.clone());
//check the headers for a content-type for custom responses
return fetchRes;
});
} else {
//failed to fetch
console.log('fetch failing', fetchRes);
throw new Error('failed to fetch');
}
})
);
})
.catch((err) => {
//offline handler
console.warn(err); //failed to fetch
let url = new URL(ev.request.url);
console.log(url);
if (url.hostname == 'picsum.photos') {
//return our image with id 1 from our static cache if we are offline
return caches.match('https://picsum.photos/id/1/300/300');
}
if (url.pathname.indexOf('.html') > -1) {
return caches.match('/404.html');
}
return caches.match('/index.html');
//handle other stuff...
})
);
}
async function sendMessage(msg) {
//send the message to all clients (tabs) using this service worker
var allClients = await clients.matchAll({ includeUncontrolled: true });
return Promise.all(
allClients.map(function sendTo(client) {
var chan = new MessageChannel();
chan.port1.onmessage = onMessage;
return client.postMessage(msg, [chan.port2]);
})
);
}
function onMessage({ data }) {
//received a message from the webpage
//probably just updating our online status
if ('statusUpdate' in data) {
console.log(`Service Worker receiving message ${data}`);
}
if ('baseURL' in data) {
baseURL = data.baseURL;
}
}