javascriptprogressive-web-appsservice-worker

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


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.


Solution

  • 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.