registerServiceWorker method

Future<void> registerServiceWorker({
  1. String? url,
  2. String? scope,
})

Re-registers this manager's service worker, replacing the previous registration (which is unregistered first).

  • url: script URL of a custom worker (e.g. a copy of js_notifications-sw.js extended with app-specific message handling for postAction payloads). When null, the bundled worker asset is used — pass only scope to keep the bundled worker but register it under a custom scope.
  • scope: registration scope. When null the browser default (the script's directory) is used. A scope outside the script's directory requires the server to send a Service-Worker-Allowed header; for the bundled asset (served from assets/packages/js_notifications/assets/) any broader scope — e.g. /js_notifications/ — needs that header.

Implementation

Future<void> registerServiceWorker({String? url, String? scope}) async {
  // Never race the automatic bundled registration (and initialise on demand
  // if the caller never awaited init()).
  await _ensureInitialized();

  final delegate = _container;
  if (delegate == null) {
    printDebug("Service workers are not supported in this browser; cannot register a service worker.", tag: tag);
    return;
  }

  try {
    await _registration?.unregister().toDart;
  } catch (e) {
    printDebug("Failed to unregister previous service worker: $e", tag: tag);
  }
  _registration = null;

  _customUrl = url;
  await _register(delegate, url ?? _resolveBundledServiceWorkerUrl(), scope: scope);
}