简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM