Library Affected:
workbox-sw
Issue or Feature Request Description:
In some case user browse some content and page predict that it should cache something for use offline (i.e. next page, related content) can we send postMessage for main page to ask service worker cache some page or file?
The Cache Storage API is exposed from web pages, and not just in the context of a service worker.
So, while it's possible to set up a message event listener in your service worker, and use that to add URLs to the cache, what I'd recommend doing instead is just using a standard cache name for your on-demand cache, and add to it from the context of your web page.
E.g.:
// In your web app's JavaScript:
async function addToCache(urls) {
const myCache = await window.caches.open('my-cache');
await myCache.addAll(urls);
}
// Call addToCache whenever you'd like. E.g. to add to cache after a page load:
window.addEventListener('load', () => {
// ...do something to determine the list of related URLs for the current page...
addToCache(['/static/relatedUrl1', '/static/relatedUrl2']);
});
And then you would just make sure to have a corresponding route using Workbox in your service worker that actually matched requests for the URLs in that cache, and used an appropriate strategy for them:
// In your service worker's JavaScript:
workbox.routing.registerRoute(
new RegExp('^/static/'),
workbox.strategies.staleWhileRevalidate({
cacheName: 'my-cache', // Use the same cache name as before.
})
);
I'll leave this issue open to track adding this code snippet to the docs as a recipe.
@jeffposnick Thank you for your solution
@jeffposnick
Is not there a way around this?
Being able to cache through the workbox because I use it throughout my workbox application and it is spectacular.
example, pass an always different query per module.
graphql?mod=person
graphql?mod=company
Most helpful comment
The Cache Storage API is exposed from web pages, and not just in the context of a service worker.
So, while it's possible to set up a
messageevent listener in your service worker, and use that to add URLs to the cache, what I'd recommend doing instead is just using a standard cache name for your on-demand cache, and add to it from the context of your web page.E.g.:
And then you would just make sure to have a corresponding route using Workbox in your service worker that actually matched requests for the URLs in that cache, and used an appropriate strategy for them:
I'll leave this issue open to track adding this code snippet to the docs as a recipe.