41 lines
1.5 KiB
JavaScript
41 lines
1.5 KiB
JavaScript
(function initializePwa() {
|
|
function notify(message) {
|
|
window.CognitiveAgentConsole?.notify?.(message);
|
|
}
|
|
|
|
function showUpdate(registration) {
|
|
const badge = document.querySelector("#pwaBadge");
|
|
if (!badge) return;
|
|
badge.hidden = false;
|
|
badge.innerHTML = '<i data-lucide="refresh-cw"></i><span>发现更新</span>';
|
|
badge.onclick = () => registration.waiting?.postMessage({ type: "SKIP_WAITING" });
|
|
window.lucide?.createIcons?.({ attrs: { "aria-hidden": "true" }, nodes: [badge] });
|
|
}
|
|
|
|
async function register() {
|
|
if (!("serviceWorker" in navigator) || !window.isSecureContext) return;
|
|
try {
|
|
const registration = await navigator.serviceWorker.register("/service-worker.js", {
|
|
scope: "/",
|
|
});
|
|
if (registration.waiting) showUpdate(registration);
|
|
registration.addEventListener("updatefound", () => {
|
|
const worker = registration.installing;
|
|
worker?.addEventListener("statechange", () => {
|
|
if (worker.state === "installed" && navigator.serviceWorker.controller) {
|
|
showUpdate(registration);
|
|
}
|
|
});
|
|
});
|
|
navigator.serviceWorker.addEventListener("controllerchange", () => window.location.reload());
|
|
navigator.serviceWorker.addEventListener("message", (event) => {
|
|
if (event.data?.type === "OFFLINE_READY") notify("PAD 离线资源已准备完成");
|
|
});
|
|
} catch (error) {
|
|
console.warn("PWA registration failed", error);
|
|
}
|
|
}
|
|
|
|
window.addEventListener("load", register, { once: true });
|
|
})();
|