Search code examples
javascriptjsonpservice-workerprogressive-web-appsoffline-caching

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?


Solution

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