serviceWorker.tsx 5.5 KB

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