2
votes

I have two service workers in my application.

The first is automatically generated by create-react-app via workbox and is responsible for caching static build assets such as the compiled javascript and css files.

The second was manually created by me and is responsible for sending out push notifications for when the user receives a new message in the application.

The issue is that both of these require access to the root scope, and I have just recently found out that two service workers cannot share a scope.

How do I reconcile this? The second service worker (for push notifications) is only registered when the user clicks to allow push notifications within the app, like so:

function subscribeUserToPush(cb) {
  if ('Notification' in window && navigator.serviceWorker) {
    return navigator.serviceWorker.register('/sw-notifications.js').then(function(registration) {
      let subscribeOptions = {
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array('the-code-qc=')
      };

      return registration.pushManager.subscribe(subscribeOptions);
    }).then(cb);
  }
}

Both do not work unless they are in the root scope. How can I have them both work when there is the restriction put in place that only one service worker can use each scope?

1
How about creating 1 sw at the root level and another in nested scope level? - Vimal Patel

1 Answers

1
votes

I would recommend using create-react-app v4, along with the cra-template-pwa.

That will give you a Workbox-based service worker that could be fully customized with additional logic, like your push notification code.

Earlier versions of c-r-a unfortunately are not customizable in this regard.