Skip to content

API in Service Worker

Background Fetch API

Published

Limited availabilityNot supported in Firefox (Desktop), Firefox (Android), Safari (macOS), Safari (iOS)WICG draft

The Background Fetch API lets a page or service worker hand a set of requests to the browser as one named download that continues after the tab closes; the browser shows progress and a cancel control in its own UI and fires an event in the service worker when the operation settles. It shipped in Chrome 74, Edge 79, and Samsung Internet 11 and is not implemented in Firefox or Safari (BCD api.BackgroundFetchManager), so keep a normal fetch() download as a fallback.

// Page or service worker; registration comes from navigator.serviceWorker.ready
const bgFetch = await registration.backgroundFetch.fetch(id, requests, options);
const existing = await registration.backgroundFetch.get(id); // undefined when no job has that id
const ids = await registration.backgroundFetch.getIds(); // string[]
// Service worker
self.addEventListener('backgroundfetchsuccess', (event) => { /* event.registration */ });
self.addEventListener('backgroundfetchfail', (event) => { /* event.registration.failureReason */ });
self.addEventListener('backgroundfetchabort', (event) => { /* user or app cancelled */ });
self.addEventListener('backgroundfetchclick', (event) => { /* user tapped the browser UI */ });

fetch() returns a Promise<BackgroundFetchRegistration> as soon as the browser has accepted the job, long before any bytes arrive. Exactly one of backgroundfetchsuccess, backgroundfetchfail, or backgroundfetchabort fires when the operation settles; backgroundfetchclick fires only if the user activates the browser’s download UI. The first two are BackgroundFetchUpdateUIEvent instances whose updateUI({ title, icons }) changes the finished notification; the other two are plain BackgroundFetchEvent instances.

fetch() takes two required arguments and one options object.

Name Type Description
id string Developer-chosen identifier, later passed to get(id). One active registration per id; reusing an id while the first is in flight rejects.
requests RequestInfo | RequestInfo[] One Request or URL string, or an array of them. All requests are fetched as one user-visible job. Requests with mode: 'no-cors' are rejected.
options.title string Title shown in the browser’s progress UI.
options.icons ImageResource[] Objects with src, optional sizes, type, and label, used in the progress UI.
options.downloadTotal number Estimated total size in bytes. It drives the progress bar and is a hard cap: the browser aborts the job once downloaded bytes exceed it, with failureReason set to "download-total-exceeded".

The returned BackgroundFetchRegistration exposes id, downloadTotal, downloaded, uploadTotal, uploaded, result ("", "success", or "failure"), failureReason ("", "aborted", "bad-status", "fetch-error", "quota-exceeded", or "download-total-exceeded"), recordsAvailable, abort(), match(), matchAll(), and a progress event that fires whenever any of the counters or result changes.

fetch() rejects its promise in these cases (MDN, BackgroundFetchManager.fetch()).

Exception Condition
TypeError no request was given, a request uses mode: 'no-cors', the registration has no service worker, a registration with the same id already exists, or a request could not be created.
AbortError (DOMException) the fetch was aborted before it was accepted.
NotAllowedError (DOMException) the user agent has not granted permission to make background fetches for this origin; the specification leaves that permission check to the browser, so the condition is browser-defined.
QuotaExceededError storing the requests exceeded the origin’s storage quota. Responses are held in Cache Storage-like storage until the service worker reads them, so they count against the same quota as caches.

A failed download does not reject anything: it fires backgroundfetchfail with event.registration.failureReason set. A "bad-status" reason means a response had a non-ok status; "fetch-error" means the network request itself failed after retries.

Both examples assume a service worker registered at /sw.js and a secure origin.

Downloading an episode and its artwork as one job

Section titled “Downloading an episode and its artwork as one job”

The page requests the audio file and its cover image under one id so the browser shows a single progress notification; downloadTotal is the sum of the two Content-Length values obtained earlier from the server’s API.

