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
export default async () => {
const status: HTMLElement = document.querySelector("#status");
const button: HTMLButtonElement = document.querySelector("#button");
if (status === null || button === null) {
throw new Error("could not find required elements");
}
navigator.serviceWorker.register("/serviceWorker.js");
const registration = await navigator.serviceWorker.ready;
if (!("pushManager" in registration)) {
status.textContent = "No notification support, try installing PWA?";
button.hidden = true;
return;
}
let clientSubscription = await registration.pushManager.getSubscription();
let serverSubscription = await (await fetch("/subscription")).json();
if (clientSubscription === null) {
if (serverSubscription !== null) {
status.textContent = "Another device is currently receiving notifications.";
}
button.textContent = "Subscribe";
} else {
if (serverSubscription === null) {
status.textContent = "Server was reset.";
clientSubscription.unsubscribe();
clientSubscription = null;
button.textContent = "Subscribe";
} else if (
clientSubscription?.toJSON().keys.p256dh === serverSubscription
) {
status.textContent = "This device is subscribed to notifications.";
button.textContent = "Unsubscribe";
} else {
status.textContent = "Another device is currently receiving notifications.";
clientSubscription.unsubscribe();
clientSubscription = null;
button.textContent = "Subscribe";
}
}
button.disabled = false;
button.addEventListener(
"click",
async () => {
button.disabled = true;
button.textContent = await (
await fetch("/subscription", {
method: "PUT",
body: JSON.stringify(
clientSubscription
? (await clientSubscription.unsubscribe(), null)
: await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: await (
await fetch("/vapidPublicKey")
).text(),
}),
),
})
).text();
},
{ once: true },
);
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
August 30, 2024