This guide explains how to make your Progressive Web App (PWA) functional across all pages, even if you don’t add the <link rel="manifest" href="manifest.json">
manually to every page.
1. Add the Manifest File
Create a manifest.json file in the root directory of your project. (you can use this: https://pwa.zneloy.site/)
2. Add a Service Worker (sw.js)
Create a sw.js file in the root directory of your project. Use the following code:
self.addEventListener(‘install’, (event) => { console.log(‘Service Worker installed’); }); self.addEventListener(‘activate’, (event) => { console.log(‘Service Worker activated’); }); self.addEventListener(‘fetch’, (event) => { if (event.request.destination === ‘document’) { event.respondWith( (async () => { const response = await fetch(event.request); const text = await response.text(); console.log(‘Fetched:’, event.request.url); const modifiedResponse = text.replace( ‘’, ’’ ); return new Response(modifiedResponse, { headers: response.headers, }); })() ); } });
3. Add this code before body end tag, in your main index page
if (‘serviceWorker’ in navigator) { navigator.serviceWorker .register(’/sw.js’) .then((registration) => { console.log(‘Service Worker registered:’, registration); }) .catch((error) => { console.log(‘Service Worker registration failed:’, error); }); }
Test Your PWA
- Open your browser (preferably Chrome or Edge).
- Visit your site’s index.html page.
- Open DevTools (F12 or Ctrl+Shift+I):
- Go to the Application tab.
- Check Service Workers to confirm that your service worker is active.
- Navigate to another page (e.g. test.html).
- Check thesection of the page in DevTools > Elements:
- Ensure the is present.
Key Points
- Place the sw.js file and manifest.json in the root directory of your project.
- The service worker automatically injects the into all pages.
- You only need to include the service worker registration script in your main index.html.
With this setup, your PWA will work seamlessly across all pages without manually adding the <link rel="manifest" href="manifest.json">
. 😊
Add an Install Button in website (Optional)
Add this code to implement an install button:
Install App let deferredPrompt; const installButton = document.getElementById(‘installButton’); installButton.style.display = ’none’; window.addEventListener(‘beforeinstallprompt’, (e) => { e.preventDefault(); deferredPrompt = e; installButton.style.display = ‘block’; installButton.addEventListener(‘click’, () => { deferredPrompt.prompt(); deferredPrompt.userChoice.then((choiceResult) => { if (choiceResult.outcome === ‘accepted’) { console.log(‘User accepted the A2HS prompt’); } else { console.log(‘User dismissed the A2HS prompt’); } deferredPrompt = null; }); }); });