What makes a web app installable?
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;
}
The manifest supplies a name, identity (id), entry point (start_url), scope and icons. display: standalone requests a separate app window. Link the manifest in HTML, serve over HTTPS (localhost is a development exception), and provide valid PNG icons. Installation promotion criteria vary; some browsers also install ordinary websites. A service worker is independent of installation itself. [1][2]
Relative paths let the demo live in its own directory without taking over the domain. Manifest scope defines the app's navigation boundary, not the worker's interception scope. Provide a separate maskable icon with a safe zone for production. The install button starts hidden; on platforms without beforeinstallprompt, explain the browser's installation menu instead. [3]
Place all listed files and both icons in pwa-demo. Each code block is a separate file; no concatenation is needed. From the parent directory run python3 -m http.server 8000 and open http://localhost:8000/pwa-demo/. Adjust the link in offline.html for other deployment paths.
How do I register a service worker and offer installation?
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;
});
}
A worker runs in a separate environment without the DOM, can be terminated by the browser and must not rely on global variables persisting. Registering sw.js inside the app directory scopes it there by default. updateViaCache: "none" limits HTTP caching for worker-script update checks; it does not disable Cache Storage. [4]
The install.v2.js module handles installation only; worker registration and draft storage live in separate modules. beforeinstallprompt is not a universally available standard mechanism. Keep the event for one prompt() call after a click; declining installation is not an application error. Registration can fail without breaking online use. ready does not ensure the current tab is controlled: check navigator.serviceWorker.controller and reload normally after initial activation. [3][4]
How do I support offline navigation without caching private responses?
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>
The public demo precaches ten resources in one versioned cache. The exact home URL (including index.html without query parameters) and allowlisted assets use cache-first. This avoids combining new HTML with an older asset set. Other navigations within scope use network-first; a network failure returns the offline page with HTTP 503. HTTP 404 and 500 responses to network-bound requests are preserved. A missing resource prevents preparation of the new release. [4][5][10]
Do not intercept POST, cross-origin requests or unknown API requests. Cache Storage does not automatically enforce HTTP Cache-Control: no-store when explicitly writing entries; use an allowlist of public resources. For authenticated apps, do not store personalized HTML or responses without designing isolation and data removal. Network-first may wait too long on a slow connection; choose a timeout and freshness policy in production. [5][6]
Precache uses credentials: "omit" and rejects redirects, but resources must actually be public. Cache Storage does not enforce no-store; do not use this configuration for personalized pages. No runtime responses are added to the cache. Cache names include the worker scope; when migrating from the previous demo, inspect the legacy field-notes-demo-v1 cache before removing it manually. The database name remains unchanged to preserve the saved note. [5][6]
How do I store offline data, not just app files?
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);
}
Cache Storage is not a database. IndexedDB supports transactions and structured records; report a successful save on transaction.oncomplete, not just request success. The demo saves one non-sensitive local draft, including offline. If the transaction fails, users can still copy their text. [7][8]
Each operation opens the database, waits for transaction completion and closes the connection. blocked reports another tab blocking an upgrade; a later upgrade request is aborted and any late connection is closed. versionchange releases connections for migration. If reading fails, saving stays disabled to avoid overwriting an unread note. Copy the text and reload after resolving the problem. Editing during a save distinguishes the saved snapshot from unsaved changes. This is a single note shared by tabs of the same origin: the last committed write wins. There is no synchronization or conflict resolution. [7][14][15]
For synchronized apps, persist operations in an outbox with idempotency identifiers, retry when connectivity returns and remove entries only after server acknowledgment. Resolve version conflicts, handle expired sessions, and do not treat navigator.onLine as proof that an API is reachable. Background Sync is optional; foreground retries should work independently. Local data can be removed; navigator.storage.persist() is neither guaranteed nor a backup. [7][8][9]
Why are users still seeing the old version?
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.";
}
}
A new worker installs its resources and normally waits until clients of the old worker are no longer controlled. Reloading one tab may not be enough. The demo announces registration.waiting and asks users to save their work and close all app windows. It does not automatically invoke skipWaiting() or clients.claim(). [4][10]
For each release, change the cache version and filenames of changed assets, publish assets before HTML and the worker, and retain older assets during migration. In activate, delete only obsolete caches owned by this app. Forced activation needs coordination across tabs, data migrations and compatibility with running code. Reloading on controllerchange alone can discard unsaved work. [10]
Can a PWA replace a native app?
A PWA suits catalogs, tools, forms and notes where access through a link matters. If long-running background tasks, specific hardware integrations or deep OS integration are essential, verify required APIs on real target devices; native or hybrid development may fit better. There is no single feature parity across operating systems. [2][9]
On iOS/iPadOS installation uses system UI; Web Push for Home Screen web apps has been available since 16.4 and requesting permission requires user interaction. Safari 26 changed default behavior when adding sites to the Home Screen, so do not rely exclusively on Chromium criteria. API detection alone does not establish permission. [11][12]
How do I verify that the PWA really works?
In Chrome DevTools > Application, inspect the manifest, icons, scope and active worker. Open online, wait for activation and reload. Save a draft, go offline, reload and check reading and writing; then visit an uncached URL within the scope. Reconnect and verify that a real HTTP 404 is not replaced with the offline page. [13]
Open two tabs, deploy a new version and inspect the waiting state, draft retention and cleanup of only obsolete app caches after closing tabs. Separately test a fresh offline profile, declined installation, storage exhaustion and real iOS/Android devices. Track offline launch success, save failures and update errors in production; a single audit score cannot establish reliability.
Also test editing during a save, a blocked IndexedDB upgrade in another tab and failed writes. Verify the old worker still serves its own home version after new HTML is deployed. Clear only the cache, not the database, and test the resulting behavior. [10][13][14]
