I am trying to set up my Service Worker so that it intercepts the request for the home page (ie the home page, like www.mywebsite.com/
), which would eventually allow me to return a cached template instead. My code looks like this so far:
main.js:
navigator.serviceWorker.register('/sw.js')
sw.js:
self.addEventListener('fetch', function(event) {
console.log(event.request.url)
/**
* only ever detects requests for resources but never the route itself..
*
* logged:
* https://www.mywebsite.com/main.js
* https://www.mywebsite.com/myimage.png
*
* not logged:
* https://www.mywebsite.com/
*/
})
I'm pretty sure the service worker is getting set up correctly, as I am indeed detecting events being fired for requests for resources (like /main.js
or /myimage.png
). However, the problem is that only the resources' events ever get fired, even though I'd like that event for requesting the route itself (/
) to be fired. Am I missing anything, or should I be listening for a different event?
Thanks
I discovered that the request for the root path was in fact getting intercepted. The reason I never noticed this is because the request happens before the page is loaded (ie before there's even a console to log to). If I turn on the Preserve log
feature in Chrome DevTools, I will notice the logs for the root path requests as I should.