1

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!

3
  • 1
    Is your service worker getting registered? Can you check the console if it giving any error. You are trying to register service worker with file name 'sw.js' but your file name is 'service-worker.js' Commented Aug 18, 2024 at 9:19
  • yes, I checked the 'sw.js' file and it's logged and active. Commented Aug 20, 2024 at 13:43
  • Can you try using "url_for" path. someting like this navigator.serviceWorker.register("{{ url_for('static', filename='service-worker.js') }}") Commented Aug 21, 2024 at 5:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.