global.tsx 2.17 KB
Newer Older
1 2
import React from 'react';
import { notification, Button, message } from 'antd';
3
import { formatMessage } from 'umi-plugin-react/locale';
4
import defaultSettings from '../config/defaultSettings';
5

Yu's avatar
Yu committed
6 7 8 9 10 11 12 13 14
const { pwa } = defaultSettings;
// if pwa is true
if (pwa) {
  // Notify user if offline now
  window.addEventListener('sw.offline', () => {
    message.warning(formatMessage({ id: 'app.pwa.offline' }));
  });

  // Pop up a prompt on the page asking the user if they want to use the latest version
何乐's avatar
何乐 committed
15 16
  window.addEventListener('sw.updated', (event: Event) => {
    const e = event as CustomEvent;
Yu's avatar
Yu committed
17 18 19 20 21 22 23 24 25 26
    const reloadSW = async () => {
      // Check if there is sw whose state is waiting in ServiceWorkerRegistration
      // https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
      const worker = e.detail && e.detail.waiting;
      if (!worker) {
        return Promise.resolve();
      }
      // Send skip-waiting event to waiting SW with MessageChannel
      await new Promise((resolve, reject) => {
        const channel = new MessageChannel();
何乐's avatar
何乐 committed
27 28 29
        channel.port1.onmessage = msgEvent => {
          if (msgEvent.data.error) {
            reject(msgEvent.data.error);
Yu's avatar
Yu committed
30
          } else {
何乐's avatar
何乐 committed
31
            resolve(msgEvent.data);
Yu's avatar
Yu committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
          }
        };
        worker.postMessage({ type: 'skip-waiting' }, [channel.port2]);
      });
      // Refresh current page to use the updated HTML and other assets after SW has skiped waiting
      window.location.reload(true);
      return true;
    };
    const key = `open${Date.now()}`;
    const btn = (
      <Button
        type="primary"
        onClick={() => {
          notification.close(key);
          reloadSW();
        }}
      >
        {formatMessage({ id: 'app.pwa.serviceworker.updated.ok' })}
      </Button>
    );
    notification.open({
      message: formatMessage({ id: 'app.pwa.serviceworker.updated' }),
      description: formatMessage({ id: 'app.pwa.serviceworker.updated.hint' }),
      btn,
      key,
      onClose: async () => {},
58 59
    });
  });
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
60 61 62 63 64
} else if ('serviceWorker' in navigator) {
  // eslint-disable-next-line compat/compat
  navigator.serviceWorker.ready.then(registration => {
    registration.unregister();
  });
Yu's avatar
Yu committed
65
}