Come rendere installabile un'app web?
manifest.webmanifest
{
"id": "./",
"name": "Offline Field Notes",
"short_name": "Field Notes",
"start_url": "./",
"scope": "./",
"display": "standalone",
"background_color": "#f8fafc",
"theme_color": "#153047",
"icons": [
{
"src": "./icon-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any"
},
{
"src": "./icon-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any"
}
]
}index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#153047" />
<link rel="manifest" href="./manifest.webmanifest" />
<link rel="stylesheet" href="./app.v2.css" />
<title>Offline Field Notes</title>
<script type="module" src="./app.v2.js"></script>
</head>
<body>
<main class="notes">
<h1>Offline Field Notes</h1>
<section aria-labelledby="installation-heading">
<h2 id="installation-heading">Installation</h2>
<button id="install" type="button" hidden>Install app</button>
<p>To install, use your browser menu if available.</p>
<p id="install-status" role="status"></p>
<p id="worker-status" role="status"></p>
</section>
<form id="draft-form" aria-labelledby="draft-heading">
<h2 id="draft-heading">Local draft</h2>
<label for="draft">Note</label>
<p id="draft-help">
Do not store sensitive information. Maximum 2000 characters.
</p>
<textarea
id="draft"
class="notes__draft"
rows="5"
maxlength="2000"
aria-describedby="draft-help"
disabled
></textarea>
<button id="save" type="submit" disabled>Save draft</button>
<p id="draft-status" role="status">Loading local draft.</p>
</form>
<noscript>JavaScript is required for local draft storage.</noscript>
</main>
</body>
</html>app.v2.css
:root {
color-scheme: light dark;
font-family: system-ui, sans-serif;
--space: 1rem;
--content-width: 36rem;
}
body {
margin: 0;
padding: var(--space);
}
.notes {
display: grid;
gap: var(--space);
max-inline-size: var(--content-width);
margin-inline: auto;
}
.notes__draft {
display: block;
box-sizing: border-box;
inline-size: 100%;
margin-block: 0.5rem var(--space);
padding: 0.75rem;
font: inherit;
resize: vertical;
}
button {
min-block-size: 2.75rem;
padding: 0.65rem var(--space);
font: inherit;
}
:focus-visible {
outline: 2px solid currentColor;
outline-offset: 3px;
}
Il manifest definisce nome, id, start_url, scope e icone; display: standalone richiede una finestra autonoma. Collegalo nell'HTML, usa HTTPS (localhost è un'eccezione di sviluppo) e icone PNG valide. I criteri di installazione variano; il service worker non è sempre richiesto. [1][2]
I percorsi relativi consentono il deploy in una sottocartella. Lo scope del manifest delimita la navigazione, non l'intercettazione del worker. Prepara un'icona maskable separata in produzione. Senza beforeinstallprompt mantieni nascosto il pulsante e spiega come usare il menu del browser. [3]
Inserisci tutti i file e le due icone in pwa-demo. Ogni blocco è un file separato. Dalla directory superiore esegui python3 -m http.server 8000 e apri http://localhost:8000/pwa-demo/. Adatta il link in offline.html se cambia il percorso.
Come registrare un service worker?
install.v2.js
export function setupInstallation(button, status) {
let installationEvent = null;
window.addEventListener("beforeinstallprompt", (event) => {
event.preventDefault();
installationEvent = event;
button.hidden = false;
});
button.addEventListener("click", async () => {
if (!installationEvent) {
return;
}
const event = installationEvent;
installationEvent = null;
button.hidden = true;
try {
await event.prompt();
const { outcome } = await event.userChoice;
status.textContent =
outcome === "accepted"
? "Installation accepted."
: "Installation dismissed.";
} catch (error) {
console.error("Installation prompt failed", error);
status.textContent = "Use the browser menu to install, if available.";
}
});
window.addEventListener("appinstalled", () => {
installationEvent = null;
button.hidden = true;
});
}
Il worker funziona senza DOM e può essere arrestato; le variabili globali non sono persistenti. sw.js nella cartella dell'app ha per impostazione predefinita quello scope. updateViaCache: "none" riguarda la cache HTTP degli script del worker, non Cache Storage. [4]
Il modulo install.v2.js conserva l'evento facoltativo per una sola chiamata a prompt() dopo un clic. Rifiutare l'installazione non è un errore. Un errore di registrazione non impedisce l'uso online. ready non garantisce il controllo della scheda corrente: verifica navigator.serviceWorker.controller e ricarica dopo la prima attivazione. [3][4]
Come offrire navigazione offline senza salvare risposte private?
sw.js
const scope = new URL(self.registration.scope);
const CACHE_PREFIX = `field-notes-demo:${scope.href}:`;
const CACHE_NAME = `${CACHE_PREFIX}v2`;
const home = new URL("./", scope).href;
const indexPage = new URL("./index.html", scope).href;
const offlinePage = new URL("./offline.html", scope).href;
const staticAssets = new Set(
[
"app.v2.css",
"app.v2.js",
"drafts.v2.js",
"install.v2.js",
"worker-client.v2.js",
"manifest.webmanifest",
"icon-192.png",
"icon-512.png",
].map((path) => new URL(path, scope).href),
);
async function precache() {
const cache = await caches.open(CACHE_NAME);
const urls = [home, offlinePage, ...staticAssets];
try {
const requests = urls.map((url) => {
return new Request(url, {
cache: "reload",
credentials: "omit",
redirect: "error",
});
});
await cache.addAll(requests);
} catch (error) {
await caches.delete(CACHE_NAME);
throw error;
}
}
async function removeObsoleteCaches() {
const cacheNames = await caches.keys();
const obsolete = cacheNames.filter((name) => {
return name.startsWith(CACHE_PREFIX) && name !== CACHE_NAME;
});
await Promise.all(obsolete.map((name) => caches.delete(name)));
}
self.addEventListener("install", (event) => {
event.waitUntil(precache());
});
self.addEventListener("activate", (event) => {
event.waitUntil(removeObsoleteCaches());
});
async function readCache(url) {
try {
const cache = await caches.open(CACHE_NAME);
return await cache.match(url);
} catch (error) {
console.error("Cache unavailable", error);
return undefined;
}
}
async function offlineResponse() {
const cached = await readCache(offlinePage);
const headers = { "Cache-Control": "no-store" };
if (cached) {
return new Response(cached.body, {
status: 503,
headers: { ...headers, "Content-Type": "text/html; charset=utf-8" },
});
}
return new Response("Offline", {
status: 503,
headers: { ...headers, "Content-Type": "text/plain; charset=utf-8" },
});
}
async function navigate(request, isHome) {
if (isHome) {
const cached = await readCache(home);
if (cached) {
return cached;
}
}
try {
return await fetch(request);
} catch {
return offlineResponse();
}
}
async function loadStaticAsset(request) {
const cached = await readCache(request);
return cached ?? fetch(request);
}
self.addEventListener("fetch", (event) => {
const { request } = event;
const url = new URL(request.url);
if (request.method !== "GET" || url.origin !== scope.origin) {
return;
}
if (request.mode === "navigate" && url.href.startsWith(scope.href)) {
const isHome = url.href === home || url.href === indexPage;
event.respondWith(navigate(request, isHome));
return;
}
if (staticAssets.has(url.href)) {
event.respondWith(loadStaticAsset(request));
}
});offline.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Offline</title>
</head>
<body>
<main>
<h1>This page is unavailable offline</h1>
<p>Reconnect to load it, or return to your saved draft.</p>
<a href="/pwa-demo/">Open Field Notes</a>
</main>
</body>
</html>
La demo pubblica precarica dieci risorse in una cache versionata. L'URL esatto della home (anche index.html senza parametri) e i file elencati usano cache-first. Si evita così di mescolare HTML nuovo e risorse precedenti. Le altre navigazioni nello scope usano network-first; un errore di rete restituisce la pagina offline con HTTP 503. Le risposte HTTP 404 e 500 della rete sono conservate. Una risorsa mancante impedisce di preparare la nuova versione. [4][5][10]
Non intercettare POST, origini esterne o API sconosciute. Cache Storage non applica automaticamente le direttive HTTP quando scrivi esplicitamente. Usa una lista di risorse pubbliche e progetta isolamento e rimozione per contenuti autenticati. In produzione stabilisci timeout e requisiti di freschezza. [5][6]
Il precaricamento usa credentials: "omit" e rifiuta i redirect, ma richiede risorse realmente pubbliche. Cache Storage non impone no-store; non usare questa configurazione per pagine personalizzate. Nessuna risposta a runtime viene aggiunta alla cache. Il nome della cache include lo scope del worker; in migrazione controlla la vecchia cache field-notes-demo-v1 prima di rimuoverla manualmente. Il nome del database non cambia per conservare la nota. [5][6]
Come salvare i dati offline?
drafts.v2.js
const DATABASE_NAME = "field-notes-demo";
const DATABASE_VERSION = 1;
const STORE_NAME = "drafts";
const DRAFT_KEY = "local-note";
export const MAX_DRAFT_LENGTH = 2000;
export function openDraftDatabase() {
return new Promise((resolve, reject) => {
if (!("indexedDB" in globalThis)) {
reject(new Error("IndexedDB is unavailable."));
return;
}
const request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
let blocked = false;
request.onblocked = () => {
blocked = true;
reject(
new DOMException("Close other app windows and retry.", "BlockedError"),
);
};
request.onupgradeneeded = () => {
if (blocked) {
request.transaction.abort();
return;
}
const database = request.result;
if (!database.objectStoreNames.contains(STORE_NAME)) {
database.createObjectStore(STORE_NAME);
}
};
request.onsuccess = () => {
const database = request.result;
if (blocked) {
database.close();
return;
}
database.onversionchange = () => {
database.close();
};
resolve(database);
};
request.onerror = () => {
reject(request.error ?? new Error("Database could not be opened."));
};
});
}
async function runDraftTransaction(mode, createRequest) {
const database = await openDraftDatabase();
try {
return await new Promise((resolve, reject) => {
const transaction = database.transaction(STORE_NAME, mode);
transaction.onabort = () => {
reject(transaction.error ?? new Error("Draft transaction aborted."));
};
let request;
try {
request = createRequest(transaction.objectStore(STORE_NAME));
} catch (error) {
transaction.abort();
reject(error);
return;
}
transaction.oncomplete = () => {
resolve(request.result);
};
});
} finally {
database.close();
}
}
export async function readDraft() {
const value = await runDraftTransaction("readonly", (store) => {
return store.get(DRAFT_KEY);
});
if (value === undefined) {
return "";
}
if (typeof value !== "string" || value.length > MAX_DRAFT_LENGTH) {
throw new Error("Stored draft has an unexpected format.");
}
return value;
}
export async function saveDraft(text) {
if (typeof text !== "string" || text.length > MAX_DRAFT_LENGTH) {
throw new TypeError("Invalid draft text.");
}
await runDraftTransaction("readwrite", (store) => {
return store.put(text, DRAFT_KEY);
});
}app.v2.js
import { MAX_DRAFT_LENGTH, readDraft, saveDraft } from "./drafts.v2.js";
import { setupInstallation } from "./install.v2.js";
import { registerWorker } from "./worker-client.v2.js";
function requireElement(id, ElementType) {
const element = document.getElementById(id);
if (!(element instanceof ElementType)) {
throw new Error(`Missing or invalid element: #${id}`);
}
return element;
}
async function initializeDraft(form, draft, saveButton, status) {
let lastSavedText = "";
let saving = false;
let ready = false;
draft.maxLength = MAX_DRAFT_LENGTH;
function showDraftState() {
status.textContent =
draft.value === lastSavedText ? "Draft is up to date." : "Unsaved changes.";
}
function showStorageError(error) {
console.error("Draft storage failed", error);
status.textContent =
error?.name === "BlockedError"
? "Close other app windows and retry. Copy your text first."
: "Local storage failed. Copy your text before leaving this page.";
}
form.addEventListener("submit", async (event) => {
event.preventDefault();
if (!ready || saving) {
return;
}
saving = true;
saveButton.disabled = true;
const textToSave = draft.value;
status.textContent = "Saving draft.";
try {
await saveDraft(textToSave);
lastSavedText = textToSave;
status.textContent =
draft.value === textToSave
? "Draft saved on this device."
: "Earlier text saved. New changes are unsaved.";
} catch (error) {
showStorageError(error);
} finally {
saving = false;
saveButton.disabled = false;
}
});
try {
lastSavedText = await readDraft();
draft.value = lastSavedText;
} catch (error) {
console.error("Draft loading failed", error);
status.textContent =
error?.name === "BlockedError"
? "Close other app windows, copy any text and reload to retry."
: "Local draft unavailable. Copy any text before reloading to retry.";
draft.disabled = false;
return;
}
ready = true;
draft.disabled = false;
saveButton.disabled = false;
showDraftState();
draft.addEventListener("input", showDraftState);
}
function initializeApp() {
const installButton = requireElement("install", HTMLButtonElement);
const installStatus = requireElement("install-status", HTMLElement);
const workerStatus = requireElement("worker-status", HTMLElement);
const form = requireElement("draft-form", HTMLFormElement);
const draft = requireElement("draft", HTMLTextAreaElement);
const saveButton = requireElement("save", HTMLButtonElement);
const draftStatus = requireElement("draft-status", HTMLElement);
setupInstallation(installButton, installStatus);
void registerWorker(workerStatus);
void initializeDraft(form, draft, saveButton, draftStatus);
}
try {
initializeApp();
} catch (error) {
console.error("Invalid application markup", error);
}
IndexedDB supporta dati strutturati e transazioni. Conferma il salvataggio con transaction.oncomplete, non al successo della singola richiesta. La demo salva una bozza non sensibile; se fallisce, l'utente può copiare il testo. [7][8]
Ogni operazione apre il database, attende il completamento della transazione e chiude la connessione. blocked segnala un'altra scheda che blocca la migrazione; una migrazione tardiva viene annullata e una connessione tardiva chiusa. versionchange libera le connessioni per la migrazione. Se la lettura fallisce, il salvataggio rimane disabilitato per non sovrascrivere una nota non letta. Copia il testo e ricarica dopo aver risolto il problema. Le modifiche durante il salvataggio restano indicate come non salvate. La nota è condivisa tra schede della stessa origine: prevale l'ultima scrittura confermata. Non ci sono sincronizzazione o risoluzione dei conflitti. [7][14][15]
Per sincronizzare, salva una coda di operazioni con chiavi di idempotenza e rimuovile solo dopo la conferma del server. Gestisci conflitti e sessioni scadute. navigator.onLine non dimostra che l'API sia raggiungibile; Background Sync è facoltativo. persist() non garantisce la conservazione e non sostituisce un backup. [7][8][9]
Perché rimane attiva la vecchia versione?
worker-client.v2.js
function observeUpdates(registration, serviceWorker, status) {
const observedWorkers = new WeakSet();
function announceState() {
if (registration.waiting && serviceWorker.controller) {
status.textContent =
"Update ready. Save your work and close all app windows.";
} else if (serviceWorker.controller) {
status.textContent = "This page is controlled by the service worker.";
} else if (registration.active) {
status.textContent =
"Offline resources prepared. Reload to enable offline navigation.";
} else {
status.textContent = "Preparing offline resources.";
}
}
function observeInstallingWorker() {
const worker = registration.installing;
if (!worker || observedWorkers.has(worker)) {
return;
}
observedWorkers.add(worker);
function handleStateChange() {
if (worker.state === "redundant") {
status.textContent =
"Offline preparation or update failed. Try again later.";
} else {
announceState();
}
if (worker.state === "activated" || worker.state === "redundant") {
worker.removeEventListener("statechange", handleStateChange);
}
}
worker.addEventListener("statechange", handleStateChange);
}
registration.addEventListener("updatefound", observeInstallingWorker);
serviceWorker.addEventListener("controllerchange", announceState);
observeInstallingWorker();
announceState();
}
export async function registerWorker(status) {
if (!("serviceWorker" in navigator)) {
status.textContent = "Offline navigation is not supported here.";
return;
}
try {
const serviceWorker = navigator.serviceWorker;
const registration = await serviceWorker.register("./sw.js", {
updateViaCache: "none",
});
observeUpdates(registration, serviceWorker, status);
} catch (error) {
console.error("Service worker registration failed", error);
status.textContent = "Offline navigation is unavailable.";
}
}
Un nuovo worker installa le risorse e normalmente attende che i client precedenti non siano più controllati. Ricaricare una scheda può non bastare. La demo segnala registration.waiting e invita a salvare e chiudere tutte le finestre, senza skipWaiting() o clients.claim() automatici. [4][10]
Versiona cache e file modificati, pubblica le risorse prima di HTML e worker e conserva i file precedenti durante la transizione. In activate elimina solo le cache obsolete dell'app. L'attivazione forzata richiede coordinamento tra schede e migrazioni; un reload automatico può perdere modifiche. [10]
Una PWA può sostituire un'app nativa?
Cataloghi, strumenti, moduli e appunti beneficiano dell'accesso tramite link. Per attività lunghe in background, hardware specifico o integrazioni profonde, verifica i dispositivi reali; un'app nativa o ibrida può essere preferibile. [2][9]
Su iOS/iPadOS l'installazione usa l'interfaccia di sistema. Web Push per le app della schermata Home è disponibile dalla 16.4; chiedere l'autorizzazione richiede interazione. Safari 26 ha modificato il comportamento predefinito di aggiunta alla Home. Rilevare un'API non garantisce il permesso. [11][12]
Come verificare il funzionamento effettivo?
In Chrome DevTools > Application controlla manifest, icone, scope e worker. Apri online, attendi l'attivazione, ricarica e salva una bozza. Disconnetti, ricarica, prova lettura e scrittura e visita un URL non salvato. Riconnettendoti verifica che un vero 404 non diventi la pagina offline. [13]
Con due schede, pubblica una versione e verifica waiting, conservazione delle bozze e rimozione delle sole cache obsolete dell'app. Prova un profilo nuovo offline, installazione rifiutata, esaurimento dello spazio e dispositivi iOS/Android. Misura avvii offline ed errori di salvataggio e aggiornamento.
Verifica anche modifiche durante il salvataggio, una migrazione IndexedDB bloccata da un'altra scheda ed errori di scrittura. Controlla che il vecchio worker serva la propria home dopo la pubblicazione del nuovo HTML. Cancella solo la cache, non il database, e verifica il comportamento. [10][13][14]
