Is it possible to get the value of window.location.pathname from within a Service Worker?

Viewed 114

I am trying to get the value from window.location.pathname (or a similar location read only API) inside the context of a ServiceWorker. I think one way to do that is sending that information from the page to the Service Worker via postMessage:

navigator.serviceWorker.ready.then( registration => {
    registration.active.postMessage({
        type: "pathname",
        value: window.location.pathname
    });
});

as seen in https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/message_event

However, I need that data in the install step of the SW lifecycle so waiting on the SW to become the active one is not ideal, and I'd rather try first to get that data earlier so I can go thru the install step with that information.

1 Answers

Within the Service Worker, self.location is accessible via WorkerGlobalScope.location. You could listen to requests and process those that match the same origin of your domain.

self.addEventListener('fetch', event => {
  const requestUrl = new URL(event.request.url)
  if (self.location.origin === requestUrl.origin) {
    const requestPathname = requestUrl.pathname
  }
})
Related