This repository has been archived by the owner on Aug 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
54 lines (43 loc) · 1.57 KB
/
index.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
const pendingRequests = [];
document.querySelector("#form").addEventListener("submit", event => {
const values = Array.from(event.target.elements)
.filter(element => element.id)
.map(({ id, value }) => `${id}: ${value}`)
.join("\n");
event.preventDefault();
event.target.reset();
sendRequestThroughWire({ values })
.then(() => {
window.alert(`Sent the following request through the wires: \n${values}`);
})
.catch(() => {
// Noop
});
});
window.addEventListener("online", processPendingRequests);
window.addEventListener("online", hideOfflineNotification);
window.addEventListener("offline", showOfflineNotification);
navigator.serviceWorker.register("/service-worker.js")
.catch(error => console.warn(`Service worker failed to register with: ${error}`));
function sendRequestThroughWire({ values }) {
const isOnline = navigator.onLine;
return new Promise((resolve, reject) => {
if (!isOnline) {
window.alert(`You're currently offline! When you regain network connectivity your request will be sent. Putting the following request in the queue now: \n${values}`);
pendingRequests.push(() => resolve({ queued: true, values }));
return;
}
resolve();
});
}
function processPendingRequests() {
while (pendingRequests.length) {
pendingRequests.shift()();
}
}
function showOfflineNotification() {
document.querySelector("#offline-notification").setAttribute("style", "visibility: visible");
}
function hideOfflineNotification() {
document.querySelector("#offline-notification").setAttribute("style", "");
}