2

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.

2 Answers 2

2

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
  }
})
Sign up to request clarification or add additional context in comments.

2 Comments

That's close but not quite what I am hoping to get. Origin is giving me the root of the path (for example, localhost:8080 when I am trying to get localhost:8080/Page). This seems very particular to my case, which only makes this more difficult.
Is requestUrl.pathname above providing you with the /Page value you're seeking?
0

For anyone looking at this question looking for an answer: my solution ended up getting self.location.pathname, splitting it into an array using .split("/"), and get the path I needed from there. Because the path is somewhat predictable in my case, I was able to get the exact path I wanted by doing something like this:

const scope =  "/" + path[path.length-offset];

Adjusting offset to the number that you'd need.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.