feihcsim
feihcsim

Reputation: 1552

Service Worker "fetch" event for requesting the root path never fires

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

Upvotes: 3

Views: 1435

Answers (3)

Craig
Craig

Reputation: 47

I just figured this out, with help from https://livebook.manning.com/book/progressive-web-apps/chapter-4/27. Here's a short version of my service worker:

const cacheName = "Cache_v1";

const urlsToCache = [
	"Offline.html"
  // styles, images and scripts
 ];
 
self.addEventListener('install', (e) => 
{
  e.waitUntil(
    caches.open(cacheName).then((cache) => 
    {
      return cache.addAll(urlsToCache);			
    })
  );
});

self.addEventListener('fetch', (e) => 
{	
  if (e.request.url == "https://<DOMAIN_NAME>/")
  {
    console.log("root");
    e.respondWith(
      fetch("offline.html")
    );
  }
}

Upvotes: 1

feihcsim
feihcsim

Reputation: 1552

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.

Upvotes: 3

guest271314
guest271314

Reputation: 1

You can chain .then() to. .register() call then check location.href to determine the page at which the ServiceWorker has been registered

  navigator.serviceWorker.register("sw.js")
  .then(function(reg) {
    if (location.href === "https://www.mywebsite.com/") {
      // do stuff
      console.log(location.href, reg.scope);
    }
  })
  .catch(function(err) {
    console.error(err);
  });

Upvotes: 1

Related Questions