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