如何将值传递给服务工作者,然后在获取事件侦听器中使用它

发布于 2025-01-31 03:46:09 字数 877 浏览 1 评论 0原文

我需要我的服务工作者监视提取请求,如果请求包含一定路径,则在响应中包括标头值,但是直到运行时间才知道此值。我可以使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文