javascript – Service worker causing site can’t be reached

I have the following service worker code. The website works sometimes and sometimes it gives “This site can’t be reached The webpage at domain.com might be temporarily down or it may have moved permanently to a new web address.”. We are using the workbox library.

Please help if something is wrong in the code.

/* eslint-disable no-undef */

importScripts('https://s3-eu-west-1.amazonaws.com/static.wizrocket.com/js/sw_webpush.js');
importScripts('https://cdn.moengage.com/webpush/releases/serviceworker_cdn.min.latest.js');
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.4.1/workbox-sw.js');

const version = 2;
const OFFLINE_URL_CACHE_NAME = `offline${version}`;
// Customize this with a different URL if needed.
const OFFLINE_URL = 'offline.html';

self.addEventListener('install', event => {
  event.waitUntil(
    (async () => {
      const cache = await caches.open(OFFLINE_URL_CACHE_NAME);
      // Setting {cache: 'reload'} in the new request will ensure that the
      // response isn't fulfilled from the HTTP cache; i.e., it will be from
      // the network.
      try {
        await cache.add(new Request(OFFLINE_URL, { cache: 'reload' }));
      } catch (e) {
        // DO NOTHING
      }
    })()
  );
  // Force the waiting service worker to become the active service worker.
  self.skipWaiting();
});

self.addEventListener('activate', event => {
  event.waitUntil(
    (async () => {
      // Enable navigation preload if it's supported.
      // See https://developers.google.com/web/updates/2017/02/navigation-preload
      if ('navigationPreload' in self.registration) {
        await self.registration.navigationPreload.enable();
      }
      // Delete Old Cache
      const keys = await caches.keys();
      return keys.map(async cache => {
        if (!cache.includes(version) && !cache.toLowerCase().includes('analytics')) {
          console.log(`Service Worker: Removing old cache: ${cache}`);
          // eslint-disable-next-line
          return await caches.delete(cache);
        }
      });
    })()
  );

  // Tell the active service worker to take control of the page immediately.
  self.clients.claim();
});

self.addEventListener('fetch', event => {
  // We only want to call event.respondWith() if this is a navigation request
  // for an HTML page.
  if (event.request.mode === 'navigate') {
    event.respondWith(
      (async () => {
        try {
          // First, try to use the navigation preload response if it's supported.
          const preloadResponse = await event.preloadResponse;
          if (preloadResponse) {
            return preloadResponse;
          }

          // Always try the network first.
          const networkResponse = await fetch(event.request);
          return networkResponse;
        } catch (error) {
          // catch is only triggered if an exception is thrown, which is likely
          // due to a network error.
          // If fetch() returns a valid HTTP response with a response code in
          // the 4xx or 5xx range, the catch() will NOT be called.
          console.log('Fetch failed; returning offline page instead.', error);

          const cache = await caches.open(OFFLINE_URL_CACHE_NAME);
          const cachedResponse = await cache.match(OFFLINE_URL);
          return cachedResponse;
        }
      })()
    );
  }

  // If our if() condition is false, then this fetch handler won't intercept the
  // request. If there are any other fetch handlers registered, they will get a
  // chance to call event.respondWith(). If no fetch handlers call
  // event.respondWith(), the request will be handled by the browser as if there
  // were no service worker involvement.
});

self.addEventListener('message', async event => {
  if (!event.data) {
    return;
  }
  /* eslint-disable */
  if ('broadcast' in event.data) {
    const allClients = await clients.matchAll();
    for (const client of allClients) {
      client.postMessage(event.data.broadcast);
    }
  }
  switch (event.data) {
    case 'force-activate':
      self.skipWaiting();
      self.clients.claim();
      self.clients.matchAll().then(clients => {
        clients.forEach(client => client.postMessage('reload-window'));
      });
      break;
    default:
      break;
  }
});

workbox.core.setCacheNameDetails({
  prefix: 'mojo',
  suffix: 'v1',
});

// workbox.precaching.precacheAndRoute(self.__precacheManifest || []); // eslint-disable-line no-underscore-dangle

workbox.googleAnalytics.initialize();

// workbox.routing.registerRoute(
//   ctx => {
//     if (ctx.url.pathname.includes('.')) return false;
//     if (ctx.url.pathname.includes('api')) return false;
//     if (!ctx.url.host.includes('rentomojo') && !ctx.url.host.includes('localhost')) return false;
//     return true;
//   },
//   new workbox.strategies.NetworkFirst({
//     cacheName: 'pages',
//   })
// );

