Background Sync Is A PWA Super Power - Part 2
How to implement outbox functionality with the Background Sync API
Oct 24, 2023
In my previous article, I wrote about the Background Sync API that enables your web app to schedule tasks while offline and run them when the network is back.
Quite some readers asked me if it was possible to create some sort of “outbox” functionality, similar to the outbox of an email app: messages are stored when offline, and when the network is back the app loops through the saved messages and sends them. One issue that came up repeatedly was that some subscribers struggled to implement this with the online and offline events.
Actually, those events are not needed because, as I mentioned in the previous article, the beauty of the Background Sync API is that it handles all this for you.
Let’s look at how we can implement an “outbox” with Background Sync.
We will build upon the demo that I added to What PWA Can Do Today which sends a push notification when the app is online but defers these when the app is offline until the network is back:
Background Sync demo What PWA Can Do Today
www.youtube.com
You may think that we could just execute multiple registration.sync.register calls but then we would need to change the sync-demo tag to something unique, otherwise any call will simply overwrite the previous one.
To solve this, you can in theory change the tag name to something unique, for example, add a timestamp. That way, you can register a separate sync event for each notification but since the event execution time is capped, the browser won’t schedule it indefinitely so it’s better to save the notifications to IndexedDB while offline and loop through them and send them when the app is back online.
But to only save the notifications to IndexedDB when the app is offline would force us to check if the app is offline and, again, the Background Sync API already handles that for us.
The solution for this is to always save any notification to IndexedDB and then immediately register a sync event. The event handler in the Service Worker will retrieve all saved notifications from IndexedDB (which, when the app is online will be only one, the one you just saved) and send them when the app is online. When the app is offline the notification won’t be sent but stay inside IndexedDB.
Any other notification that is sent while offline will simply be saved and when the network is back the sync event fires and the app loops through all notifications in IndexedDB, sends them, and then removes them. This way, you can be sure no notification will be lost and all will be sent.
// inside the service worker an event handler is registered
// for the 'sync' event that sends the notification
self.addEventListener('sync', e => {
e.waitUntil(
self.registration.showNotification(title, options)
.catch(err => console.log(err))
)
});
// in the browser:
const syncButton = document.querySelector('#sync-button');
const registration = await navigator.serviceWorker.getRegistration();
if('sync' in registration) {
syncButton.addEventListener('click', async () => {
await registration.sync.register('sync-demo');
});
}
This does mean there is some overhead of saving notifications to IndexedDB but since it’s optimized for fast storage this is a perfectly fine trade-off to make sure important tasks (like sending messages and network calls) are always executed, even if the network is not available.
Let’s update the code to implement this:
// inside the service worker an event handler is registered
// for the 'sync' event that sends the notification
self.addEventListener('sync', e => {
e.waitUntil(
getNotifications()
.then((notifications) => {
const requests = notifications.map(({message}) => {
return self.registration.showNotification(title, options);
});
return Promise.all(requests)
.then(() => openStore())
.then(idbStore => idbStore.clear());
})
)
});
// in the browser:
const syncButton = document.querySelector('#sync-button');
const registration = await navigator.serviceWorker.getRegistration();
let notificationNum = 0;
if('sync' in registration) {
syncButton.addEventListener('click', async () => {
const notification = {
timestamp: Date.now(),
title: 'Background Sync Demo',
message: `This is notification #${++notificationNum}`,
};
const idbStore = await getStore();
await idbStore.add(notification);
await registration.sync.register(`sync-demo`);
});
}
In the event handler for the sync event we now get all notifications from IndexedDB, loop through them, and show each one. Then we clear all notifications from IndexedDB.
The click handler for the button now saves each notification to IndexedDB and then registers a sync (which will fire and send the notification immediately when online).
I omitted the code for IndexedDB for brevity but I hope you get the idea so you can implement it yourself for your own use cases.
Check the demo!