Advertisement
seezee

Service Worker TypeError

Feb 25th, 2022
1,205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // JavaScript Document
  2. // Important! Paths are relative to root. Soft link to this file from root to
  3. // avoid scope restrictions.
  4. 'use strict;
  5.  
  6. // Listen for request events
  7. self.addEventListener('fetch', function (event) {
  8.  
  9.  // Get the request
  10.  let request = event.request;
  11.  
  12.  // Bug fix
  13.  // https://stackoverflow.com/a/49719964
  14.  if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') return;
  15.  
  16.  // HTML files
  17.  // Network-first
  18.  if (request.headers.get('Accept').includes('text/html')) {
  19.    event.respondWith(
  20.      fetch(request).then(function (response) {
  21.  
  22.        // Create a copy of the response and save it to the cache
  23.        let copy = response.clone();
  24.        event.waitUntil(caches.open('app').then(function (cache) {
  25.          // This is the line that throws an error:
  26.          return cache.put(request, copy);
  27.        }));
  28.  
  29.        // Return the response
  30.        return response;
  31.  
  32.      }).catch(function (error) {
  33.        return caches.match(request).then(function (response) {
  34.          return response;
  35.        });
  36.      })
  37.    );
  38.  }
  39.  
  40.  // CSS, JavaScript, images, & fonts
  41.  // Offline-first
  42.  if (request.headers.get('Accept').includes('text/css') || request.headers.get('Accept').includes('text/javascript') || request.headers.get('Accept').includes('image') || request.headers.get('Accept').includes('font')) {
  43.    // Check the cache first
  44.    // If it's not found, send the request to the network
  45.     event.respondWith(
  46.       caches.match(request).then(function (response) {
  47.         return response || fetch(request).then(function (response) {
  48.           return response;
  49.         });
  50.       })
  51.     );
  52.     return;
  53.   }
  54.  
  55. });
  56.  
  57. let coreAssets = [
  58.   // Paths to core assets.
  59. ];
  60.  
  61. // On install, cache some stuff
  62. self.addEventListener('install', function (event) {
  63.  
  64.   // Cache core assets
  65.   event.waitUntil(caches.open('app').then(function (cache) {
  66.     for (let asset of coreAssets) {
  67.       cache.add(new Request(asset));
  68.     }
  69.     return cache;
  70.   }));
  71. });
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement