5

I am trying to register service worker in django but I get this error

DOMException: Failed to register a ServiceWorker: The script resource is behind a redirect, which is disallowed.

My project structure is

src/
   templates/sw.js
   static/js/main.js  #file where I register service worker

main.js

if ('serviceWorker' in navigator) {
        navigator.serviceWorker
            .register('sw.js', {scope: '/'})
            .then(function(reg) {
                console.log('Achieng Service worker Registration worked!');
            })
            .catch(function(error) {
                console.log(error);
            });

    }

According to this django-service worker, I have defined my urls as

path('sw.js/', (TemplateView.as_view(template_name="sw.js", content_type='application/javascript', )), name='sw.js'),

and have my sw.js in templates folder.

What could I be missing? I want service worker to have a default scope '/'

1 Answers1

5

Your service worker is served at /sw.js/. Django automatically redirects /sw.js to /sw.js/. To make it work you simply have to remove the trailing slash in path().

The convention in Django is to use a trailing slash in every url, but cases like this are an exception.

knbk
  • 52,111
  • 9
  • 124
  • 122