serviceWorker.tsx 5.2 KB

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