Ignore query params in service worker requests

Viewed 5217

I am trying to build an offline app using service workers. I have a list of resources defined like

var urlsToPrefetch = ['foo.html', 'bar.js']

Query strings are added to many of the urls and that is causing the service worker's fetch event to fail since the request doesn't match what is defined in the cache. The query strings are mainly used to force fetching of new file versions. For instance, bar.js is requested as bar.js?version=2

There is an option for ignoring query strings (ignoreSearch below), although this is not yet implemented as of Chrome V50. Chrome Canary is only available for Win/Mac

The below code is in the fetch eventListener

event.respondWith(
    // caches.match() will look for a cache entry in all of the caches available to the service worker.
    // It's an alternative to first opening a specific named cache and then matching on that.

    caches.match(event.request, {'ignoreSearch': true} ).then(function(response) {
        if (response) {

            return response;
        }

        ...
)
3 Answers

Try...

function stripQueryStringAndHashFromPath(url) {
  return url.split("?")[0].split("#")[0];
}

function onFetch(event) {
  const requestUrl = stripQueryStringAndHashFromPath(event.request.url.replace(/^.*\/\/[^\/]+/, ''));
... all the other jazz
}

This will give you just the path name. For example /?test=1#three will give you just /.

Related