1

I have domain https://test.com. Below is my service worker code

var CACHE_NAME = 'my-site-mas2';
var urlsToCache = [
  '/',
  '/scripts/app.js',
  '/scripts/test.js',
  '/scripts/test1.js',
  '/scripts/test2.js',
  'https://otherdomain.com/planet-styles.min.css'
];

self.addEventListener('install', function(event) {
  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});

// var corsRequest = new Request(url, { mode: 'cors' });
self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        }

        return fetch(event.request);
      }
    )
  );
});

self.addEventListener('activate', function(event) {

  var cacheWhitelist = ['my-site-mas2'];

  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.map(function(cacheName) {
          if (cacheWhitelist.indexOf(cacheName) === -1) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

I need to cache cross domain assests. Above code throws Failed to load https://otherdomain.com/planet-styles.min.css: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://test.com' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

  • The error message already says it. You need to set the HTTP Header `Access-Control-Allow-Origin` header on the server side. If you want to allow the access from everywhere an appropriate value would be `*`. Otherwise give a list of allowed origins. – newBee Jun 11 '18 at 06:59
  • Also relevant: https://stackoverflow.com/questions/39109789, since if you can't enable CORS for that URL, you do have the option of explicitly making a `no-cors` Request and then calling `cache.put()` to save the opaque response. – Jeff Posnick Jun 11 '18 at 18:39

0 Answers0