Downloading a 200 MB podcast season or offline map from a service worker fails if the worker is stopped. Background Fetch hands the download to the browser, which shows a progress notification and keeps going even when your app is closed.
const reg = await navigator.serviceWorker.ready;
if ('backgroundFetch' in reg) {
const bgFetch = await reg.backgroundFetch.fetch('season-3', ['/media/s3e1.mp3', '/media/s3e2.mp3'], {
title: 'Season 3',
icons: [{ src: '/icons/podcast-192.png', sizes: '192x192', type: 'image/png' }],
downloadTotal: 180 * 1024 * 1024,
});
}
self.addEventListener('backgroundfetchsuccess', (event) => {
event.waitUntil((async () => {
const cache = await caches.open('downloads');
for (const record of await event.registration.matchAll()) {
await cache.put(record.request, await record.responseReady);
}
event.updateUI?.({ title: 'Season 3 is ready to play offline' });
})());
});
self.addEventListener('backgroundfetchfail', (event) => { /* tell the user */ });
self.addEventListener('backgroundfetchclick', () => clients.openWindow('/downloads/'));
Support and fallbacks
Background Fetch is Chromium-only. Elsewhere, download in the page with fetch() and streams, show your own progress bar, and store results in the Cache API or OPFS. Ask for persistent storage first for large downloads.
ब्राउज़र सपोर्ट
| फ़ीचर | Chrome / Edge desktop | Chrome Android | Safari iOS / iPadOS | Safari macOS | Firefox desktop | Firefox Android | Samsung Internet |
|---|---|---|---|---|---|---|---|
| Background Fetch | Chrome / Edge desktop: हाँ | Chrome Android: हाँ | Safari iOS / iPadOS: नहीं | Safari macOS: नहीं | Firefox desktop: नहीं | Firefox Android: नहीं | Samsung Internet: अलग-अलग |