Advertisement
ahmadandika

serviceWorker

Mar 1st, 2022
777
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* eslint-disable no-param-reassign */
  2. // In production, we register a service worker to serve assets from local cache.
  3.  
  4. // This lets the app load faster on subsequent visits in production, and gives
  5. // it offline capabilities. However, it also means that developers (and users)
  6. // will only see deployed updates on the "N+1" visit to a page, since previously
  7. // cached resources are updated in the background.
  8.  
  9. // To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
  10. // This link also includes instructions on opting out of this behavior.
  11.  
  12. const firebaseConfig = new URLSearchParams(process.env.REACT_APP_CONFIG_FIREBASE).toString();
  13. const PATH_FIREBASE_SW = `/firebase-messaging-sw.js${firebaseConfig}`;
  14.  
  15. const isLocalhost = Boolean(
  16.   window.location.hostname === 'localhost' ||
  17.     // [::1] is the IPv6 localhost address.
  18.     window.location.hostname === '[::1]' ||
  19.     // 127.0.0.1/8 is considered localhost for IPv4.
  20.     window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/),
  21. );
  22.  
  23. function registerValidSW(swUrl) {
  24.   navigator.serviceWorker
  25.     .register(swUrl)
  26.     .then((registration) => {
  27.       registration.onupdatefound = () => {
  28.         const installingWorker = registration.installing;
  29.         installingWorker.onstatechange = () => {
  30.           if (installingWorker.state === 'installed') {
  31.             if (navigator.serviceWorker.controller) {
  32.               // At this point, the old content will have been purged and
  33.               // the fresh content will have been added to the cache.
  34.               // It's the perfect time to display a "New content is
  35.               // available; please refresh." message in your web app.
  36.               console.log('New content is available; please refresh.');
  37.             } else {
  38.               // At this point, everything has been precached.
  39.               // It's the perfect time to display a
  40.               // "Content is cached for offline use." message.
  41.               console.log('Content is cached for offline use.');
  42.             }
  43.           }
  44.         };
  45.       };
  46.     })
  47.     .catch((error) => {
  48.       console.error('Error during service worker registration:', error);
  49.     });
  50. }
  51.  
  52. function checkValidServiceWorker(swUrl) {
  53.   // Check if the service worker can be found. If it can't reload the page.
  54.   fetch(swUrl)
  55.     .then((response) => {
  56.       // Ensure service worker exists, and that we really are getting a JS file.
  57.       if (
  58.         response.status === 404 ||
  59.         response.headers.get('content-type').indexOf('javascript') === -1
  60.       ) {
  61.         // No service worker found. Probably a different app. Reload the page.
  62.         navigator.serviceWorker.ready.then((registration) => {
  63.           registration.unregister().then(() => {
  64.             window.location.reload();
  65.           });
  66.         });
  67.       } else {
  68.         // Service worker found. Proceed as normal.
  69.         registerValidSW(swUrl);
  70.       }
  71.     })
  72.     .catch(() => {
  73.       console.log('No internet connection found. App is running in offline mode.');
  74.     });
  75. }
  76.  
  77. export function register() {
  78.   console.log('a');
  79.   if ('serviceWorker' in navigator) {
  80.     // The URL constructor is available in all browsers that support SW.
  81.     const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
  82.     if (publicUrl.origin !== window.location.origin) {
  83.       // Our service worker won't work if PUBLIC_URL is on a different origin
  84.       // from what our page is served on. This might happen if a CDN is used to
  85.       // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
  86.       return;
  87.     }
  88.  
  89.     window.addEventListener('load', () => {
  90.       const swUrl = `${process.env.PUBLIC_URL}/${PATH_FIREBASE_SW}`;
  91.  
  92.       if (!isLocalhost) {
  93.         // Is not local host. Just register service worker
  94.         registerValidSW(swUrl);
  95.       } else {
  96.         // This is running on localhost. Lets check if a service worker still exists or not.
  97.         checkValidServiceWorker(swUrl);
  98.       }
  99.     });
  100.   }
  101. }
  102.  
  103. export function unregister() {
  104.   if ('serviceWorker' in navigator) {
  105.     navigator.serviceWorker.ready.then((registration) => {
  106.       registration.unregister();
  107.     });
  108.   }
  109. }
  110.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement