-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserviceworker.js
More file actions
250 lines (238 loc) · 7.04 KB
/
serviceworker.js
File metadata and controls
250 lines (238 loc) · 7.04 KB
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
let isSubscribed = false;
//Service worker register
if ("serviceWorker" in navigator) {
window.addEventListener("load", function () {
navigator.serviceWorker.register("/sw.js").then(
function (registration) {
// Registration was successful
console.log(
"ServiceWorker registration successful with scope: ",
registration.scope
);
},
function (err) {
// registration failed :(
console.log("ServiceWorker registration failed: ", err);
}
);
});
}
//Seller Subscription
const applicationServerKey =
"BI5PjOjLjyaQSOsad3tuzM8c5DsxN7GwYn4GeJk-Kig3WVFSfBtOm5E2_l-Y2GaGsvuC0qM7KaalgJse8HmRH78";
const runPushCheck = () => {
//Check support
if (!("serviceWorker" in navigator)) {
console.warn("Sorry: browser doesn't support servieworker");
changePushButtonState("disable");
return;
}
if (!("PushManager" in window)) {
console.warn("Sorry: browser doesn't support webpush");
changePushButtonState("disable");
return;
}
if (!("showNotification" in ServiceWorkerRegistration.prototype)) {
console.warn("Sorry: browser doesn't support showing webpush");
changePushButtonState("disable");
return;
}
// Check the current Notification permission.
if (Notification.permission === "denied") {
console.warn(
"Sorry: You've disabled notification permission manually, you may re-enable them in browser settings"
);
isSubscribed = false;
changePushButtonValue("off");
return;
}
if (Notification.permission === "granted") {
//make sure if granted but unsubscribed
navigator.serviceWorker
.getRegistration()
.then((registration) => {
if (!registration) {
isSubscribed = false;
changePushButtonValue("off");
return;
}
return registration.pushManager.getSubscription();
})
.then((subscription) => {
if (!subscription) {
isSubscribed = false;
changePushButtonValue("off");
return;
}
isSubscribed = true;
changePushButtonValue("on");
//TODO Maybe PUT request to update subscription? Or check if this subscription endpoint is actually in database
return;
})
.catch((err) => {
return;
});
}
};
function push_subscribe() {
changePushButtonState("disable");
return checkNotificationPermission()
.then(() => navigator.serviceWorker.ready)
.then((serviceWorkerRegistration) =>
serviceWorkerRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(applicationServerKey),
})
)
.then((subscription) => {
// Success: Send Subscription to server
return subscribeToServer(subscription);
})
.then((subscription) => subscription && changePushButtonState("enabled")) // update UI
.catch((e) => {
//Error: show relevent error msg
if (Notification.permission === "denied") {
canceledByUserNotice();
} else {
canceledByUnknownNotice();
}
});
}
async function push_unsubscribe() {
changePushButtonState("disable");
try {
const registration = await navigator.serviceWorker.ready;
const subscription = await registration.pushManager.getSubscription();
if (!subscription) {
//No subscription registered
noticeAndOffBtn("We did not detect previous registration in browser");
return;
}
const serverUnsubscription = await unsubscribeToServer(subscription);
if (serverUnsubscription.success) {
await subscription.unsubscribe();
}
} catch (err) {
noticeAndOnBtn("Error unsubscribing, please try again");
}
}
//Helpers
function checkNotificationPermission() {
return new Promise((resolve, reject) => {
if (Notification.permission === "denied") {
return reject(new Error("Push messages are blocked."));
}
if (Notification.permission === "granted") {
return resolve();
}
if (Notification.permission === "default") {
return Notification.requestPermission().then((result) => {
if (result !== "granted") {
reject(new Error("Bad permission result"));
}
resolve();
});
}
});
}
function changePushButtonState(state) {
//state = (string)enable||disable
$("#push_switcher").bootstrapToggle(state);
}
function changePushButtonValue(value) {
//value = (string)on||off
changePushButtonState("enable");
$("#push_switcher").bootstrapToggle(value);
}
function canceledByUserNotice() {
$(".push-content-modal").text(
"Sorry: You've disabled notification permission manually, you may re-enable them in browser settings"
);
$("#push-result-modal").modal("show");
changePushButtonValue("off");
}
function canceledByUnknownNotice() {
$(".push-content-modal").text("Unknwon error: Please refresh and try again");
$("#push-result-modal").modal("show");
changePushButtonValue("off");
}
function noticeAndOffBtn(msg) {
$(".push-content-modal").text(msg);
$("#push-result-modal").modal("show");
isSubscribed = false;
changePushButtonValue("off");
}
function noticeAndOnBtn(msg) {
$(".push-content-modal").text(msg);
$("#push-result-modal").modal("show");
isSubscribed = true;
changePushButtonValue("on");
}
function urlBase64ToUint8Array(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;
}
//Requests
function subscribeToServer(subscription) {
$.ajax({
url: "index.php?route=api/webpush/subscribe",
type: "POST",
cache: false,
data: { subscription: JSON.stringify(subscription) },
dataType: "json",
beforeSend: function () {
changePushButtonState("disable");
},
complete: function () {
changePushButtonState("enable");
},
success: function (json) {
if (json["error"]) {
noticeAndOffBtn(json["error"]);
return;
}
isSubscribed = true;
},
error: function (err) {
noticeAndOffBtn("Network Error: Please refresh and try again");
// console.log(err);
},
});
}
function unsubscribeToServer(subscription) {
return $.ajax({
url: "index.php?route=api/webpush/unsubscribe",
type: "POST",
cache: false,
data: { subscription: JSON.stringify(subscription) },
dataType: "json",
beforeSend: function () {
changePushButtonState("disable");
},
complete: function () {
changePushButtonState("enable");
},
success: function (json) {
if (json["error"]) {
noticeAndOnBtn(json["error"]);
return;
}
if (json["success"]) {
noticeAndOffBtn(json["success"]);
return;
}
},
error: function (err) {
noticeAndOffBtn("Network Error: Please refresh and try again");
// console.log(err);
},
});
}