0

我有域https://test.com。以下是我的服务人员代码

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);
          }
        })
      );
    })
  );
});

我需要缓存跨域资产。上面的代码抛出 Failed to load https://otherdomain.com/planet-styles.min.css:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问来源“ https://test.com ”。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

4

0 回答 0