106 lines
2.4 KiB
TypeScript
Raw Normal View History

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 {
2017-10-20 00:43:02 +00:00
arn: AnimeNotifier
uri: string
constructor(arn: AnimeNotifier, uri: string) {
this.arn = arn
this.uri = uri
}
register() {
if(!("serviceWorker" in navigator)) {
console.warn("service worker not supported, skipping registration")
2017-10-20 00:43:02 +00:00
return
}
navigator.serviceWorker.register(this.uri).then(registration => {
// registration.update()
})
navigator.serviceWorker.addEventListener("message", evt => {
this.onMessage(evt)
})
// This will send a message to the service worker that the DOM has been loaded
let sendContentLoadedEvent = () => {
if(!navigator.serviceWorker.controller) {
return
}
// A reloadContent call should never trigger another reload
if(this.arn.app.currentPath === this.arn.lastReloadContentPath) {
this.arn.lastReloadContentPath = ""
return
}
2018-04-17 23:08:04 +00:00
let url = ""
2017-10-20 00:43:02 +00:00
// If mainPageLoaded is set, it means every single request is now an AJAX request for the /_/ prefixed page
if(this.arn.mainPageLoaded) {
2018-04-17 23:08:04 +00:00
url = window.location.origin + "/_" + window.location.pathname
2017-10-20 00:43:02 +00:00
} else {
this.arn.mainPageLoaded = true
2018-04-17 23:08:04 +00:00
url = window.location.href
2017-10-20 00:43:02 +00:00
}
2018-02-28 15:26:49 +00:00
// console.log("checking for updates:", message.url)
2017-10-20 00:43:02 +00:00
2018-04-17 23:08:04 +00:00
this.postMessage({
type: "loaded",
2018-11-16 07:46:56 +00:00
url
2018-04-17 23:08:04 +00:00
})
2017-10-20 00:43:02 +00:00
}
// For future loaded events
document.addEventListener("DOMContentLoaded", sendContentLoadedEvent)
// If the page is loaded already, send the loaded event right now.
if(document.readyState !== "loading") {
sendContentLoadedEvent()
}
}
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
}
2018-09-27 04:54:02 +00:00
onMessage(evt: MessageEvent) {
2018-11-07 08:05:13 +00:00
let message = JSON.parse(evt.data)
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
// case "new content":
// if(message.url.includes("/_/")) {
// // Content reload
// this.arn.contentLoadedActions.then(() => {
// this.arn.reloadContent(true)
// })
// } else {
// // Full page reload
// this.arn.contentLoadedActions.then(() => {
// this.arn.reloadPage()
// })
// }
// break
// case "offline":
// this.arn.statusMessage.showError("You are viewing an offline version of the site now.")
// break
}
2017-10-20 00:43:02 +00:00
}
}