I need my service worker to monitor fetch requests and include a header value in the response if the request contains a certain path however this value isn't known until run time. I can use postMessage() to send the value and receive it in the sw's message listener, but then can't seem to use it in the fetch listener.
app.js
const customerUrl = "customerUrl.domain.com" //this will come from a setting
const swr = new Worker('/sw.js')
swr.postMessage(customerUrl)
sw.js
let customerDomain = "foo.domain.com"
self.addEventListener("message", (msg) => {
console.log("Service Worker Message Recieved", msg.data) // "customerUrl.domain.com"
customerDomain = msg.data
console.log(customerDomain) // "customerUrl.domain.com" ... awesome
})
self.addEventListener('fetch', evt => {
console.log("Fetch intercepted for " + customerDomain) // "foo.sample.com" but needs to be "customerUrl.domain.com"
if (evt.url.includes("/bar/")) {
// ... modify request and send with customerDomain in header
}
}