5

I'm trying to put a Service Worker on a website and I want to load the service worker script from a CDN. However when I load the service worker from a different domain I get the following error.

ServiceWorker DOMException: Failed to register a ServiceWorker: The origin of the provided scriptURL ('https://cdndomain.com') does not match the current origin ('http://mydomain')

Is there a way to load a Service worker from a CDN? I've seen few push notification services doing it out there, can we use eval to execute service worker js locally?

Any workarounds for this? Thanks

Here is how my current code looks like

 if (navigator.serviceWorker) {
   console.log("ServiceWorkerssupported");

   navigator.serviceWorker.register('https://cdn.com/sw.js', {
     scope: './'
   })
   .then(function(reg) {
     console.log("ServiceWorkerstered", reg);
   })
   .catch(function(error) {
     console.log("Failedegister ServiceWorker", error);
   });
}
rksh
  • 3,920
  • 10
  • 49
  • 68
  • Seems like there's solution here: https://stackoverflow.com/questions/21913673/execute-web-worker-from-different-origin – Siniša Apr 30 '20 at 03:40

1 Answers1

1

Service worker has to be coming from the same domain - because the location of the Service Worker file matters a lot.

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js').then(function(registration) {
    // Registration was successful
    console.log('ServiceWorker registration successful with scope: ',    registration.scope);
  }).catch(function(err) {
    // registration failed :(
    console.log('ServiceWorker registration failed: ', err);
  });
}

One subtlety with the register method is the location of the service worker file. You'll notice in this case that the service worker file is at the root of the domain. This means that the service worker's scope will be the entire origin. In other words, this service worker will receive fetch events for everything on this domain. If we register the service worker file at /example/sw.js, then the service worker would only see fetch events for pages whose URL starts with /example/ (i.e. /example/page1/, /example/page2/).

You can use a php script as a proxy to load it from elsewhere.

Charlie
  • 22,886
  • 11
  • 59
  • 90