-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw-registration.js
41 lines (40 loc) · 1.26 KB
/
sw-registration.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
/*jslint browser*/
const {navigator} = window;
let workerPort;
let refreshed;
if (navigator.serviceWorker) {
navigator.serviceWorker.register("/sw.js", {scope: "/"});
navigator.serviceWorker.addEventListener("message", handleMessage);
navigator.serviceWorker.startMessages();
navigator.serviceWorker.addEventListener("controllerchange", function () {
if (!refreshed) {
window.location.reload(true);
refreshed = true;
}
});
}
function notifyWorker(data) {
if (typeof workerPort.postMessage === "function") {
workerPort.postMessage(data);
}
}
function handleMessage({data, ports}) {
if (data.statusUpdateRequest) {
workerPort = ports[0];
notifyWorker({statusUpdate: {isOnline: navigator.onLine}});
}
}
window.addEventListener("online", function () {
if (navigator.serviceWorker && navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage({
statusUpdate: {isOnline: true}
});
}
});
window.addEventListener("offline", function () {
if (navigator.serviceWorker && navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage({
statusUpdate: {isOnline: false}
});
}
});