Search code examples
javascriptservice-workerprogressive-web-appscacheapi

in the Cache API , what is the difference between using caches.match(event.request) and caches.match(event.request.url)


I'm working with services worker and I have the following code

  self.addEventListener('fetch', function (event) {
    const url = new URL(event.request.url)

    if (event.request.mode == "navigate") {
        const fetchData = fetch(event.request).catch(function () {
            //console.log("errr")
            return caches.match("/core/index.php/offline_controlador/index")
        });
        event.respondWith(fetchData)
        return;
    }

    event.respondWith(
        caches.match(event.request).then(function (response) {
            return response || fetch(event.request);
        })
    );
 });

when i tried to get these files from the cache, it does not work, but when i change the code to

event.respondWith(
        caches.match(event.request.url).then(function(response) {
          return response || fetch(event.request);
        })
    );

instead of

event.respondWith(
            caches.match(event.request).then(function(response) {
              return response || fetch(event.request);
            })
        );

It works perfect


Solution

  • The relevant section of the Cache Storage API specification is 5.4.2. (Although that applies to the matchAll() method of a Cache object, that's what ends up being called "under the hood" when you do caches.match().

    Of particular relevance to your question is step 2:

    If the optional argument request is not omitted, then:

    • If request is a Request object, then:

      • Set r to request’s request.

      • If r’s method is not GET and options.ignoreMethod is false, return a promise resolved with an empty array.

    • Else if request is a string, then:

      • Set r to the associated request of the result of invoking the initial value of Request as constructor with request as its argument. If this throws an exception, return a promise rejected with that exception.

    To summarize, the biggest difference is that passing in a Request object as the first parameter can cause the match() to fail if the Request has a method of something other than 'GET'. Maybe that's what you're bumping into.

    Other than that, the two approaches should basically be the same, though passing in a Request is slightly more efficient, since the browser doesn't have to implicitly create a Request object based on the string.