serviceWorker.js 4.6 KB

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