serviceWorker.tsx 5.4 KB

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