global.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * @Author: your name
  3. * @Date: 2021-09-03 14:28:27
  4. * @LastEditTime: 2022-01-14 11:37:33
  5. * @LastEditors: Please set LastEditors
  6. * @Description: In User Settings Edit
  7. * @FilePath: /MedicalWisdomCheckSys/src/global.tsx
  8. */
  9. import { Button, message, notification } from 'antd';
  10. import defaultSettings from '../config/defaultSettings';
  11. const { pwa } = defaultSettings;
  12. const isHttps = document.location.protocol === 'https:';
  13. // if pwa is true
  14. if (pwa) {
  15. // Pop up a prompt on the page asking the user if they want to use the latest version
  16. window.addEventListener('sw.updated',(event: Event) => {
  17. const e = event as CustomEvent;
  18. const reloadSW = async () => {
  19. // Check if there is sw whose state is waiting in ServiceWorkerRegistration
  20. // https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
  21. const worker = e.detail && e.detail.waiting;
  22. if (!worker) {
  23. return true;
  24. }
  25. // Send skip-waiting event to waiting SW with MessageChannel
  26. await new Promise((resolve, reject) => {
  27. const channel = new MessageChannel();
  28. channel.port1.onmessage = (msgEvent) => {
  29. if (msgEvent.data.error) {
  30. reject(msgEvent.data.error);
  31. } else {
  32. resolve(msgEvent.data);
  33. }
  34. };
  35. worker.postMessage({ type: 'skip-waiting' }, [channel.port2]);
  36. });
  37. // Refresh current page to use the updated HTML and other assets after SW has skiped waiting
  38. window.location.reload();
  39. return true;
  40. };
  41. const key = `open${Date.now()}`;
  42. const btn = (
  43. <Button
  44. type="primary"
  45. onClick={() => {
  46. notification.close(key);
  47. reloadSW();
  48. }}
  49. >
  50. app.pwa.serviceworker.updated.ok
  51. </Button>
  52. );
  53. notification.open({
  54. message: 'app.pwa.serviceworker.updated',
  55. description: 'pp.pwa.serviceworker.updated.hint',
  56. btn,
  57. key,
  58. onClose: async () => null,
  59. });
  60. });
  61. } else if ('serviceWorker' in navigator && isHttps) {
  62. // unregister service worker
  63. const { serviceWorker } = navigator;
  64. if (serviceWorker.getRegistrations) {
  65. serviceWorker.getRegistrations().then((sws) => {
  66. sws.forEach((sw) => {
  67. sw.unregister();
  68. });
  69. });
  70. }
  71. serviceWorker.getRegistration().then((sw) => {
  72. if (sw) sw.unregister();
  73. });
  74. //remove all caches
  75. // if (window.caches && await window.caches.keys()) {
  76. // caches.keys().then((keys) => {
  77. // keys.forEach((key) => {
  78. // caches.delete(key);
  79. // });
  80. // });
  81. // }
  82. }