Integrating Batch with an existing Service Worker

As you may know, only one Service Worker per domain can be registered. Progressive Web Apps (PWA) come with one, for example.

By default, Batch will try to register its own Service Worker (named batchsdk-worker-loader.js) as soon as possible which makes harder to add your own code in there.

But don't worry, we made it very easy to use Batch even if you already have a Service Worker!

Load Batch into your Service Worker

You'll have to register a Service Worker yourself, early on page load.

You will also need to load Batch into your existing Service Worker. Once you've downloaded the batchsdk-shared-worker.js file, you've got two options:

  • Upload batchsdk-shared-worker.js to your website's root, and import it using importScripts("/batchsdk-shared-worker.js"),
  • or copy and paste the code from that file into your Service Worker source.

By default, Batch will wait up to 10 seconds for your Service Worker to be ready. If needed, you can extend the duration with waitTimeout in the service worker related configuration of the JavaScript tag's setup object.

  batchSDK('setup', {
    ...,
    serviceWorker: {
      waitTimeout: 15 // In seconds
    }
  });

Do NOT import or copy batchsdk-worker-loader.js, as this version is designed for exclusive, Batch-controlled Service Worker usage. Please make sure you import or copy batchsdk-shared-worker.js.

Prevent Batch from registering its own Service Worker

To prevent Batch from registering its own service worker, add the following lines to the JavaScript tag's setup object.

  batchSDK('setup', {
    ...,
    serviceWorker: {
      automaticallyRegister: false,
    }
  });