35 lines
1.1 KiB
JavaScript
35 lines
1.1 KiB
JavaScript
async function poll(config) {
|
|
try {
|
|
const response = await fetch(config.url, {
|
|
method: 'GET',
|
|
headers: {
|
|
Authorization: config.token,
|
|
Accept: 'application/json',
|
|
'Cache-Control': 'no-cache, no-store, must-revalidate',
|
|
Pragma: 'no-cache'
|
|
},
|
|
credentials: 'include',
|
|
// 待办必须始终读取后端最新状态,禁止浏览器复用 GET 缓存。
|
|
cache: 'no-store'
|
|
})
|
|
if (!response.ok) throw new Error(`HTTP ${response.status}`)
|
|
const result = await response.json()
|
|
if (result.code !== 200) throw new Error(result.msg || '待办查询失败')
|
|
self.postMessage({ type: 'todos', todos: result.data || [] })
|
|
} catch (error) {
|
|
self.postMessage({ type: 'error', message: error.message })
|
|
}
|
|
}
|
|
|
|
self.onmessage = event => {
|
|
const config = event.data || {}
|
|
if (config.command === 'stop') {
|
|
return
|
|
}
|
|
// 不在 Worker 内部使用定时器:仅由页面上的真实用户操作触发检查。
|
|
// 这样页面挂在后台或用户长时间不操作时,不会持续请求待办接口。
|
|
if (config.command === 'check') {
|
|
poll(config)
|
|
}
|
|
}
|