global.tsx 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import '@umijs/max';
  2. import { Button, message, notification } from 'antd';
  3. import defaultSettings from '../config/defaultSettings';
  4. const { pwa } = defaultSettings;
  5. const isHttps = document.location.protocol === 'https:';
  6. const clearCache = () => {
  7. // remove all caches
  8. if (window.caches) {
  9. caches
  10. .keys()
  11. .then((keys) => {
  12. keys.forEach((key) => {
  13. caches.delete(key);
  14. });
  15. })
  16. .catch((e) => console.log(e));
  17. }
  18. };
  19. // if pwa is true
  20. if (pwa) {
  21. // Notify user if offline now
  22. window.addEventListener('sw.offline', () => {
  23. message.warning('当前处于离线状态');
  24. });
  25. // Pop up a prompt on the page asking the user if they want to use the latest version
  26. window.addEventListener('sw.updated', (event: Event) => {
  27. const e = event as CustomEvent;
  28. const reloadSW = async () => {
  29. // Check if there is sw whose state is waiting in ServiceWorkerRegistration
  30. // https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
  31. const worker = e.detail && e.detail.waiting;
  32. if (!worker) {
  33. return true;
  34. }
  35. // Send skip-waiting event to waiting SW with MessageChannel
  36. await new Promise((resolve, reject) => {
  37. const channel = new MessageChannel();
  38. channel.port1.onmessage = (msgEvent) => {
  39. if (msgEvent.data.error) {
  40. reject(msgEvent.data.error);
  41. } else {
  42. resolve(msgEvent.data);
  43. }
  44. };
  45. worker.postMessage(
  46. {
  47. type: 'skip-waiting',
  48. },
  49. [channel.port2],
  50. );
  51. });
  52. clearCache();
  53. window.location.reload();
  54. return true;
  55. };
  56. const key = `open${Date.now()}`;
  57. const btn = (
  58. <Button
  59. type="primary"
  60. onClick={() => {
  61. notification.close(key);
  62. reloadSW();
  63. }}
  64. >
  65. {'刷新'}
  66. </Button>
  67. );
  68. notification.open({
  69. message: '有新内容',
  70. description: '请点击“刷新”按钮或者手动刷新页面',
  71. btn,
  72. key,
  73. onClose: async () => null,
  74. });
  75. });
  76. } else if ('serviceWorker' in navigator && isHttps) {
  77. // unregister service worker
  78. const { serviceWorker } = navigator;
  79. if (serviceWorker.getRegistrations) {
  80. serviceWorker.getRegistrations().then((sws) => {
  81. sws.forEach((sw) => {
  82. sw.unregister();
  83. });
  84. });
  85. }
  86. serviceWorker.getRegistration().then((sw) => {
  87. if (sw) sw.unregister();
  88. });
  89. clearCache();
  90. }