aldinokemal

2_sw.js

Jul 23rd, 2022 (edited)
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let cacheName = 'pwa-cache';
  2.  
  3. const isValidUrl = urlString => {
  4.     let url;
  5.     try {
  6.         url = new URL(urlString);
  7.     } catch (e) {
  8.         return false;
  9.     }
  10.     if (url.host === 'localhost:3000') {
  11.         return url.protocol === "http:" || url.protocol === "https:";
  12.     }
  13.     return false
  14. }
  15.  
  16. self.addEventListener("install", (event) => {
  17.     event.waitUntil((async () => {
  18.         const cache = await caches.open(cacheName)
  19.         console.log('mulai caching saat install');
  20.         await cache.addAll([
  21.             '/index.html',
  22.             // '/karyawan.html',
  23.             // '/pushnotif.html',
  24.             '/css/materialize.min.css',
  25.             '/js/materialize.min.js',
  26.             '/js/main.js'
  27.         ])
  28.         await self.skipWaiting();
  29.     })());
  30. });
  31.  
  32. self.addEventListener("fetch", (event) => {
  33.     event.waitUntil((async () => {
  34.         if (event.request.url.endsWith(".png") ||
  35.             event.request.url.endsWith(".css") ||
  36.             event.request.url.endsWith(".js") ||
  37.             event.request.url.endsWith(".html")) {
  38.             caches.open(cacheName).then((cache) => {
  39.                 // check apakah URL valid atau chrome ekstensi
  40.                 if (isValidUrl(event.request.url)) {
  41.                     cache.add(event.request)
  42.                 }
  43.             })
  44.         }
  45.  
  46.         event.respondWith(caches.match(event.request)
  47.             .then((resp) => {
  48.                 return resp || fetch(event.request);
  49.             }))
  50.     })());
  51. });
  52.  
Add Comment
Please, Sign In to add comment