Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make workbox cache cross origin responses?

According to workbox doc, cross domain request should be configured to ensure that regular expression matches the beginning of the URL. However, it doesn't work.

The service worker code is like below.

importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js');

workbox.routing.registerRoute(
  /.*\.(png|jpg|jpeg|svg|gif)/,
  workbox.strategies.cacheFirst()
);

workbox.routing.registerRoute(
  new RegExp('^https://a248.e.akamai.net/.*'),
  workbox.strategies.cacheFirst()
);

In the page, responses from same origin resources are cached, but responses from https://a248.e.akami.net is not.

Anything wrong with my config? or is this a workbox 3.0.0 bug?

like image 919
Morgan Cheng Avatar asked Mar 15 '18 09:03

Morgan Cheng


1 Answers

Do you have CORS enabled on your https://a248.e.akami.net server? If not, you'll be getting back opaque responses, and by default, those will not be cached when using a cacheFirst strategy.

There's a guide for handling third-party requests with a recipe you could use if you want to opt-in to caching those responses when using a cacheFirst strategy:

workbox.routing.registerRoute(
  new RegExp('^https://a248.e.akamai.net/.*'),
  workbox.strategies.cacheFirst({
    plugins: [
      new workbox.cacheableResponse.Plugin({
        statuses: [0, 200]
      })
    ]
  }),
);

You should also see a new warning logged in the JavaScript console when using Workbox v3 in localhost when this situation arises, explaining what's going on.

like image 117
Jeff Posnick Avatar answered Nov 09 '22 15:11

Jeff Posnick