I have a webapp that is implemented with flask and nginx (in docker environment) I want to add a service worker so I read here how to set the configuration such that the scope is the root directory ('/')
When I start the application I can see that my service worker registers, installed and activated. This happens repeatedly as expected.
But I have a problem to intercept the fetch commands reliably.
Using chrome devtools, if I set a breakpoint in the install, wait and continue,
then sometimes, the GET operations are routed to the service worker (I can see the console printout from the fetch event listener in the service worker).
When I get to this state, then all fetch events are intercepted, as expected
But if I remove the breakpoints and run the program normally, the service worker doesn't intercept the fetch events.
I read here that the scope of the service worker can cause to miss of routing. But in such case the miss is systematic, i.e. the path which is not in the scope is never intercepted
This is not my case, because with certain conditions, my service worker does intercept the fetch calls.
My settings are below.
Thanks, Avner
# the file structure
/usr/src/app/web/
├── V1
│ ├── js
│ │ └── mlj
│ │ └── ...
│ │ ├── main.js
│ ├── ...
├── project
│ ├── sites
│ │ └── ...
│ │ └── views.py
└── sw1.js
------------------------------------------------------------
# the file that registers the service worker
cat main.js
...
navigator.serviceWorker.register("../../../sw1.js", {scope: '/'})
.then(regisration => console.log('SW Registered1'))
.catch(console.error);
------------------------------------------------------------
# the service worker
cat sw1.js
const version = 1;
self.addEventListener('install', function(event) {
console.log ('SW v%s installed at', version, new Date().toLocaleTimeString());
});
self.addEventListener('activate', function(event) {
console.log ('SW v%s activated at', version, new Date().toLocaleTimeString());
});
self.addEventListener('fetch', function(event) {
console.log ('SW v%s fetched at', version, new Date().toLocaleTimeString());
if(!navigator.onLine) {
event.respondWith(new Response('<h1> Offline :( </h1>', {headers: {'Content-Type': 'text/html'}}));
}
else {
console.log (event.request.url);
event.respondWith(fetch(event.request));
}
});
------------------------------------------------------------
# the route to the service worker in the flask python file
cat web/project/sites/views.py
...
from flask import current_app, send_from_directory
...
@sites_blueprint.route('/sw1.js', methods=['GET'])
def sw():
# /usr/src/app
root_dir = os.path.dirname(os.getcwd())
filename = 'sw1.js'
# /usr/src/app/web
dir1 = os.path.join(root_dir, 'web')
return send_from_directory(dir1, filename)