serviceWorker.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. // This optional code is used to register a service worker.
  2. // register() is not called by default.
  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 subsequent visits to a page, after all the
  6. // existing tabs open on the page have been closed, since previously cached
  7. // resources are updated in the background.
  8. // To learn more about the benefits of this model and instructions on how to
  9. // opt-in, read https://bit.ly/CRA-PWA
  10. const isLocalhost = Boolean(
  11. window.location.hostname === 'localhost' ||
  12. // [::1] is the IPv6 localhost address.
  13. window.location.hostname === '[::1]' ||
  14. // 127.0.0.0/8 are considered localhost for IPv4.
  15. window.location.hostname.match(
  16. /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
  17. )
  18. );
  19. type Config = {
  20. onSuccess?: (registration: ServiceWorkerRegistration) => void;
  21. onUpdate?: (registration: ServiceWorkerRegistration) => void;
  22. };
  23. function registerValidSW(swUrl: string, config?: Config) {
  24. navigator.serviceWorker
  25. .register(swUrl)
  26. .then((registration) => {
  27. // eslint-disable-next-line no-param-reassign
  28. registration.onupdatefound = () => {
  29. const installingWorker = registration.installing;
  30. if (installingWorker == null) {
  31. return;
  32. }
  33. installingWorker.onstatechange = () => {
  34. if (installingWorker.state === 'installed') {
  35. if (navigator.serviceWorker.controller) {
  36. // At this point, the updated precached content has been fetched,
  37. // but the previous service worker will still serve the older
  38. // content until all client tabs are closed.
  39. console.log(
  40. 'New content is available and will be used when all ' +
  41. 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
  42. );
  43. // Execute callback
  44. if (config && config.onUpdate) {
  45. config.onUpdate(registration);
  46. }
  47. } else {
  48. // At this point, everything has been precached.
  49. // It's the perfect time to display a
  50. // "Content is cached for offline use." message.
  51. console.log('Content is cached for offline use.');
  52. // Execute callback
  53. if (config && config.onSuccess) {
  54. config.onSuccess(registration);
  55. }
  56. }
  57. }
  58. };
  59. };
  60. })
  61. .catch((error) => {
  62. console.error('Error during service worker registration:', error);
  63. });
  64. }
  65. function checkValidServiceWorker(swUrl: string, config?: Config) {
  66. // Check if the service worker can be found. If it can't reload the page.
  67. fetch(swUrl, {
  68. headers: { 'Service-Worker': 'script' },
  69. })
  70. .then((response) => {
  71. // Ensure service worker exists, and that we really are getting a JS file.
  72. const contentType = response.headers.get('content-type');
  73. if (
  74. response.status === 404 ||
  75. (contentType != null && contentType.indexOf('javascript') === -1)
  76. ) {
  77. // No service worker found. Probably a different app. Reload the page.
  78. navigator.serviceWorker.ready.then((registration) => {
  79. registration.unregister().then(() => {
  80. window.location.reload();
  81. });
  82. });
  83. } else {
  84. // Service worker found. Proceed as normal.
  85. registerValidSW(swUrl, config);
  86. }
  87. })
  88. .catch(() => {
  89. console.log(
  90. 'No internet connection found. App is running in offline mode.'
  91. );
  92. });
  93. }
  94. export function register(config?: Config) {
  95. if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
  96. const url = process.env.PUBLIC_URL || 'localhost';
  97. // The URL constructor is available in all browsers that support SW.
  98. const publicUrl = new URL(url, window.location.href);
  99. if (publicUrl.origin !== window.location.origin) {
  100. // Our service worker won't work if PUBLIC_URL is on a different origin
  101. // from what our page is served on. This might happen if a CDN is used to
  102. // serve assets; see https://github.com/facebook/create-react-app/issues/2374
  103. return;
  104. }
  105. window.addEventListener('load', () => {
  106. const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
  107. if (isLocalhost) {
  108. // This is running on localhost. Let's check if a service worker still exists or not.
  109. checkValidServiceWorker(swUrl, config);
  110. // Add some additional logging to localhost, pointing developers to the
  111. // service worker/PWA documentation.
  112. navigator.serviceWorker.ready.then(() => {
  113. console.log(
  114. 'This web app is being served cache-first by a service ' +
  115. 'worker. To learn more, visit https://bit.ly/CRA-PWA'
  116. );
  117. });
  118. } else {
  119. // Is not localhost. Just register service worker
  120. registerValidSW(swUrl, config);
  121. }
  122. });
  123. }
  124. }
  125. export function unregister() {
  126. if ('serviceWorker' in navigator) {
  127. navigator.serviceWorker.ready.then((registration) => {
  128. registration.unregister();
  129. });
  130. }
  131. }