Files
blog/write-server/nginx/sw.js
T
2026-06-21 23:28:31 +08:00

43 lines
1.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;
}
});