Nanfeng

Notes on software development, code, and curious ideas

Building a Platform-Aware PWA Installation Flow

This PWA refinement adds three features: different browser and installed views, an explicit install button, and platform-specific guidance when direct installation is unavailable.

The browser view is index.html; the installed view is selected through manifest.json‘s start_url. Android and supported desktop browsers use beforeinstallprompt. Safari on iOS receives an Add to Home Screen guide, while other iOS browsers are told to open Safari.

Core JavaScript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
let deferredPrompt;

const isAndroid = () => /Android/i.test(navigator.userAgent);
const isIOS = () => /iPhone|iPad|iPod/i.test(navigator.userAgent);
const isSafari = () => isIOS() && navigator.userAgent.includes('Safari')
&& !navigator.userAgent.includes('CriOS') && !navigator.userAgent.includes('FxiOS');

window.addEventListener('beforeinstallprompt', event => {
event.preventDefault();
deferredPrompt = event;
});

document.querySelector('#install-btn').addEventListener('click', async () => {
if (deferredPrompt) {
deferredPrompt.prompt();
await deferredPrompt.userChoice;
deferredPrompt = null;
} else if (isSafari()) {
document.querySelector('#ios-install-guide').style.display = 'flex';
} else if (isIOS()) {
alert('Open this page in Safari and choose Add to Home Screen from Share.');
} else {
alert('Direct PWA installation is unavailable. Try Chrome or Edge.');
}
});

if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js');
}

The manifest selects the installed entry point:

1
2
3
4
5
6
7
8
9
10
11
12
{
"short_name": "MyPWA",
"name": "My Progressive Web App",
"start_url": "/client/test/pwa2/index.html",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#ffffff",
"icons": [
{"src":"icons/icon-192x192.png","type":"image/png","sizes":"192x192"},
{"src":"icons/icon-512x512.png","type":"image/png","sizes":"512x512"}
]
}

A minimal service worker can install, activate, and observe fetches. Also prepare both icon sizes and an ios-install-guide.png image.

Project structure

+