服务工作者可以获取和缓存跨域资产吗?

时间:2019-02-10 18:31:16

标签: javascript cors cross-domain service-worker

我正在使用Progressive Web app tutorial by Google中的一些服务人员代码,但出现错误:

Uncaught (in promise) TypeError:
 Failed to execute 'clone' on 'Response':
 Response body is already used

该网站将第三方Javascript和样式表用于Web字体。   我想将托管在这些CDN上的资产添加到脱机缓存中。

addEventListener("fetch", function(e) {
  e.respondWith(
    caches.match(e.request).then(function(response) {
        return response || fetch(e.request).then(function(response) {
        var hosts = [
          "https://fonts.googleapis.com",
          "https://maxcdn.bootstrapcdn.com",
          "https://cdnjs.cloudflare.com"
        ];
        hosts.map(function(host) {
          if (e.request.url.indexOf(host) === 0) {
            caches.open(CACHE_NAME).then(function(cache) {
              cache.put(e.request, response.clone());
            });
          }
        });
        return response;
      });
    })
  );
});

这些托管在流行的CDN上,所以我的直觉是他们应该对CORS标头做正确的事情。

以下是我要缓存的HTML中的资产:

<link rel="stylesheet" type="text/css"
      href="https://fonts.googleapis.com/css?family=Merriweather:900,900italic,300,300italic">
<link rel="stylesheet" type="text/css"
      href="https://fonts.googleapis.com/css?family=Lato:900,300" rel="stylesheet">
<link rel="stylesheet" type="text/css"
      href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css">
<script type="text/javascript" async
        src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>

根据控制台日志,服务工作者正在尝试获取这些资产:

Fetch finished loading:
 GET "https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css".
 sw.js:32
Fetch finished loading:
 GET "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML".
 sw.js:32
Fetch finished loading:
 GET "https://fonts.googleapis.com/css?family=Merriweather:900,900italic,300,300italic".
 sw.js:32
Fetch finished loading:
 GET "https://fonts.googleapis.com/css?family=Lato:900,300".
 sw.js:32
Fetch finished loading:
 GET "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/config/TeX-AMS-MML_HTMLorMML.js?V=2.7.1".
 sw.js:32
Fetch finished loading:
 GET "https://maxcdn.bootstrapcdn.com/font-awesome/latest/fonts/fontawesome-webfont.woff2?v=4.7.0".
 sw.js:32

如果按照Why does fetch request have to be cloned in service worker?的建议删除clone,我将得到相同的错误:

TypeError: Response body is already used

如果我将{ mode: "no-cors" }添加到每个Service worker CORS issue的提取中,我将得到相同的错误和以下警告:

The FetchEvent for
 "https://maxcdn.bootstrapcdn.com/font-awesome/latest/fonts/fontawesome-webfont.woff2?v=4.7.0"
 resulted in a network error response: an "opaque" response was
 used for a request whose type is not no-cors
The FetchEvent for
 "https://fonts.gstatic.com/s/lato/v14/S6u9w4BMUTPHh50XSwiPGQ3q5d0.woff2"
 resulted in a network error response: an "opaque" response was
 used for a request whose type is not no-cors
The FetchEvent for
 "https://fonts.gstatic.com/s/lato/v14/S6u9w4BMUTPHh7USSwiPGQ3q5d0.woff2"
 resulted in a network error response: an "opaque" response was
 used for a request whose type is not no-cors
The FetchEvent for
 "https://fonts.gstatic.com/s/merriweather/v19/u-4n0qyriQwlOrhSvowK_l521wRZWMf6hPvhPQ.woff2"
 resulted in a network error response: an "opaque" response was
 used for a request whose type is not no-cors

我可以在服务工作者的install事件中将这些资产添加到静态缓存中,但是我有理由仅在fetch事件中将它们添加到缓存中。

1 个答案:

答案 0 :(得分:3)

使用clone()使您处在正确的轨道上,但是时机很重要。您需要确保在执行最后一个clone()之前调用return response,因为这时,响应将传递到服务工作者的客户端页面,并且其主体将被“消耗”。 / p>

有两种解决方法:要么在执行异步缓存代码之前调用clone(),要么将return response语句延迟到缓存完成之后。

我将建议第一种方法,因为这意味着您最终将尽快获得对页面的响应。我还建议您重写代码以使用async/await,因为它更具可读性(并且受今天也支持服务工作者的任何浏览器的支持)。

addEventListener("fetch", function(e) {
  e.respondWith((async function() {
    const cachedResponse = await caches.match(e.request);
    if (cachedResponse) {
      return cachedResponse;
    }

    const networkResponse = await fetch(e.request);

    const hosts = [
      'https://fonts.googleapis.com',
      'https://maxcdn.bootstrapcdn.com',
      'https://cdnjs.cloudflare.com',
    ];

    if (hosts.some((host) => e.request.url.startsWith(host))) {
      // This clone() happens before `return networkResponse` 
      const clonedResponse = networkResponse.clone();

      e.waitUntil((async function() {
        const cache = await caches.open(CACHE_NAME);
        // This will be called after `return networkResponse`
        // so make sure you already have the clone!
        await cache.put(e.request, clonedResponse);
      })());
    }

    return networkResponse;
  })());
});

注意:(async function() {})()语法可能看起来有些怪异,但这是在立即执行的函数中使用async / await的捷径,该函数将返回promise。参见http://2ality.com/2016/10/async-function-tips.html#immediately-invoked-async-function-expressions

对于原始代码,您需要先克隆响应,然后再进行异步缓存更新:

        var clonedResponse = response.clone();
        caches.open(CACHE_NAME).then(function(cache) {
          cache.put(e.request, clonedResponse);
        });

Service Worker primer by Google的示例代码显示了正确的方法。该代码带有带“重要”注释的注释,但是它只是强调克隆,而不是克隆时遇到的问题:

        // IMPORTANT: Clone the response. A response is a stream
        // and because we want the browser to consume the response
        // as well as the cache consuming the response, we need
        // to clone it so we have two streams.
        var responseToCache = response.clone();

        caches.open(CACHE_NAME)
          .then(function(cache) {
            cache.put(event.request, responseToCache);
          });

        return response;