Django ServiceWorker not in scope

Viewed 194

Thanks for your time.

i got a Django web app and am trying to set a PWA for it.

I've been seting the files (sw.js, manifest.json, install_sw.html) through urls with TemplateView class:

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('config/', include('config.urls')),
    path('products/', include('products.urls')),
    path('cart/', include('cart.urls')),
    path('accounts/', include('allauth.urls')),
    path('home/', home_view, name='home'),
    path('sw.js/', (TemplateView.as_view(template_name="admin/sw.js", content_type='application/javascript', )), name='sw.js'),
    path('manifest.json/', (TemplateView.as_view(template_name="admin/manifest.json", content_type='application/json', )), name='manifestjson'),
    path('install_sw/', (TemplateView.as_view(template_name="admin/install_sw.html", content_type='text/html', )), name='install_sw'),
]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

although i keep getting this error:

no matching service worker detected. You may need to reload the page, or check that the scope of the service worker for the current page encloses the scope and start URL from the manifest

and even with the serviceworker being found and his code running, i don't think its getting installed.

Lighthouse told me so, and when i leave the page the service worker ain't in the list anymore, so im not able to run it offline because the cache gets deleted.

files under:

sw.js:


{
    const cacheName = 'cache-v1';
    const resourcesToPrecache = [
        "{% url 'sw.js' %}",
        "{% url 'home' %}",
        "{% url 'install_sw' %}"
    ];

    self.addEventListener('install', function (event) {
        console.log('sw install event!');
        event.waitUntil(
            caches.open(cacheName)
                .then(function (cache) {
                    console.log('cache added')
                    return cache.addAll(resourcesToPrecache);
                }
                )
        );
    });

    self.addEventListener('fetch', function (event) {
        console.log(event.request.url);

        event.respondWith(
            caches.match(event.request).then(function (response) {
                return response || fetch(event.request);
            })
        );
    });
};

console.log('ok')

manifest.json

{
    "short_name": "Mega",
    "name": "MegaMagazine",
    "scope": "/",
    "icons": [
        {
            "src": "/static/m1.png",
            "type": "image/png",
            "sizes": "144x144"
        }
    ],
    "start_url": "/",
    "background_color": "#3367D6",
    "display": "standalone",
    "theme_color": "#3367D6",
    "prefer_related_applications": false
}

install_sw.html

<!doctype html>

<head>
    <link rel="manifest" href="{% url 'manifestjson' %}">
</head>
<title>installing service worker</title>

<body>
    <img src="/static/m1.png" alt="">
    <script type='text/javascript'>
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register("{% url 'sw.js' %}").then(function (registration) {
                console.log('Service worker  registrado com sucesso:', registration, registration.scope);
            }).catch(function (error) {
                console.log('Falha ao Registrar o Service Worker:', error);
            });
        } else {
            console.log('Service workers não suportado!');
        }
    </script>

</body>

files

1 Answers

Your Project must be serve over localhost:[8000] or HTTPS.

If you serve it on local network like 192.168.43.101 you should change it to localhost or install SSL crt. on it.

Service workers require a Secure Context.

(MDN page, Chromium page).

The value of window.isSecureContext indicates whether [SecureContext] features are visible or hidden. (This is true on a file:// URL and the serviceWorker API will be visible, but it won't work, of course.)

Related