I’m working on a Flask web application and I want to implement an offline page that displays when the user is offline or the server is down. I’ve set up a basic Flask app and a service worker, but I’m having trouble getting the offline page to display correctly when the internet is disconnected or the server is down.
app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/offline')
def offline():
return render_template('offline.html')
if __name__ == '__main__':
app.run(debug=True)
static/service-worker.js
const CACHE_NAME = 'my-cache-v1';
const urlsToCache = [
'/',
'/offline',
'/static/styles.css',
// Add other URLs you want to cache
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(urlsToCache))
);
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => response || fetch(event.request))
);
});
self.addEventListener('activate', event => {
const cacheWhitelist = [CACHE_NAME];
event.waitUntil(
caches.keys().then(cacheNames =>
Promise.all(
cacheNames.map(cacheName => {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
)
)
);
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Flask App</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
</head>
<body>
<h1>Welcome to My Flask App!</h1>
<!-- Content of your main page -->
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/static/sw.js')
.then(function(registration) {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
})
.catch(function(error) {
console.log('ServiceWorker registration failed: ', error);
});
}
</script>
</body>
</html>
offline.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Offline</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<h1>Oops! It looks like you're offline.</h1>
<p>Please check your internet connection or try again later.</p>
</body>
</html>
Problem:
When I turn off the Wi-Fi or stop the flask app, I don’t see the offline page. Instead, I get the default chrome error page. What can I do to fix it?
Thank you!