Skip to content

Commit

Permalink
fix: 修复失去sw引用问题
Browse files Browse the repository at this point in the history
  • Loading branch information
Stan-BK committed Jan 2, 2024
1 parent e068ff2 commit 20079ba
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 13 deletions.
11 changes: 9 additions & 2 deletions src/libs/getSWR.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,26 @@ 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
}

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()
}
6 changes: 4 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -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)

Expand All @@ -13,4 +13,6 @@ async function init() {
initNotification()
}

init()
init()

window.onunload = unregisterSW
24 changes: 15 additions & 9 deletions src/sw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ interface NoticeEvent extends ExtendableMessageEvent {
data: {
key: 'tmrList' | 'todayList',
value: NoticeType[]
}
} | 'close'
}

self.skipWaiting()
Expand All @@ -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')
Expand Down

0 comments on commit 20079ba

Please sign in to comment.