async function downloadEpisode(episode) {
const registration = await navigator.serviceWorker.ready;
const bgFetch = await registration.backgroundFetch.fetch(
`episode-${episode.id}`,
[episode.audioUrl, episode.artworkUrl],
{
title: episode.title,
icons: [{ src: '/icons/download-192.png', sizes: '192x192', type: 'image/png', label: 'Episode download' }],
downloadTotal: episode.audioBytes + episode.artworkBytes,
},
);
bgFetch.addEventListener('progress', () => {
const percent = Math.round((bgFetch.downloaded / bgFetch.downloadTotal) * 100);
document.querySelector('#progress').value = percent;
});
}

The progress listener only runs while this page is open; once the tab closes, the browser’s own UI is the only progress indicator.

Storing the responses when the job settles

Section titled “Storing the responses when the job settles”

The service worker copies each response into a named cache in backgroundfetchsuccess, then changes the notification text; on failure it logs the reason and leaves the notification untouched so the user sees the browser’s failure state.

self.addEventListener('backgroundfetchsuccess', (event) => {
event.waitUntil((async () => {
const cache = await caches.open('episodes');
const records = await event.registration.matchAll();
await Promise.all(records.map(async (record) => {
const response = await record.responseReady;
await cache.put(record.request, response);
}));
await event.updateUI({ title: `${event.registration.id} is ready to play` });
})());
});
self.addEventListener('backgroundfetchfail', (event) => {
console.warn('background fetch failed:', event.registration.failureReason);
});
self.addEventListener('backgroundfetchclick', () => {
clients.openWindow('/downloads/');
});

record.responseReady is a promise because a record’s response may still be streaming when the event fires for a partially failed job; awaiting it inside waitUntil() keeps the worker alive until the copy finishes.

Detecting support and downloading in the foreground instead

Section titled “Detecting support and downloading in the foreground instead”

Firefox and Safari have no backgroundFetch property on the registration. The fallback performs an ordinary fetch() and triggers the browser’s save dialog through a temporary <a download>, which only works while the page stays open; the UI should say so.

async function downloadWithFallback(id, urls, title) {
const registration = await navigator.serviceWorker.ready;
if ('backgroundFetch' in registration) {
return registration.backgroundFetch.fetch(id, urls, { title });
}
for (const url of urls) {
const response = await fetch(url);
if (!response.ok) throw new Error(`${url}: ${response.status}`);
const link = document.createElement('a');
link.href = URL.createObjectURL(await response.blob());
link.download = new URL(url, location.href).pathname.split('/').pop();
link.click();
URL.revokeObjectURL(link.href);
}
}

The foreground path buffers each file in memory before saving it, so very large files should be fetched one at a time and the user warned not to navigate away.

Specifications

SpecificationStatus
Background FetchWICG draft
  • Legend
  • Yes
  • Partial
  • Flag
  • No
  • Unknown
Browser / PlatformSupportVersionsConfidenceSourceNotes
Chrome (Desktop)#Yes74highsource—
Chrome (Android)#Yes74highsource1
Edge (Desktop)#Yes79highsource2
Firefox (Desktop)#No—highsource3
Firefox (Android)#No—highsource45
Safari (macOS)#No—highsource6
Safari (iOS)#No—highsource78
Samsung Internet#Yes11.0highsource9
WebView (Android)#No—highsource10
  1. Derived by browser-compat-data mirroring from Chrome.
  2. Derived by browser-compat-data mirroring from Chrome.
  3. No Firefox support is recorded in browser-compat-data.
  4. No Firefox for Android support is recorded in browser-compat-data.
  5. Derived by browser-compat-data mirroring from Firefox.
  6. No Safari support is recorded in browser-compat-data.
  7. No Safari on iOS support is recorded in browser-compat-data.
  8. Derived by browser-compat-data mirroring from Safari.
  9. Derived by browser-compat-data mirroring from Chrome Android.
  10. No WebView Android support is recorded in browser-compat-data.

Source data: /compatibility/background-fetch.json · Global usage: 75 % (StatCounter 2026-09, CC BY-SA 4.0)

Source: spec · MDN · Last verified 2026-10-03 · Confidence: high (computed from sources)