diff --git a/src/libs/getSWR.ts b/src/libs/getSWR.ts index 312edf9..0dad9a2 100644 --- a/src/libs/getSWR.ts +++ b/src/libs/getSWR.ts @@ -7,6 +7,7 @@ const SW = import.meta.env.MODE === 'production' ? '/notice-book/sw.js' : '/src/ let swr: ServiceWorkerRegistration export async function getSWR() { + swr.active?.postMessage('close') return swr.active || swr.installing } @@ -14,12 +15,18 @@ export async function SWR() { swr = await navigator.serviceWorker.getRegistration(SW) as ServiceWorkerRegistration if (swr) { - await swr.unregister() + await unregisterSW() } swr = await navigator.serviceWorker.register(SW, { - type: 'module' + type: 'module', + scope: `./?${Date.now()}` }).then(serviceWorkerRegistration => { return serviceWorkerRegistration }) } + +export async function unregisterSW() { + swr.active?.postMessage('close') + await swr.unregister() +} \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index 4a6b15a..134d874 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,7 +1,7 @@ import { createApp } from 'vue' import './style.css' import App from './App.vue' -import { SWR, getSWR, initData, initNotification } from './libs' +import { SWR, getSWR, initData, initNotification, unregisterSW } from './libs' const app = createApp(App) @@ -13,4 +13,6 @@ async function init() { initNotification() } -init() \ No newline at end of file +init() + +window.onunload = unregisterSW \ No newline at end of file diff --git a/src/sw.ts b/src/sw.ts index d21e905..e3d178b 100644 --- a/src/sw.ts +++ b/src/sw.ts @@ -8,7 +8,7 @@ interface NoticeEvent extends ExtendableMessageEvent { data: { key: 'tmrList' | 'todayList', value: NoticeType[] - } + } | 'close' } self.skipWaiting() @@ -32,20 +32,26 @@ const noticePool: { todayList: [], tmrList: [] } +let interval: number self.addEventListener('message', (e: NoticeEvent) => { - const notices = e.data - noticePool[notices.key] = [] - notices.value.forEach(item => { - if (getTime(item.hour, item.minute) > Date.now()) { - noticePool[notices.key].push(item) - } - }) + if (e.data != 'close') { + const notices = e.data + noticePool[notices.key] = [] + notices.value.forEach(item => { + if (getTime(item.hour, item.minute) > Date.now()) { + noticePool[notices.key].push(item) + } + }) + } else { + clearInterval(interval) + } }) + self.addEventListener('install', () => { let lastDate = new Date() - setInterval(() => { + interval = setInterval(() => { const date = new Date() const todayTodo = noticePool.todayList.reduce((prev, cur) => `\n--${prev + cur.noticeName}`, '') console.log(`%cNotice book: Today is ${ lastDate.getMonth() + 1 } / ${ lastDate.getDate() } \n There have ${ noticePool.todayList.length } notices wait for posting today: ${ todayTodo }`, 'color: green')