registerServiceWorker.js 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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 default function register() {
  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/facebookincubator/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. Lets check if a service worker still exists or not.
  31. checkValidServiceWorker(swUrl);
  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);
  43. }
  44. });
  45. }
  46. }
  47. function registerValidSW(swUrl) {
  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. } else {
  62. // At this point, everything has been precached.
  63. // It's the perfect time to display a
  64. // "Content is cached for offline use." message.
  65. console.log('Content is cached for offline use.');
  66. }
  67. }
  68. };
  69. };
  70. })
  71. .catch(error => {
  72. console.error('Error during service worker registration:', error);
  73. });
  74. }
  75. function checkValidServiceWorker(swUrl) {
  76. // Check if the service worker can be found. If it can't reload the page.
  77. fetch(swUrl)
  78. .then(response => {
  79. // Ensure service worker exists, and that we really are getting a JS file.
  80. if (
  81. response.status === 404 ||
  82. response.headers.get('content-type').indexOf('javascript') === -1
  83. ) {
  84. // No service worker found. Probably a different app. Reload the page.
  85. navigator.serviceWorker.ready.then(registration => {
  86. registration.unregister().then(() => {
  87. window.location.reload();
  88. });
  89. });
  90. } else {
  91. // Service worker found. Proceed as normal.
  92. registerValidSW(swUrl);
  93. }
  94. })
  95. .catch(() => {
  96. console.log(
  97. 'No internet connection found. App is running in offline mode.'
  98. );
  99. });
  100. }
  101. export function unregister() {
  102. if ('serviceWorker' in navigator) {
  103. navigator.serviceWorker.ready.then(registration => {
  104. registration.unregister();
  105. });
  106. }
  107. }