douyinWEB/frontend/public/sw.js
eric 472cef16de fix(pwa): clearer Android install feedback + harden SW precache
Explain app-drawer vs home screen; show manual Chrome menu steps; avoid SW install fail on auth redirect.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 07:53:31 -05:00

54 lines
1.7 KiB
JavaScript

/* Minimal service worker — enables installability; network-first for app/API. */
const CACHE = "dylive-shell-v2";
const PRECACHE = ["/manifest.webmanifest", "/icon-192.png", "/icon-512.png", "/apple-touch-icon.png"];
self.addEventListener("install", (event) => {
event.waitUntil(
(async () => {
const cache = await caches.open(CACHE);
// Prefer one-by-one so a single miss (e.g. auth redirect on "/") does not fail SW install.
await Promise.all(
PRECACHE.map((url) => cache.add(url).catch(() => undefined)),
);
await self.skipWaiting();
})(),
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))),
).then(() => self.clients.claim()),
);
});
self.addEventListener("fetch", (event) => {
const req = event.request;
if (req.method !== "GET") return;
const url = new URL(req.url);
if (url.origin !== self.location.origin) return;
// Never cache API / auth / SSE
if (url.pathname.startsWith("/api/") || url.pathname.includes("event")) return;
event.respondWith(
fetch(req)
.then((res) => {
const copy = res.clone();
if (res.ok && (url.pathname.startsWith("/_next/static/") || PRECACHE.includes(url.pathname))) {
caches.open(CACHE).then((cache) => cache.put(req, copy)).catch(() => {});
}
return res;
})
.catch(async () => {
const hit = await caches.match(req);
if (hit) return hit;
if (req.mode === "navigate") {
const home = await caches.match("/");
if (home) return home;
}
throw new Error("offline");
}),
);
});