workbox.routing.registerRoute(
  new RegExp('https://fonts.(?:googleapis|gstatic).com/(.*)'),
  workbox.strategies.cacheFirst({
    cacheName: `fonts${version}`,
    plugins: [
      new workbox.cacheableResponse.Plugin({
        statuses: [0, 200],
      }),
      new workbox.expiration.Plugin({
        maxEntries: 10,
        purgeOnQuotaError: true,
      }),
    ],
  })
);

workbox.routing.registerRoute(
  new RegExp('https://cdnjs.cloudflare.com/ajax/libs/(.*)/(.*)'),
  workbox.strategies.cacheFirst({
    cacheName: `fonts${version}`,
    plugins: [
      new workbox.cacheableResponse.Plugin({
        statuses: [0, 200],
      }),
      new workbox.expiration.Plugin({
        maxEntries: 10,
        purgeOnQuotaError: true,
      }),
    ],
  })
);

workbox.routing.registerRoute(
  /.(?:woff|woff2)$/,
  workbox.strategies.cacheFirst({
    cacheName: `fonts${version}`,
    plugins: [
      new workbox.cacheableResponse.Plugin({
        statuses: [0, 200],
      }),
      new workbox.expiration.Plugin({
        maxEntries: 10,
        purgeOnQuotaError: true,
      }),
    ],
  })
);

workbox.routing.registerRoute(
  /.(?:png|gif|jpg|jpeg|svg)$/,
  workbox.strategies.cacheFirst({
    cacheName: `images${version}`,
    plugins: [
      new workbox.expiration.Plugin({
        maxEntries: 60,
        maxAgeSeconds: 4 * 24 * 60 * 60, // 4 Days
        purgeOnQuotaError: true,
      }),
    ],
  })
);

workbox.routing.registerRoute(
  /.(?:js|css)$/gi,
  workbox.strategies.staleWhileRevalidate({
    cacheName: `assets${version}`,
  })
);

workbox.routing.registerRoute(
  /.*/api/locations/[1-9]/getFullCategory.*/,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: `api${version}`,
    plugins: [
      new workbox.expiration.Plugin({
        maxAgeSeconds: 1 * 24 * 60 * 60, // 1 Days
      }),
    ],
  })
);

workbox.routing.registerRoute(
  //api/products/location/d*/productVariant/d*/getProductAddons/?/gi,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: `api${version}`,
    plugins: [
      new workbox.expiration.Plugin({
        maxAgeSeconds: 1 * 24 * 60 * 60, // 1 Days
      }),
    ],
  })
);

workbox.routing.registerRoute(
  //api/Products/location/d*/category/d*/[w-]*/fullInfo/?/gi,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: `api${version}`,
    plugins: [
      new workbox.expiration.Plugin({
        maxAgeSeconds: 1 * 24 * 60 * 60, // 1 Days
      }),
    ],
  })
);

workbox.routing.registerRoute(
  //api/ExchangeProductPricing/isProductExchangeable/??productVariantId=d*/gi,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: `api${version}`,
    plugins: [
      new workbox.expiration.Plugin({
        maxAgeSeconds: 1 * 24 * 60 * 60, // 1 Days
      }),
    ],
  })
);

workbox.routing.registerRoute(
  //api/Coupons/getCouponByProductAndLocation/productId/d*/locationId/d*/?/gi,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: `api${version}`,
    plugins: [
      new workbox.expiration.Plugin({
        maxAgeSeconds: 1 * 24 * 60 * 60, // 1 Days
      }),
    ],
  })
);

workbox.routing.registerRoute(
  //api/Products/relatedProducts.*/gi,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: `api${version}`,
    plugins: [
      new workbox.expiration.Plugin({
        maxAgeSeconds: 1 * 24 * 60 * 60, // 1 Days
      }),
    ],
  })
);

workbox.routing.registerRoute(
  //api/Campaigns/getCurrent/??locationId=d*/gi,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: `api${version}`,
    plugins: [
      new workbox.expiration.Plugin({
        maxAgeSeconds: 1 * 24 * 60 * 60, // 1 Days
      }),
    ],
  })
);

workbox.routing.registerRoute(
  //api/Locations/d*/getPopularProducts/?/gi,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: `api${version}`,
    plugins: [
      new workbox.expiration.Plugin({
        maxAgeSeconds: 1 * 24 * 60 * 60, // 1 Days
      }),
    ],
  })
);

workbox.routing.registerRoute(
  //api/Meta/trendingSearch/?/gi,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: `api${version}`,
    plugins: [
      new workbox.expiration.Plugin({
        maxAgeSeconds: 1 * 24 * 60 * 60, // 1 Days
      }),
    ],
  })
);

Leave a Comment