auto-update.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. *通过监听当前页面的JS的SRC来判断当前网页是否有更新
  3. *使用方法 main.js import checkUpdate from "/@/utils/auto-update";
  4. */
  5. let lastSrcs: any[] | null; //上次js地址集合
  6. // const scriptReg = /(?<=<script.*src=["']).*?(?=["'])/gm; //IOS 不支持断言匹配
  7. const scriptReg = /<script.*?src=['"](.*?)['"]/gm;
  8. /**
  9. * 获取最新的js集合
  10. * @returns
  11. */
  12. async function extractNewScripts() {
  13. const html = await fetch('/?_t=' + Date.now()).then((res) => res.text());
  14. scriptReg.lastIndex = 0;
  15. const result = html.match(scriptReg);
  16. return result;
  17. }
  18. /**
  19. * 判断是否有更新
  20. * @returns
  21. */
  22. async function checkUpdate() {
  23. const newScripts = await extractNewScripts();
  24. if (!lastSrcs) {
  25. lastSrcs = newScripts;
  26. return false;
  27. }
  28. if (newScripts == null) return false;
  29. let result = false;
  30. if (lastSrcs.length !== newScripts.length) {
  31. result = true;
  32. }
  33. for (let i = 0; i < lastSrcs.length; i++) {
  34. if (lastSrcs[i] !== newScripts[i]) {
  35. result = true;
  36. break;
  37. }
  38. }
  39. lastSrcs = newScripts;
  40. return result;
  41. }
  42. /**
  43. * 定时器定时检测是否更新,有更新则执行回调函数
  44. * @param callbackFn
  45. * @param interval
  46. */
  47. function checkUpdateInterval(callbackFn: any, interval: number = 60000) {
  48. setTimeout(async () => {
  49. const willUpdate = await checkUpdate();
  50. if (willUpdate) {
  51. callbackFn();
  52. }
  53. checkUpdateInterval(callbackFn, interval);
  54. }, interval);
  55. }
  56. export default checkUpdateInterval;