如何将值传递给服务工作者,然后在获取事件侦听器中使用它
我需要我的服务工作者监视提取请求,如果请求包含一定路径,则在响应中包括标头值,但是直到运行时间才知道此值。我可以使用postmessage()发送值并在SW的消息侦听器中接收值,但随后似乎无法在获取侦听器中使用它。
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
}
}
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论