Registering a custom Service Worker

Uploading the Service Worker to a folder of your website

Some CMS don't allow you to upload a file directly at the root of your website. In this case, you can upload the file to a folder of your website.

Upload the service worker

Let's say you can only upload the batchsdk-worker-loader.js file to the media folder of your website, the path to this file will be: https://mywebsite.com/media/batchsdk-worker-loader.js.

The server needs to get a success response with GET and OPTIONS methods.

The Service-Worker-Allowed header with the value " /" has to be served. Otherwise, you will need to add it.

You can test it as below, from the terminal, with httpie for example (test with the service worker path).

check server

Register the service worker

You need to manually register the service worker with your custom path and give the returned promise to the JavaScript tag's setup object as following:

  const registrationPromise = navigator.serviceWorker.register("/media/batchsdk-worker-loader.js");
  batchSDK('setup', {
    ...,
    // Service worker related configuration
    serviceWorker: {
      // Set it to `false` to prevent Batch from registering its own service worker
      automaticallyRegister: false,
      // A promise that resolves the service worker registration with your custom path 
      registration: registrationPromise 
    }
  });

Registering a Service Worker in a Sub-Scope

You may want to register a Service Worker in a sub-scope that does not control the current page.

To do that, You need to manually register the service worker with your sub-scope and prevent Batch from registering its own by updating the JavaScript tag's setup object as following:


  const subScopeRegistration = navigator.serviceWorker.register("batchsdk-worker-loader.js",
    { scope: "your_scope" });

  batchSDK('setup', {
    ...,
    // Service worker related configuration
    serviceWorker: {
      // Time Batch will wait for your service worker to be ready
      waitTimeout: 10,
      // Set it to `false` to prevent Batch from registering its own service worker
      automaticallyRegister: false,
      // A promise that resolves the service worker registration 
      registration: subScopeRegistration
    }
  });