serviceWorker.js 4.8 KB

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