簡體   English   中英

如何在Firefox Service Worker中處理206個響應

[英]How to handle 206 responses in Firefox service workers

在測試服務人員的項目並使用Google提供的示例時:

/*
 Copyright 2016 Google Inc. All Rights Reserved.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

// Names of the two caches used in this version of the service worker.
// Change to v2, etc. when you update any of the local resources, which will
// in turn trigger the install event again.
const PRECACHE = 'precache-v1';
const RUNTIME = 'runtime';

// A list of local resources we always want to be cached.
const PRECACHE_URLS = [
  'index.html',
  './', // Alias for index.html
  'styles.css',
  '../../styles/main.css',
  'demo.js'
];

// The install handler takes care of precaching the resources we always need.
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(PRECACHE)
      .then(cache => cache.addAll(PRECACHE_URLS))
      .then(self.skipWaiting())
  );
});

// The activate handler takes care of cleaning up old caches.
self.addEventListener('activate', event => {
  const currentCaches = [PRECACHE, RUNTIME];
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
    }).then(cachesToDelete => {
      return Promise.all(cachesToDelete.map(cacheToDelete => {
        return caches.delete(cacheToDelete);
      }));
    }).then(() => self.clients.claim())
  );
});

// The fetch handler serves responses for same-origin resources from a cache.
// If no response is found, it populates the runtime cache with the response
// from the network before returning it to the page.
self.addEventListener('fetch', event => {
  // Skip cross-origin requests, like those for Google Analytics.
  if (event.request.url.startsWith(self.location.origin)) {
    event.respondWith(
      caches.match(event.request).then(cachedResponse => {
        if (cachedResponse) {
          return cachedResponse;
        }

        return caches.open(RUNTIME).then(cache => {
          return fetch(event.request).then(response => {
            // Put a copy of the response in the runtime cache.
            return cache.put(event.request, response.clone()).then(() => {
              return response;
            });
          });
        });
      })
    );
  }
});

來源: https : //github.com/GoogleChrome/samples/blob/gh-pages/service-worker/basic/service-worker.js

我發現Firefox(與野生動物園和Chrome瀏覽器相反)會在event.waitUntil()以及event.respondWith()內引發錯誤,如果某些操作不適用於提取請求(即使它只是206部分內容響應):

服務工作者事件waitUntil()被傳遞了一個承諾,該承諾被'TypeError拒絕:嘗試添加請求時,高速緩存獲得狀態為206的基本響應

這種行為會破壞安裝程序。 如果我這樣向安裝程序添加.catch()

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(PRECACHE)
      .then(cache => cache.addAll(PRECACHE_URLS))
      .then(self.skipWaiting())
      .catch(function(err){
        console.log(err);
        self.skipWaiting();
      })
  );

});

我認為前206個將使預緩存停止(?)

另外在安裝了sw之后,偶爾我會得到一個

服務工作者事件responseWith()已傳遞一個承諾,該承諾被'TypeError:嘗試添加請求時,緩存狀態為206的基本響應返回錯誤狀態

即使沒有發生,如果我嘗試在安裝/預緩存時嘗試打開指向引發206錯誤的網址的鏈接,則會得到:

無法加載“ https://xxxx/yyyyy.mp3 ”。 一個ServiceWorker向FetchEvent.respondWith()傳遞了一個承諾,該承諾以“ TypeError:Cache嘗試添加請求https://xxxx/yyyyy.mp3 ”時得到了狀態為206的基本響應。

在瀏覽器內部,錯誤看起來像文件已損壞

如何正確處理此類錯誤? 像上面那樣捕獲並沒有多大意義,因為它破壞了強制預緩存。 即使那是可以接受的,它似乎也會干擾從那時起發生的每個請求,並可能在以后引起麻煩。

我可以通過將return語句從cache.put()函數內部移出來解決一半的問題:

self.addEventListener('fetch', event => {
  // Skip cross-origin requests, like those for Google Analytics.
  if (event.request.url.startsWith(self.location.origin)) {
    event.respondWith(
      caches.match(event.request).then(cachedResponse => {
        if (cachedResponse) {
          return cachedResponse;
        }

        return caches.open(RUNTIME).then(cache => {
          return fetch(event.request).then(response => {
            // Put a copy of the response in the runtime cache.
            cache.put(event.request, response.clone()).then(() => {
              console.log("logged a file into RUNTIME:");
              console.log(response);
            });
            return response; // and return anyhow whatever came back
          });
        });
      })
    );
  }
});

這樣,sw不會等待cache.put()成功,但是大多數時候它都會被緩存。

這解決了最緊迫的問題,但問題仍然存在

a)強制預緩存仍然被206個響應取消b)萬一我想確保請求在運行時被緩存,我仍然需要做一些retry()函數或其他操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM