2328
This commit is contained in:
1 parent
5d0aaea018
commit
92ecf6bba0
6 files changed
+220
-32
No files matched your search
@@ -0,0 +1,42 @@
|
||||
const CACHE = 'v1';
|
||||
const LOGIN = '/login.html';
|
||||
|
||||
self.addEventListener('install', () => self.skipWaiting());
|
||||
|
||||
self.addEventListener('activate', e => e.waitUntil(self.clients.claim()));
|
||||
|
||||
self.addEventListener('fetch', e => {
|
||||
const req = e.request;
|
||||
if (req.url.includes('/login.html') || req.url.includes('/auth/')) {
|
||||
e.respondWith(fetch(req));
|
||||
return;
|
||||
}
|
||||
|
||||
e.respondWith((async () => {
|
||||
const token = self.__auth_token;
|
||||
if (!token) {
|
||||
// 尝试从 IndexedDB/localStorage 读取(SW 中无法直接访问 localStorage)
|
||||
// 依赖客户端页面消息传递 token
|
||||
return fetch(req);
|
||||
}
|
||||
|
||||
const headers = new Headers(req.headers);
|
||||
headers.set('Authorization', 'Basic ' + token);
|
||||
const res = await fetch(new Request(req, { headers }));
|
||||
|
||||
if (res.status === 401) {
|
||||
return Response.redirect(LOGIN, 302);
|
||||
}
|
||||
return res;
|
||||
})());
|
||||
});
|
||||
|
||||
// 接收页面发来的 token
|
||||
self.addEventListener('message', e => {
|
||||
if (e.data && e.data.type === 'SET_TOKEN') {
|
||||
self.__auth_token = e.data.token;
|
||||
}
|
||||
if (e.data && e.data.type === 'CLEAR_TOKEN') {
|
||||
self.__auth_token = null;
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user