1
votes

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?

2

2 Answers

3
votes

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)) { ... }
1
votes

I don''t know if the specification is more recent than this post, but the actual way to get the scope of a service worker is to use:

let scope = self.registration.scope; 

That will return the scope specified to the service worker. I had to deal with this in my service worker since we have several applications on the same site that could potentially use or not use the serviceworker - depending on the developer's wishes to do so.