use-common.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { getLastBuildDate } from '@/utils/localStorage/app';
  2. import { windowReload } from 'billd-utils';
  3. import { useTip } from './use-tip';
  4. export const useCheckUpdate = () => {
  5. function handleHtmlCheckUpdate(data: {
  6. htmlUrl: string;
  7. lastBuildDate: string;
  8. }) {
  9. return new Promise<{ shouldTip: boolean }>((resolve) => {
  10. const xhr = new XMLHttpRequest();
  11. xhr.open('GET', data.htmlUrl, true);
  12. xhr.onreadystatechange = function () {
  13. try {
  14. if (this.readyState !== 4) return;
  15. if (this.status !== 200) return; // or whatever error handling you want
  16. const reg = /\('最后构建日期:', "(.+)"\)/;
  17. const res = reg.exec(this.responseText);
  18. if (res?.[1] !== data.lastBuildDate) {
  19. resolve({ shouldTip: true });
  20. console.log('提示更新');
  21. useTip({
  22. content: '发现新内容可用,是否刷新页面?',
  23. confirmButtonText: '刷新',
  24. })
  25. .then(() => {
  26. windowReload();
  27. })
  28. .catch(() => {});
  29. } else {
  30. resolve({ shouldTip: false });
  31. console.log('不提示更新');
  32. }
  33. } catch (error) {
  34. console.error(error);
  35. }
  36. };
  37. xhr.send();
  38. });
  39. }
  40. function checkUpdate(data: { htmlUrl: string }) {
  41. setInterval(
  42. async () => {
  43. const lastBuildDate = getLastBuildDate();
  44. if (lastBuildDate) {
  45. const res = await handleHtmlCheckUpdate({
  46. htmlUrl: data.htmlUrl,
  47. lastBuildDate,
  48. });
  49. return res;
  50. }
  51. },
  52. 1000 * 60 * 5
  53. );
  54. }
  55. return { checkUpdate };
  56. };