Advertisement
Guest User

HEAD raping service worker

a guest
Jun 15th, 2020
335
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const cacheName = 'storage';
  2.  
  3. function signalTimeout(ms) {
  4.   const controller = new AbortController();
  5.   setTimeout(() => controller.abort(), ms);
  6.   return controller.signal;
  7. }
  8.  
  9. function log(msg) {
  10.   console.log(msg);
  11. }
  12.  
  13. self.addEventListener('fetch', e => {
  14.   if(e.request.method != 'GET') return;
  15.  
  16.   e.respondWith(async function() {
  17.     const url = new URL(e.request.url).pathname;
  18.     const cache = await caches.match(e.request);
  19.  
  20.     if(cache) {
  21.       try {
  22.         const head = await fetch(url, {
  23.           method: 'HEAD',
  24.           signal: signalTimeout(7000)
  25.         });
  26.         const fetchedET = head.headers.get('last-modified');
  27.         const cachedET = cache.headers.get('last-modified');
  28.         if(fetchedET === cachedET) {
  29.           log(`[${url}] Up to date, using cached`);
  30.           return cache;
  31.         }
  32.       }
  33.       catch(err) {
  34.         const nw = err.name === 'AbortError' ? 'dogshit' : 'unavailable';
  35.         log(`[${url}] Network is ${nw}, using cached`);
  36.         return cache;
  37.       }
  38.     }
  39.  
  40.     try {
  41.       const fetchedObject = await fetch(e.request);
  42.       if(fetchedObject.ok) {
  43.         const storage = await caches.open(cacheName);
  44.         storage.put(e.request, fetchedObject.clone());
  45.         log(`[${url}] New version, fetching and caching`);
  46.       }
  47.       return fetchedObject;
  48.     }
  49.     catch(err) {
  50.       if(cache) return cache;
  51.       throw err;
  52.     }
  53.   }());
  54. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement