Danny Jebb
Danny Jebb

Reputation: 961

PWA not working correctly offline. Uncaught (in promise) TypeError: Failed to fetch

I am trying to convert a simple webpage I have into a PWA in case the site it uses goes down.

I think I have done the majority of the work. The page is installable on my phone and passes all the Chrome lighthouse tests. But I get the following warning,


Web app manifest meets the installability requirements
Warnings: Page does not work offline. The page will not be regarded as installable after Chrome 93, stable release August 2021.

I also get the following warning and error in console,

The FetchEvent for "https://dannyj1984.github.io/index.html" resulted in a network error response: the promise was rejected.
Promise.then (async)
(anonymous) @ serviceWorker.js:30
serviceWorker.js:1 Uncaught (in promise) TypeError: Failed to fetch

There is then a warning saying the site cannot be installed as does not work offline. I have read the chrome dev article which says from the chrome release in Aug21 apps that dont work offline wont be installable. But I am stuck on which part of my fetch is causing an issue. The code in my service worker is,

const TGAbxApp = "TG-ABX-App-v1"
const assets = [
  //paths to files to add

]

self.addEventListener("install", installEvent => {
  installEvent.waitUntil(
    caches.open(TGAbxApp).then(cache => {
      cache.addAll(assets)
    })
  )
})

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        }
        return fetch(event.request);
      }
    )
  );
});

The above code for the fetch part of the service worker I took from Google and as I understand it, it first checks if there is data in the cache stored on install, if not it will request it from the network.

Upvotes: 2

Views: 3597

Answers (2)

Korkut hacisalihoğlu
Korkut hacisalihoğlu

Reputation: 51

I've had the same problem. I re enabled the cache through the developer console->network. fixed

Upvotes: 0

Bob-HL
Bob-HL

Reputation: 56

https://developer.chrome.com/blog/improved-pwa-offline-detection/

From Chrome 89 March 2021, it gives a warning if this check does not pass: The installed service worker fetch event returns an HTTP 200 status code (indicating a successful fetch) in simulated offline mode.

So, in your case, the service worker should return a cached 'index.html' when fetch(event.request) is failed.

Upvotes: 2

Related Questions