45 lines
926 B
TypeScript
Raw Normal View History

2018-04-02 07:34:16 +02:00
import AnimeNotifier from "./AnimeNotifier"
2017-10-20 02:43:02 +02:00
2018-04-02 07:34:16 +02:00
export default class ServiceWorkerManager {
2019-11-18 11:04:13 +09:00
private arn: AnimeNotifier
private uri: string
2017-10-20 02:43:02 +02:00
constructor(arn: AnimeNotifier, uri: string) {
this.arn = arn
this.uri = uri
}
2019-11-18 11:04:13 +09:00
public register() {
2017-10-20 02:43:02 +02:00
if(!("serviceWorker" in navigator)) {
console.warn("service worker not supported, skipping registration")
2017-10-20 02:43:02 +02:00
return
}
2019-04-22 18:06:50 +09:00
navigator.serviceWorker.register(this.uri)
2019-11-18 11:04:13 +09:00
navigator.serviceWorker.addEventListener("message", evt => this.onMessage(evt))
2017-10-20 02:43:02 +02:00
}
2019-11-18 11:04:13 +09:00
public postMessage(message: any) {
2019-04-19 22:12:33 +09:00
const controller = navigator.serviceWorker.controller
if(!controller) {
return
}
controller.postMessage(JSON.stringify(message))
2017-10-20 02:43:02 +02:00
}
2019-11-18 11:04:13 +09:00
private onMessage(evt: MessageEvent) {
2019-11-17 18:25:14 +09:00
const message = JSON.parse(evt.data)
2018-11-07 17:05:13 +09:00
switch(message.type) {
case "new notification":
2019-04-19 22:50:52 +09:00
if(this.arn.notificationManager) {
this.arn.notificationManager.update()
}
2018-11-07 17:05:13 +09:00
break
}
2017-10-20 02:43:02 +02:00
}
2019-11-17 18:44:30 +09:00
}