global.js 1.71 KB
Newer Older
1 2
import React from 'react';
import { notification, Button, message } from 'antd';
xiaoiver's avatar
xiaoiver committed
3 4 5 6 7 8 9 10 11
import { formatMessage } from 'umi/locale';

// 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
window.addEventListener('sw.updated', e => {
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
  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();
      channel.port1.onmessage = event => {
        if (event.data.error) {
          reject(event.data.error);
        } else {
          resolve(event.data);
        }
      };
      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;
  };
35 36
  const key = `open${Date.now()}`;
  const btn = (
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
37 38 39 40 41 42 43
    <Button
      type="primary"
      onClick={() => {
        notification.close(key);
        reloadSW();
      }}
    >
44 45 46 47 48 49 50 51
      {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,
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
52
    onClose: async () => {},
xiaoiver's avatar
xiaoiver committed
53 54
  });
});