serviceWorkerRegistration.js 5.3 KB

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