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 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 paste the code from that file into your Service Worker source.

Batch will wait up to 5 seconds for your Service Worker to be ready. If needed, you can extend the duration by adding serviceWorkerTimeout: 10 (where 10 would be in seconds) in the setup object of the JavaScript tag.

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

Add the following line to the JavaScript tag's setup object.

useExistingServiceWorker: true