javascriptservice-workerprogressive-web-appsservice-worker-events

Getting service worker scope inside fetch event listener


I want to access my service worker's scope inside of a fetch event listener. My planned workaround was to use window.location.host, but window isn't available inside the service worker. I also tried using ServiceWorkerRegistration.scope (MDN doc), which would return the value I want, but this also isn't accessible inside the fetch event handler.

I'm hoping there's something similar to event.scope (available in the registration handler), but for fetch handlers. Is this possible?


Solution

  • After some digging around in Chrome dev tools, I found the variable I was looking for: self.location.host. This references the ServiceWorkerGlobalScope, which has a property of 'location'.

    I found a similar usage in the Google Chrome team's example service worker using self.location.origin instead:

    // Skip cross-origin requests, like those for Google Analytics.
      if (event.request.url.startsWith(self.location.origin)) { ... }