implement web push
This commit is contained in:
58
web/sw.js
58
web/sw.js
@@ -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)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
Reference in New Issue
Block a user