implement web push

This commit is contained in:
2025-05-10 13:04:39 +01:00
parent f832b95d69
commit 44d744266a
11 changed files with 559 additions and 142 deletions

View File

@@ -1,47 +1,17 @@
let ws
let shouldRetry = false
self.addEventListener('install', function (event) {
event.waitUntil(self.skipWaiting());
});
function start(location) {
shouldRetry = true
const port = self.location.port ? `:${self.location.port}` : ""
const socket = new WebSocket(`ws://${self.location.hostname}${port}/ws?location=${location}`)
socket.onopen = () => {
ws = socket
}
socket.onclose = () => {
reconnect()
}
socket.onerror = () => {
reconnect()
}
socket.onmessage = (event) => {
self.registration.showNotification("7am weather summary", {
body: event.data
})
}
}
self.addEventListener('activate', function (event) {
event.waitUntil(self.clients.claim());
});
function cancel() {
shouldRetry = false
if (ws) {
ws.close()
ws = null
self.addEventListener("push", (event) => {
if (event.data) {
event.waitUntil(
self.registration.showNotification("7am weather summary", {
body: event.data.text()
})
)
}
}
async function reconnect() {
while (shouldRetry) {
await new Promise((resolve) => {
setTimeout(resolve, 5 * 60 * 1000)
})
start(location)
}
}
self.addEventListener("message", (event) => {
if (event.data === "cancel") {
cancel()
} else {
start(event.data)
}
})
})