Reputation: 123
i want to cache all json resources in a directory on my websites's cdn with workbox service worker
resources url :
https://cdn.example.com/mydir/*.json
and my service worker is at:
https://example.com/service-worker.js
i wrote my cache code as below
workbox.routing.registerRoute(
/mydir\/.+\.json$/,
new workbox.strategies.CacheFirst({
plugins: [
new workbox.cacheableResponse.Plugin({
statuses: [0, 200]
})
]
})
);
but i get this error from workbox:
The regular expression '/mydir\/.+\.json$/' only partially matched against the cross-origin URL 'https://cdn.example.com/mydir/test.json'. RegExpRoute's will only handle cross-origin requests if they match the entire URL.
how can i cache these resources in my service worker ? any idea ?
Upvotes: 2
Views: 1765
Reputation: 123
i found my answer at worbox routing doc:
However, for cross-origin requests, regular expressions must match the beginning of the URL. The reason for this is that it’s unlikely that with a regular expression
new RegExp('/styles/.*\\.css')
you intended to match third-party CSS files.https://cdn.third-party-site.com/styles/main.css https://cdn.third-party-site.com/styles/nested/file.css https://cdn.third-party-site.com/nested/styles/directory.css
If you did want this behaviour, you just need to ensure that the regular expression matches the beginning of the URL. If we wanted to match the requests for https://cdn.third-party-site.com we could use the regular expression
new RegExp('https://cdn\\.third-party-site\\.com.*/styles/.*\\.css')
https://cdn.third-party-site.com/styles/main.css https://cdn.third-party-site.com/styles/nested/file.css https://cdn.third-party-site.com/nested/styles/directory.css
so i changed my routing regex to:
/^https:\/\/cdn\.example\.com\/mydir\/.+\.json$/
and now workbox caching is working
Upvotes: 3
Reputation: 5253
You have to tune your regex so that it matches the whole domain. A bit more verbose but it makes sure that you actually wanted to cache this and that from the exact domain.
So the path (/mydir/bla/blu/bla.json) is not enough, instead match against the whole address (https://sub.domain.com/mydir/bla/blu/bla.json).
Upvotes: 1