Registering a Sync Event
You'll learn: How to queue background sync tasks using registration.sync.register() so your app can retry failed operations when connectivity returns.
The Core Idea
Once you've detected a failed network request (like a form submission or API call), you need to tell the service worker to retry it later. This is where registration.sync.register() comes in. Think of it like adding a task to a "to-do list" that the browser will execute when conditions improve—even if your page is closed.
You call this method from your application code (not inside the service worker itself). It takes a tag name as an argument—a unique identifier for the sync event you're requesting.
Using registration.sync.register()
Here's the basic pattern:
// In your application code (e.g., app.js)
navigator.serviceWorker.ready.then(registration => {
return registration.sync.register('sync-messages');
});
The tag name ('sync-messages' in this example) acts like a category. When the browser determines the device is online, it fires a sync event in your service worker with that tag, allowing you to handle all queued "sync-messages" tasks together.
Practical Example: Queuing a Failed POST
// When a form submission fails
fetch('/api/messages', {
method: 'POST',
body: JSON.stringify(messageData)
})
.catch(() => {
// Store data locally first
saveToIndexedDB(messageData);
// Request background sync
return navigator.serviceWorker.ready.then(registration => {
return registration.sync.register('retry-message');
});
});
You typically register a sync event after storing the failed request's data locally (using IndexedDB or Cache Storage), so your service worker knows what to retry later.
Key Takeaway: Use registration.sync.register('tag-name') in your app code to queue background tasks that will trigger a sync event in your service worker when connectivity is restored.