简体   繁体   中英

How to proxy a jsonp call in service worker

My site fetches some user-based data from another site through a jsonp call how can I proxy these request for offline use?

The JSONP pattern involves adding a <script> element to your page, the source of which will invoke a callback that exposes the data from the remote URL to your page.

From the service worker's perspective, this the addition of a <script> will trigger a fetch event, with the event.request.destination set to 'script' . Additionally, the event.request.url will be set to the full URL of the JSONP script resource. You could use a combination of one or both of those facts to tell your service worker's fetch handler to do something special when it encounters a JSONP request:

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
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM