Question:I have a Django web app that contains a service worker designed for handling push notifications. Everything is working beautifully. In the many articles, tutorials and documentation it is written that the location and scope of service workers is important and to make sure to put it at the root of the domain.
See for example this article, that states:
Service worker file must registered at the root directory of your website.
I’ve spend 15 hours to learn that fact. You guys are lucky !
So when I first created my service worker in Django, I had to make sure to set the scope correctly. I created a View that served the JS code of the service worker as a template, just so that I could set the
But now I wonder: why does the scope matter? I just changed things around and moved the code of the service worker to a standard location inside Django’s static folders. In the SW registration code I removed the scope attribute. It is now simply:
I have done some testing on Chrome and Firefox, from localhost and using ngrok, and this seems to work fine as well.
So my question: does the scope and location of a service worker, that handles push notifications, really matter? Am I missing something? Are there cases where the scope for a push SW is important?
Answer:The same considerations that make scope and location very important when you have a service worker with a
fetchhandler do not apply to
push-only service workers.
If you just use the default
scopeand register a service worker script that exists somewhere in your origin (
navigator.serviceWorker.register('/static/account/sw.js')in your example), that should be fine for
I believe that OneSignal and Firebase Cloud Messaging for the web both have client libraries that will register a
push-only service worker for you (configured to use their messaging backend) with a synthetic scope, which is presumably guaranteed not to interfere with any of your actual URLs and accidentally take control of clients that you don’t expect. That’s overkill for what you’re trying to do, though.
If you have better answer, please add a comment about this, thank you!