服务人员中断301重定向

Der*_*son 5 javascript service-worker progressive-web-apps

我在WordPress网站上使用服务人员,并且弄乱了从https://example.com/pagehttps://example.com/page/的重定向。

第一次加载后,转到不带斜杠的URL眨眼浏览器说“无法访问此站点”,而Firefox说“内容损坏”。

基于我对https://medium.com/@boopathi/service-workers-gotchas-44bec65eab3f#.hf3r4pbcs的阅读以及如何更改请求的标头?我必须检测何时响应为3xx并将重定向模式设置为手动。

但是,根据我的研究,我没有尝试过任何方法。我该如何解决?

当前服务工作者文件:

var cacheName = 'v14';

var urlsToCache = [
  // list of URLs to precache
];

self.addEventListener('install', event => {

  function onInstall(event) {
    return caches.open(cacheName)
      .then(cache => cache.addAll(urlsToCache));
  }

  event.waitUntil(
    onInstall(event)
      .then(() => self.skipWaiting())
  );

});

self.addEventListener('activate', event => {

  function onActivate (event) {
    return caches.keys()
      .then(cacheKeys => {
        var oldCacheKeys = cacheKeys.filter(key => key.indexOf(cacheName) !== 0);
        var deletePromises = oldCacheKeys.map(oldKey => caches.delete(oldKey));
        return Promise.all(deletePromises);
      })
  }

  event.waitUntil(
    onActivate(event)
      .then(() => self.clients.claim ())
  );
});

self.addEventListener('fetch', event => {

  function onFetch (event) {
    // Let's not interfere with requests for stuff that doesn't need to be cached
    // or could prevent access to admin if it is
    if (event.request.url.match(/wp-admin/) || event.request.url.match(/wp-login/) || event.request.url.match(/preview=true/) || event.request.url.match(/wp-includes/) || event.request.url.match(/plugins/) || event.request.url.match(/google-analytics/) || event.request.url.match(/gravatar\.com/) || event.request.url.match(/login/) || event.request.url.match(/admin/) || event.request.method !== 'GET') {
      return;
    }

    // Determine type of asset
    var request = event.request,
        acceptHeader = request.headers.get('Accept'),
        resourceType = 'static';

    if(acceptHeader.indexOf('text/html') !== -1) {
      resourceType = 'content';
    } else if(acceptHeader.indexOf('image') !== -1) {
      resourceType = 'image';
    }

    // Network first for HTML and images
    if(resourceType === 'content') {
      event.respondWith(fetch(request.url, {
        method: request.method,
        headers: request.headers,
        mode: 'same-origin', // need to set this properly
        credentials: request.credentials,
        redirect: 'manual'
      })
        .then(response => addToCache(request, response)) // read through caching
        .catch(() => fetchFromCache(event))
        .catch(() => offlineResponse(resourceType))
      )
    }

    // Cache first for static assets
    else if(resourceType === 'static' || resourceType === 'image') {
      event.respondWith(fetchFromCache(event)
        .catch(() => fetch(request))
        .then(response => addToCache(request, response))
        .catch(() => offlineResponse(resourceType))
      )
    }
  }

  onFetch(event);

});

function addToCache(request, response) {

  if(response.ok) { // only 200s
    var copy = response.clone(); // Because responses can only be used once
    caches.open(cacheName)
      .then(cache => {
        cache.put(request, copy);
      });

    return response;
  }

}

function fetchFromCache (event) {

  return caches.match(event.request)
    .then(response => {
      if(!response) {
        // A synchronous error that will kick off the catch handler
        throw Error('${event.request.url} not found in cache');
      }
    return response;
  });

}

function offlineResponse (resourceType) {

  if(resourceType === 'content') {
    return caches.match('/offline/');
  }
  return undefined;

}
Run Code Online (Sandbox Code Playgroud)

And*_*ast 1

当特定网站遇到错误时,我建议先清除浏览器缓存并删除为该网站保存的 cookie。内容损坏错误可能是由于在服务器中运行过时的软件引起的。

关于Service Worker需要注意的是,它是一个JavaScript Worker。所以,它不能直接访问 DOM。相反,Service Worker 可以通过响应通过 postMessage 发送的消息来与其控制的页面进行通信。