Library Affected:
workbox-sw
Browser & Platform:
"all browsers".
Issue or Feature Request Description:
In sw-toolbox, I was able to manually cache any url like this:
Inside the sw.js:
self.addEventListener('message', function(event) {
if (event.data && event.data.action === 'navigate') {
caches.open(cacheName).then(function(cache) {
var req = new Request(event.data.url);
toolbox.cache(req.url);
});
}
});
Then I could call anywhere:
navigator.serviceWorker.controller.postMessage({ action: 'navigate', url: '/about' });
Now using this example: https://workboxjs.org/examples/workbox-sw/ is there a way to do the same ?
Ok I found:
importScripts('https://unpkg.com/[email protected]/build/importScripts/workbox-runtime-caching.dev.v0.0.2.js');
...
const custom = new workbox.runtimeCaching.RequestWrapper();
self.addEventListener('message', function(event) {
if (event.data && event.data.action === 'navigate') {
custom.fetchAndCache({ request: new Request(event.data.url) });
}
});
The solution does not work in 3.0.0-beta
In general, you can use the Cache Storage API directly to accomplish this. The one Workbox-specific wrinkle is that you might want to get the name of the default runtime cache that Workbox uses when you don't specify your own cache name. You can get this in v3 via workbox.core.cacheNames.runtime.
So the equivalent to https://github.com/GoogleChrome/workbox/issues/807#issue-258338019 is:
self.addEventListener('message', event => {
if (event.data && event.data.action === 'navigate') {
// Just use the Cache Storage API directly,
// and add to the default runtime cache:
caches.open(workbox.core.cacheNames.runtime)
.then(cache => cache.add(event.data.url));
}
});
We've got some info about this in the v3 preview docs at https://developers.google.com/web/tools/workbox/guides/configure-workbox#configure_cache_names
Let's add this to V3 docs.
Yes, it would be nice to have a public method for this, because initial resources loaded while web-worker is installing will not be added to the runtime cache before the second visit, so there is a need to send path for the landing-page and its page-specific assets manually into runtime-caching if you would like to offer them offline on next visit
@gerhardsletten if support lands I can immediately add to next-offline 馃敟