EthicsComputerCourses
Join training +91 90532 10052

PWA Installation & Update Workflow

HTML · Lesson 160 of 234 Advanced 12 min read Updated

By the end of this lesson you will be able to offer a custom install button, guide iPhone users through manual installation, detect when your app runs installed, and ship new versions with a "New version available" prompt that never breaks open pages.

What you should know first: Progressive Web Apps (PWA), where you built Rohtak Bus Timings, Web App Manifest and the lifecycle from Service Workers Fundamentals.

Who can install, and how

Each browser family handles installation differently, so plan for all of them:

BrowserHow users installWhat the site needs
Chrome, Edge, Samsung Internet (Chromium) on Android and desktopInstall icon in the address bar, the browser menu, or your own buttonThe criteria below
Safari on iPhone and iPadShare menu, then Add to Home ScreenNothing: since iOS 26 any site can be added and opens as a web app
Safari on MacFile menu, then Add to Dock (Safari 17 and later)Nothing; a manifest improves the result
FirefoxAndroid: browser menu. Windows: pin a site to the taskbar as a web app (Firefox 143 and later)No custom prompt event

Chrome's documented criteria are: the site is served over HTTPS; the manifest has name or short_name, 192 and 512 pixel icons, a start_url, and a display of fullscreen, standalone, minimal-ui or window-controls-overlay; prefer_related_applications is missing or false; the app is not already installed; and the user has clicked or tapped the page at least once and spent at least 30 seconds on it. Chrome stopped requiring a service worker for menu installs in Chrome 108 on Android and 112 on desktop, but its automatic install prompts still expect a worker with a fetch handler, so keep one.

A custom install button

When a page meets the criteria, Chromium browsers fire a beforeinstallprompt event on window. You can catch it, stop the browser's own small banner, and show your own button at a better moment, such as after a user saves a favourite route. A good shopkeeper offers the loyalty card after you have chosen your items, not at the door.

Step 1: hide the button by default, so browsers without the event never show it.

Step 2: catch the event, call preventDefault() and keep the event object.

Step 3: on click, call prompt() and read the choice. It works only from a user action, and only once per event.

Step 4: on appinstalled, which fires after any install, even one from the browser menu, hide your button.

