【问题标题】:How to proxy a jsonp call in service worker如何在服务工作者中代理 jsonp 调用
【发布时间】:2020-02-03 22:33:48
【问题描述】:

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

【问题讨论】:

    标签: javascript jsonp service-worker progressive-web-apps offline-caching


    【解决方案1】:

    JSONP pattern 涉及将<script> 元素添加到您的页面,其源将调用回调,将来自远程 URL 的数据公开到您的页面。

    从服务工作者的角度来看,添加<script> 将触发fetch 事件,event.request.destination 设置为'script'。此外,event.request.url 将设置为 JSONP 脚本资源的完整 URL。您可以结合使用这些事实中的一个或两个来告诉服务人员的 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
      }
    });
    

    【讨论】:

    • 问题不是如何识别jsonp请求。我们不能使用 fetch 在 service worker 中创建 jsonp requset。而不是应该使用 importScripts 但有了这个解决方案,我无法代理基本请求。
    • 我不明白为什么你不能在fetch 事件处理程序中使用fetch(event.request) 来获取与<script> 资源对应的Response
    • 因为它来自不同的域并且CORS不可用
    • 您的请求可以使用mode: 'no-cors'。事实上,如果你在一个 service worker 中拦截一个来自页面上 <script> 标签的传入 FetchEvent,那么 event.request.mode 应该已经设置为 'no-cors'。您返回的不透明响应仍然可以被缓存并在离线时用于响应。
    猜你喜欢
    • 2011-06-15
    • 2018-11-14
    • 2022-07-11
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    相关资源
    最近更新 更多