Guest User

registerServiceWorker.js

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