I am trying to implement offline capabilities for my web app but I'm experiencing some strange behavior while offline and it's probably something I'm missing since it's reproducible both in Chrome and Firefox.
I'll describe below what the sample app I created does:
Steps to reproduce
- Open a new Chrome tab and open console view.
- Navigate to sample app (hosted on Netlify).
- Observe log messages confirming the installation and activation of service worker, plus the creation and population of the app's cache storage.
- Go to application tab in developer tools and confirm that cache was created and populated
- Under "Service Worker" enable "Offline" to make network unavailable.
- Alternatively just turn off your wifi/network.
- Refresh page.
Observed behavior
- The cache storage
MyCache
previously created by the service worker disappears.
Expected behavior
- The page fails to load as expected but the cache storage should remain available after refreshing so that the app can use it for serving content while being offline.
HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vanishing cache storage test</title>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js')
.then((registration) => {
console.log('Service worker registered sucessfully:', registration);
})
.catch((error) => {
console.error('Failed to register service worker:', error.stack);
});
});
}
</script>
</head>
<body>
<h1>Hi!</h1>
</body>
</html>
Service worker
const CACHE_NAME = 'MyCache';
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME)
.then((cache) => {
return cache.add('/');
})
.then(() => {
console.debug(CACHE_NAME, 'created and populated');
})
);
});
self.addEventListener('activate', (event) => {
console.debug('SW activated');
});
OS + browser version
Google Chrome Version: 87.0.4280.141 (Official Build) (x86_64) Firefox version: 85.0b5 (64-bit, Developer Edition) OS: macOS v11.1 (Big Sur)
Question
Is this expected behavior? If so, why?
Notes
- I couldn't test on Safari because I there's no visible way to visualize cache storage content (ugh!).
- After refreshing on Firefox, you might need to close and reopen devtools to have the Storage tab refresh itself.
before going offline: cache is A-OK after refreshing while offline: cache is gone!