-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
158 lines (133 loc) · 5.57 KB
/
app.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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
let isSubscribed = false;
let swRegistration = null;
let applicationKey = "BCWxoXJo6AfZp5T4GOAqw9XLEgU7zXbFz2zySuUjy4sAmt7ADQ-_XDCG6qQyRGAs0x7G9W9gYNLUAaMF9BMOgdo";
function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
if ('serviceWorker' in navigator && 'PushManager' in window) {
console.log('Service Worker and Push is supported');
window.addEventListener('load', function () {
navigator.serviceWorker.register('/sw.js')
.then(function (swReg) {
console.log('service worker registered');
swRegistration = swReg;
swRegistration.pushManager.getSubscription()
.then(function (subscription) {
isSubscribed = !(subscription === null);
if (isSubscribed) {
console.log('User is subscribed');
} else {
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlB64ToUint8Array(applicationKey)
})
.then(function (subscription) {
console.log(subscription);
console.log('User is subscribed');
saveSubscription(subscription);
isSubscribed = true;
})
.catch(function (err) {
console.log('Failed to subscribe user: ', err);
})
}
})
// When the user asks to refresh the UI, we'll need to reload the window
var preventDevToolsReloadLoop;
navigator.serviceWorker.addEventListener('controllerchange', function (event) {
// Ensure refresh is only called once.
// This works around a bug in "force update on reload".
if (preventDevToolsReloadLoop) return;
preventDevToolsReloadLoop = true;
console.log('Controller loaded');
window.location.reload();
});
onNewServiceWorker(swReg, function () {
showRefreshUI(swReg);
});
})
.catch(function (error) {
console.error('Service Worker Error', error);
});
});
} else {
console.warn('Push messaging is not supported');
}
function saveSubscription(subscription) {
let xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", "/subscribe");
xmlHttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState != 4) return;
if (xmlHttp.status != 200 && xmlHttp.status != 304) {
console.log('HTTP error ' + xmlHttp.status, null);
} else {
console.log("User subscribed to server");
}
};
xmlHttp.send(JSON.stringify(subscription));
}
// function unSubscribe(subscription) {
// let xmlHttp = new XMLHttpRequest();
// xmlHttp.open("DELETE", "/unsubscribe");
// xmlHttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
// xmlHttp.onreadystatechange = function () {
// if (xmlHttp.readyState != 4) return;
// if (xmlHttp.status != 200 && xmlHttp.status != 304) {
// console.log('HTTP error ' + xmlHttp.status, null);
// } else {
// console.log("User subscribed to server");
// }
// };
// xmlHttp.send(JSON.stringify(subscription));
// }
function showRefreshUI(subscription) {
// TODO: Display a toast or refresh UI.
// This demo creates and injects a button.
var button = document.createElement('button');
button.style.position = 'relative';
button.style.bottom = '24px';
button.style.left = '24px';
button.style.backgroundColor ="#999";
button.textContent = 'This site has updated. Please click to see changes.';
button.addEventListener('click', function () {
if (!registration.waiting) {
// Just to ensure registration.waiting is available before
// calling postMessage()
return;
}
button.disabled = true;
registration.waiting.postMessage('skipWaiting');
});
document.body.appendChild(button);
}
function onNewServiceWorker(subscription, callback) {
if (subscription.waiting) {
// SW is waiting to activate. Can occur if multiple clients open and
// one of the clients is refreshed.
return callback();
}
function listenInstalledStateChange() {
subscription.installing.addEventListener('statechange', function (event) {
if (event.target.state === 'installed') {
// A new service worker is available, inform the user
callback();
}
});
};
if (subscription.installing) {
return listenInstalledStateChange();
}
// We are currently controlled so a new SW may be found...
// Add a listener in case a new SW is found,
subscription.addEventListener('updatefound', listenInstalledStateChange);
}