The event never fires inside the editor, because browsers fire it only for top-level pages, not frames. So this example shows which path the current browser would take.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Install helper</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    .card { border: 1px solid #ccc; border-radius: 8px; padding: 12px 16px; margin-block: 12px; }
  </style>
</head>
<body>
  <h1>Pune Library Card</h1>
  <p>Display mode right now: <strong id="mode"></strong></p>

  <div class="card" id="install-card" hidden>
    <p>Install the app to check due dates in one tap.</p>
    <button type="button" id="install">Install app</button>
  </div>

  <div class="card" id="manual-card" hidden>
    <h2>Add this app to your home screen</h2>
    <ol>
      <li>On iPhone or iPad: open the Share menu in Safari, then choose Add to Home Screen.</li>
      <li>Keep Open as Web App switched on, then tap Add.</li>
      <li>In other browsers: open the browser menu and look for Install or Add to Home screen.</li>
    </ol>
  </div>
  <p id="status" role="status"></p>

  <script>
    const modes = ["fullscreen", "standalone", "minimal-ui", "browser"];
    function currentMode() {
      return modes.find((m) => matchMedia(`(display-mode: ${m})`).matches) || "unknown";
    }
    function showMode() {
      document.querySelector("#mode").textContent = currentMode();
    }
    for (const m of modes) {
      matchMedia(`(display-mode: ${m})`).addEventListener("change", showMode);
    }
    showMode();

    let deferredPrompt = null;
    const installCard = document.querySelector("#install-card");
    const manualCard = document.querySelector("#manual-card");
    const status = document.querySelector("#status");

    if (currentMode() === "browser") {
      if ("BeforeInstallPromptEvent" in window) {
        status.textContent = "This browser supports beforeinstallprompt. The Install button appears when the browser decides the app can be installed.";
      } else {
        manualCard.hidden = false;
      }
    } else {
      status.textContent = "You are already using the installed app.";
    }

    window.addEventListener("beforeinstallprompt", (event) => {
      event.preventDefault();          // stop the browser's own mini prompt
      deferredPrompt = event;          // keep it for our button
      installCard.hidden = false;
    });

    document.querySelector("#install").addEventListener("click", async () => {
      if (!deferredPrompt) return;
      const { outcome } = await deferredPrompt.prompt();
      status.textContent = outcome === "accepted" ? "Installing..." : "No problem. You can install later.";
      deferredPrompt = null;
      installCard.hidden = true;
    });

    window.addEventListener("appinstalled", () => {
      installCard.hidden = true;
      status.textContent = "Installed. Look for Pune Library Card on your home screen or app list.";
    });
  </script>
</body>
</html>

Chrome and Edge show the "supports beforeinstallprompt" message; Safari and Firefox show the manual instructions.

Manual install on iPhone and iPad

Every browser on iOS uses Apple's WebKit engine, and none fires beforeinstallprompt. Your page can only show instructions. On iOS 26 in Safari:

  1. Tap the Page menu button (three dots) next to the address bar, then Share. With the older Top or Bottom tab layout, tap the Share button directly.
  2. Scroll down and tap Add to Home Screen.
  3. Leave Open as Web App switched on, and tap Add.

Since iOS 16.4, other iOS browsers such as Chrome and Edge can also add a site to the Home Screen from their Share menu. Safari uses <link rel="apple-touch-icon"> for the icon, so keep it. Show the instructions only in browser mode.

Detecting the installed app

The display-mode media feature tells you how the page is shown. In CSS, hide install prompts inside the installed app:

CSS
@media (display-mode: standalone), (display-mode: minimal-ui), (display-mode: fullscreen) {
  .install-banner { display: none; }
}

In JavaScript, matchMedia("(display-mode: standalone)").matches gives the same answer. Older iOS code also checks navigator.standalone, a non-standard Safari property; prefer the media query. To count launches of the installed app in analytics, use the query string in start_url, such as ?source=pwa.

How service worker updates arrive

You deploy a new sw.js. The browser checks for an updated worker:

  • after a navigation to a page in the worker's scope;
  • after events such as push and sync, unless it already checked in the last 24 hours;
  • whenever your code calls registration.update().

It compares the new sw.js byte by byte with the installed copy; any difference starts an update. By default this check skips the HTTP cache, but scripts loaded with importScripts() still follow cache headers.

The new worker installs and precaches its files, then waits. The old worker keeps control while any tab uses it, so no page mixes old HTML with new JavaScript. A plain reload is not enough, because the old page stays open during the reload. Users who never close the app could stay on the old version for days, so ask them.

Prompt "New version available"

Step 1: in sw.js, let the page tell a waiting worker to activate now. self.skipWaiting() skips the wait.

JavaScript
self.addEventListener("message", (event) => {
  if (event.data && event.data.type === "SKIP_WAITING") self.skipWaiting();
});

Step 2: add a message area and a hidden button to the page:

HTML
<p id="update-msg" role="status"></p>
<button type="button" id="update-btn" hidden>Reload</button>

Step 3: replace the registration in app.js with update.js. It shows the prompt when a new worker is installed and waiting, sends SKIP_WAITING when the user agrees, and reloads when the new worker takes control.

JavaScript
const message = document.querySelector("#update-msg");
const reloadButton = document.querySelector("#update-btn");

function showUpdate(worker) {
  message.textContent = "A new version is available.";
  reloadButton.hidden = false;
  reloadButton.onclick = () => worker.postMessage({ type: "SKIP_WAITING" });
}

async function watchForUpdates() {
  const hadController = Boolean(navigator.serviceWorker.controller);
  let refreshing = false;

  navigator.serviceWorker.addEventListener("controllerchange", () => {
    if (!hadController || refreshing) return;
    refreshing = true;
    window.location.reload();
  });

  const reg = await navigator.serviceWorker.register("/sw.js");

  // Case 1: an update was already waiting when this page opened
  if (reg.waiting && hadController) showUpdate(reg.waiting);

  // Case 2: an update is found while the page is open
  reg.addEventListener("updatefound", () => {
    const worker = reg.installing;
    worker.addEventListener("statechange", () => {
      if (worker.state === "installed" && navigator.serviceWorker.controller) {
        showUpdate(worker);
      }
    });
  });

  // People keep a bus app open all day, so check again every hour
  setInterval(() => reg.update(), 60 * 60 * 1000);
}

if ("serviceWorker" in navigator) watchForUpdates();

controller is null on the first visit, so the first install shows no prompt. hadController stops a pointless reload if your worker calls clients.claim(), and refreshing prevents a reload loop.

What you should see in Rohtak Bus Timings after a deploy: the prompt appears; a plain reload keeps the update waiting; clicking Reload activates the new worker, reloads the page and deletes the old bus-shell-v1 cache.

Service workers cannot run in the editor, so this simulator copies the same events and states with stand-in objects. Click Deploy, then Reload in the dark bar, and read the log.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Update flow simulator</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    #toast { background: #263238; color: #fff; padding: 10px 14px; border-radius: 8px; display: flex; gap: 12px; align-items: center; }
    #toast[hidden] { display: none; }
    #log { font-family: monospace; font-size: 0.9rem; }
  </style>
</head>
<body>
  <h1>Lucknow Tiffin Orders</h1>
  <p>Page is running code from: <strong id="running">v1</strong></p>
  <button type="button" id="deploy">Deploy a new version to the server</button>

  <p id="msg" role="status"></p>
  <div id="toast" hidden>
    <span>A new version is available.</span>
    <button type="button" id="reload">Reload</button>
  </div>

  <h2>What happened</h2>
  <ol id="log"></ol>

  <script>
    // A pretend registration with the same events and states as the real one
    const container = new EventTarget();          // stands in for navigator.serviceWorker
    const reg = new EventTarget();                // stands in for the registration
    let serverVersion = 1;
    let activeVersion = 1;
    reg.waiting = null;

    function log(text) {
      const li = document.createElement("li");
      li.textContent = text;
      document.querySelector("#log").append(li);
    }

    function makeWorker(version) {
      const worker = new EventTarget();
      worker.version = version;
      worker.state = "installing";
      worker.postMessage = (data) => {
        log(`page -> worker v${version}: postMessage(${JSON.stringify(data)})`);
        if (data.type === "SKIP_WAITING") {
          log(`worker v${version}: skipWaiting(), then activate deletes old caches`);
          setTimeout(() => {
            worker.state = "activated";
            reg.waiting = null;
            activeVersion = version;
            container.dispatchEvent(new Event("controllerchange"));
          }, 500);
        }
      };
      return worker;
    }

    // The browser's update check: a byte-different sw.js means a new worker installs
    document.querySelector("#deploy").addEventListener("click", () => {
      serverVersion++;
      log(`server now has sw.js v${serverVersion}; browser checks and finds it is different`);
      const worker = makeWorker(serverVersion);
      reg.installing = worker;
      reg.dispatchEvent(new Event("updatefound"));
      setTimeout(() => {
        worker.state = "installed";
        reg.installing = null;
        reg.waiting = worker;
        worker.dispatchEvent(new Event("statechange"));
      }, 700);
    });

    // ----- The page code: the same pattern you write for a real app -----
    const toast = document.querySelector("#toast");

    reg.addEventListener("updatefound", () => {
      const worker = reg.installing;
      log(`updatefound: v${worker.version} is installing (precaching files)`);
      worker.addEventListener("statechange", () => {
        log(`statechange: v${worker.version} is ${worker.state}, waiting for old pages to close`);
        if (worker.state === "installed") {
          document.querySelector("#msg").textContent = "A new version is available.";
          toast.hidden = false;
        }
      });
    });

    document.querySelector("#reload").addEventListener("click", () => {
      toast.hidden = true;
      reg.waiting.postMessage({ type: "SKIP_WAITING" });
    });

    container.addEventListener("controllerchange", () => {
      log(`controllerchange: v${activeVersion} now controls the page, so reload`);
      document.querySelector("#running").textContent = `v${activeVersion} (after reload)`;
      document.querySelector("#msg").textContent = `Updated to version ${activeVersion}.`;
    });
  </script>
</body>
</html>

The log shows the real order of events. Never call skipWaiting() automatically in an app with forms: a reload in the middle of Ananya's tiffin order would lose her typing.

Cache versioning on deploy

A release checklist for each deploy:

  1. Change VERSION in sw.js. This makes the file byte-different and gives the new shell its own cache, which activate cleans up later.
  2. Give CSS and JS files a content hash in their names, such as app.3f9a1c.js, so cache first can never serve an old file under a new name.
  3. Keep the same worker URL, /sw.js. Renaming it to sw-v2.js breaks updates, because old cached pages still register the old name.
  4. Send sw.js and your HTML with Cache-Control: no-cache. On Apache, with mod_headers enabled:
Text
<Files "sw.js">
  Header set Cache-Control "no-cache"
</Files>
  1. Keep the manifest id unchanged. Browsers refresh an installed app's name and icons on their own schedule, and some ask the user before changing them.

Uninstalling and cleaning up

Users remove an installed app like any other: from the app window's menu on desktop, or by long-pressing the icon on a phone. This may not delete the site's caches and IndexedDB data; some browsers offer to clear them too.

Sometimes you need to remove the offline layer, for example after a buggy worker shipped. Never just delete sw.js from the server: the browser keeps the installed worker. Deploy a small "kill switch" worker in its place:

JavaScript
self.addEventListener("install", () => self.skipWaiting());
self.addEventListener("activate", (event) => {
  event.waitUntil((async () => {
    for (const name of await caches.keys()) await caches.delete(name);
    await self.registration.unregister();
    for (const client of await self.clients.matchAll({ type: "window" })) {
      client.navigate(client.url);
    }
  })());
});

It deletes every cache, unregisters itself and reloads open pages from the network. A server can also send the Clear-Site-Data: "cache", "storage" response header, which removes caches, storage and service worker registrations for the site; Chrome 61+, Firefox 63+ and Safari 17+ support it.

Common mistakes

  • Showing an install button before beforeinstallprompt fires. It does nothing in Safari and Firefox.
  • Calling prompt() twice or without a click. It works once per event, only from a user action.
  • Auto skipWaiting() in apps with forms. Users lose unsaved work in the reload.
  • Reloading on every controllerchange. The first install reloads for no reason; guard it.
  • Renaming sw.js for each release. Keep one URL and change its contents.
  • Deleting sw.js to "uninstall" the worker. Ship a kill-switch worker instead.

Interview questions

1. How do you build a custom install button, and where does it work?

Listen for beforeinstallprompt, call preventDefault(), store the event and show your button. On click call event.prompt() once and read outcome. It works only in Chromium browsers, so Safari and Firefox users need manual instructions.

2. Why does a new service worker wait instead of taking over at once?

Open pages were loaded by the old worker and expect its cached files. Taking over at once could mix old HTML with new scripts or deleted caches, so it waits until no tab uses the old worker, unless skipWaiting() is called.

3. Why does refreshing the page not activate a waiting worker?

During a refresh, the current page stays open until the new response arrives, so the old worker still has a client. The waiting worker activates only when every client of the old one has gone, or when skipWaiting() is called.

4. How do you show a "New version available" prompt?

Watch updatefound on the registration and the new worker's statechange. When its state is installed and the page already has a controller, show the prompt. On click, postMessage({type: "SKIP_WAITING"}) to the worker, which calls skipWaiting(), and reload once on controllerchange.

5. How do you detect that a PWA is running as an installed app?

Use the display-mode media feature, in CSS with @media (display-mode: standalone) or in JavaScript with matchMedia(). Old iOS code used navigator.standalone.

Key points

  • Chromium installs need HTTPS, a complete manifest and user engagement; Safari on iOS 26 lets users add any site; Firefox installs on Android and Windows without a custom prompt.
  • beforeinstallprompt and appinstalled are Chromium only: store the event, call prompt() once from a click, and keep manual instructions for others.
  • Detect installed mode with @media (display-mode: standalone) or matchMedia().
  • Browsers check for a new sw.js on navigation, on some events and on registration.update(); any byte change starts an update.
  • A new worker waits until old tabs close; ask the user, then send SKIP_WAITING and reload once on controllerchange.
  • On each deploy, bump the cache version, hash asset names, keep the sw.js URL and id stable, and use a kill-switch worker or Clear-Site-Data to remove a broken worker.

Exercise

Priya runs "Kochi School Notices", a PWA used by parents. Write the page code that: shows an "Install the app" button only when beforeinstallprompt fires (hidden after the choice and after appinstalled); hides an element with class install-help when running in standalone mode; and shows a "New version available" message with a Reload button when a new service worker is waiting, activating it only when the parent clicks. Also write the message listener for sw.js.

Show solution
JavaScript
// sw.js
self.addEventListener("message", (event) => {
  if (event.data && event.data.type === "SKIP_WAITING") self.skipWaiting();
});
JavaScript
// page script
const installBtn = document.querySelector("#install");
let deferred = null;

if (matchMedia("(display-mode: standalone)").matches) {
  document.querySelector(".install-help").hidden = true;
}

window.addEventListener("beforeinstallprompt", (event) => {
  event.preventDefault();
  deferred = event;
  installBtn.hidden = false;
});
installBtn.addEventListener("click", async () => {
  if (!deferred) return;
  await deferred.prompt();
  deferred = null;
  installBtn.hidden = true;
});
window.addEventListener("appinstalled", () => { installBtn.hidden = true; });

async function watchForUpdates() {
  const hadController = Boolean(navigator.serviceWorker.controller);
  let refreshing = false;
  navigator.serviceWorker.addEventListener("controllerchange", () => {
    if (!hadController || refreshing) return;
    refreshing = true;
    location.reload();
  });

  const reg = await navigator.serviceWorker.register("/sw.js");
  const offer = (worker) => {
    document.querySelector("#update-msg").textContent = "New version available.";
    const btn = document.querySelector("#update-btn");
    btn.hidden = false;
    btn.onclick = () => worker.postMessage({ type: "SKIP_WAITING" });
  };
  if (reg.waiting && hadController) offer(reg.waiting);
  reg.addEventListener("updatefound", () => {
    const worker = reg.installing;
    worker.addEventListener("statechange", () => {
      if (worker.state === "installed" && navigator.serviceWorker.controller) offer(worker);
    });
  });
}

if ("serviceWorker" in navigator) watchForUpdates();

The install button stays hidden in Safari and Firefox, and an update activates only after the parent clicks Reload.

Quick Quiz

1. In which browsers does beforeinstallprompt fire?

2. A new service worker is installed and waiting. The user presses Reload in the browser. What happens?

3. How many times can you call prompt() on one beforeinstallprompt event?

4. What is the safest way to remove a buggy service worker from users' devices?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call