serviceWorkerRegistration.js 5.3 KB

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