serviceWorker.ts 5.1 KB

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