如何在服务工作者中代理 jsonp 调用

How to proxy a jsonp call in service worker

我的站点通过 jsonp 调用从另一个站点获取一些基于用户的数据 我如何代理这些请求以供离线使用?

JSONP pattern 涉及向您的页面添加一个 <script> 元素,该元素的源将调用一个回调,将数据从远程 URL 公开到您的页面。

从 service worker 的角度来看,添加 <script> 将触发 fetch 事件,event.request.destination 设置为 'script'。此外,event.request.url 将设置为 JSONP 脚本资源的完整 URL。您可以结合使用其中一个或两个事实来告诉您的 service worker 的 fetch 处理程序在遇到 JSONP 请求时做一些特殊的事情:

self.addEventListener('fetch', (event) => {
  if (event.request.destinaton = 'script' &&
      event.request.url.startsWith('https://example.com')) {
    // Your caching strategy goes here.
    // E.g. https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook#network-falling-back-to-cache
  }
});