html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sync Messages PWA</title>
<link rel="manifest" href="manifest.json">
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
margin: 0;
padding: 0;
background: #f5f5f5;
}
#app {
max-width: 600px;
margin: 0 auto;
padding: 20px;
background: white;
min-height: 100vh;
box-sizing: border-box;
}
h1 {
text-align: center;
color: #333;
}
#messageForm {
display: flex;
gap: 10px;
margin-bottom: 20px;
}
#messageInput {
flex: 1;
padding: 12px;
border: 1px solid #ddd;
border-radius: 8px;
font-size: 16px;
}
button {
padding: 12px 20px;
background: #4A90E2;
color: white;
border: none;
border-radius: 8px;
font-size: 16px;
cursor: pointer;
}
button:hover {
background: #357ABD;
}
button:disabled {
background: #ccc;
cursor: not-allowed;
}
#messages {
list-style: none;
padding: 0;
margin: 0;
}
#messages > div {
margin-bottom: 20px;
}
#messages h3 {
margin: 0 0 10px 0;
color: #666;
font-size: 18px;
}
li {
padding: 12px;
background: #f8f9fa;
border-radius: 8px;
margin-bottom: 8px;
border-left: 4px solid #4A90E2;
}
li.pending {
border-left-color: #ffc107;
opacity: 0.7;
}
small {
display: block;
color: #999;
font-size: 12px;
margin-top: 4px;
}
#status {
padding: 12px;
background: #e3f2fd;
border-radius: 8px;
text-align: center;
font-weight: bold;
margin-top: 20px;
}
.online { color: #4CAF50; }
.offline { color: #f44336; }
@media (max-width: 480px) {
#messageForm { flex-direction: column; }
button { width: auto; }
}
</style>
</head>
<body>
<div id="app">
<h1>📱 Sync Messages PWA</h1>
<form id="messageForm">
<input id="messageInput" type="text" placeholder="Enter a message to sync..." required>
<button type="submit" id="submitBtn">Send</button>
</form>
<ul id="messages"></ul>
<div id="status">Loading...</div>
</div>
<script src="app.js"></script>
</body>
</html>
json Copy code
// manifest.json
{
"name": "Sync Messages PWA",
"short_name": "SyncDemo",
"description": "A PWA demo with offline caching and background sync",
"start_url": "/",
"display": "standalone",
"background_color": "#f5f5f5",
"theme_color": "#4A90E2",
"icons": [
{
"src": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 192 192'%3E%3Crect width='192' height='192' rx='24' fill='%234A90E2'/%3E%3Ctext x='96' y='112' font-size='72' text-anchor='middle' dominant-baseline='middle' fill='white' font-weight='bold' font-family='sans-serif'%3ES%3C/text%3E%3C/svg%3E",
"sizes": "192x192",
"type": "image/svg+xml",
"purpose": "any maskable"
},
{
"src": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'%3E%3Crect width='512' height='512' rx='64' fill='%234A90E2'/%3E%3Ctext x='256' y='300' font-size='200' text-anchor='middle' dominant-baseline='middle' fill='white' font-weight='bold' font-family='sans-serif'%3ES%3C/text%3E%3C/svg%3E",
"sizes": "512x512",
"type": "image/svg+xml",
"purpose": "any maskable"
}
]
}
javascript Copy code
// sw.js
const CACHE_NAME = 'sync-pwa-v1';
const urlsToCache = [
'/',
'/index.html',
'/app.js',
'/manifest.json'
];
const DB_NAME = 'sync-demo';
const STORE_NAME = 'queue';
function openDB() {
return new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, 1);
req.onerror = () => reject(req.error);
req.onsuccess = () => resolve(req.result);
req.onupgradeneeded = (e) => {
const db = e.target.result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME, { keyPath: 'id', autoIncrement: true });
}
};
});
}
self.addEventListener('install', (e) => {
e.waitUntil(
caches.open(CACHE_NAME)
.then((cache) => cache.addAll(urlsToCache))
.then(() => self.skipWaiting())
);
});
self.addEventListener('activate', (e) => {
e.waitUntil(
caches.keys().then((cacheNames) =>
Promise.all(
cacheNames.map((name) => {
if (name !== CACHE_NAME) {
return caches.delete(name);
}
})
)
).then(() => self.clients.claim())
);
});
self.addEventListener('fetch', (e) => {
e.respondWith(
caches.match(e.request)
.then((cachedResponse) => {
if (cachedResponse) {
return cachedResponse;
}
return fetch(e.request).then((networkResponse) => {
if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') {
return networkResponse;
}
const responseClone = networkResponse.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(e.request, responseClone);
});
return networkResponse;
}).catch(() => {
// Cache-first offline fallback for app shell
return caches.match('/');
});
})
);
});
async function syncPendingMessages() {
const db = await openDB();
const tx = db.transaction(STORE_NAME, 'readwrite');
const store = tx.objectStore(STORE_NAME);
const pending = await new Promise((resolve) => {
const req = store.getAll();
req.onsuccess = () => resolve(req.result);
});
const newlySynced = [];
for (const item of pending) {
try {
const res = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: item.message })
});
if (res.ok) {
store.delete(item.id);
newlySynced.push(item);
} else {
// Stop on first failure to retry later
break;
}
} catch (err) {
// Network error, stop and retry next sync
break;
}
}
// Notify all clients
self.clients.matchAll({ type: 'window' }).then((clients) => {
clients.forEach((client) => {
client.postMessage({
type: 'items-synced',
items: newlySynced
});
});
});
}
self.addEventListener('sync', (e) => {
if (e.tag === 'sync-messages') {
e.waitUntil(syncPendingMessages());
}
});
How to Use This PWA Demo
Save the files : Create the four files (index.html, manifest.json, app.js, sw.js) in a folder.
Serve it :
Use a local server with HTTPS for full PWA features (e.g., npx serve . --ssl or deploy to Netlify/GitHub Pages).
Open index.html directly in Chrome for basic testing (offline cache works, but install prompt needs HTTPS).
Test Features :
Offline Caching : Go offline (DevTools > Network > Offline). Reload—the app loads from cache.
Offline Submit : Submit a message offline—it queues as "Pending Sync".
Background Sync : Go online. The Service Worker automatically syncs pending messages to httpbin.org (mock server), moves them to "Synced", and updates the UI.
Online Submit : Works directly, adds to "Synced".
PWA Install : On HTTPS, "Add to home screen" appears. Launches standalone.
DevTools Tips :
Application tab: See Service Worker, Cache Storage, Manifest, IndexedDB (sync-demo).
Simulate offline/online toggles.
This is a fully functional, self-contained PWA! 🚀