BackgroundSync
Defer work until the user has connectivity. Wraps the Background Sync API (SyncManager) plus the related Periodic Background Sync - register tags from C# and let the service worker do the actual work when its sync event fires.
@inject Bit.Butil.BackgroundSync backgroundSyncMDN reference
IsSupported / IsPeriodicSupported before relying on them.
/sw.js first - its
sync handler logs every fired tag to the DevTools console.
IsSupported is true when the runtime exposes ServiceWorkerRegistration.sync; IsPeriodicSupported checks for ServiceWorkerRegistration.periodicSync.
var oneShot = await backgroundSync.IsSupported();
var periodic = await backgroundSync.IsPeriodicSupported();Background sync tags are stored on a service worker registration, so one must exist before Register or GetTags can succeed. This button registers the same minimal /sw.js used across this category.
Bit.Butil.ServiceWorker serviceWorker
await serviceWorker.Register("/sw.js");Register queues a one-shot sync under a tag; the service worker's sync event fires for that tag once the device is online (immediately, if it already is). GetTags lists the tags currently registered. Registering the same tag twice coalesces into one pending sync.
var ok = await backgroundSync.Register("sync-outbox");
string[] tags = await backgroundSync.GetTags();Periodic sync wakes the service worker at a browser-chosen cadence, never more often than the minimum interval you pass (in milliseconds). It requires the periodic-background-sync permission, which Chromium only grants to installed web apps (PWAs) with sufficient site engagement - expect a rejection when running this demo from a plain tab.
// minimum interval: 1 hour (the browser may extend it)
var ok = await backgroundSync.RegisterPeriodic("refresh-feed", 60 * 60 * 1000);
string[] tags = await backgroundSync.GetPeriodicTags();
var removed = await backgroundSync.UnregisterPeriodic("refresh-feed");sync / periodicsync handlers - the demo worker simply logs the tag, so open
the DevTools console (and, in Chromium, DevTools, Application, Service workers, where you can also
dispatch a sync event manually) to observe it firing.
API reference
ValueTask<bool> IsSupported()ValueTask<bool> IsPeriodicSupported()ValueTask<bool> Register(string tag)ValueTask<string[]> GetTags()ValueTask<bool> RegisterPeriodic(string tag, long minInterval)ValueTask<string[]> GetPeriodicTags()ValueTask<bool> UnregisterPeriodic(string tag)