checkUpdate.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { h } from 'vue'
  2. import { ElNotification } from 'element-plus'
  3. // 用于记录时间戳的变量,时间戳是响应头中的etag和last-modified字段其中之一
  4. let previousTimeTag: string | null = '';
  5. async function getTimeTag() {
  6. const response = await fetch(`${window.location.protocol}//${window.location.host}`, {
  7. method: 'HEAD',
  8. cache: 'no-cache'
  9. })
  10. // 以响应体的etag或者last-modified为时间戳
  11. return response.headers.get('etag') || response.headers.get('last-modified')
  12. }
  13. let notice:any = null;
  14. async function judge() {
  15. // 获取当前最新的时间戳
  16. const currentTimeTag = await getTimeTag()
  17. // 检测到最新请求的时间戳和上一次不一致,即文件发生变化
  18. if (previousTimeTag !== currentTimeTag) { // 需要更新的逻辑
  19. // 监听是否更新
  20. const noticeList: any[] = [
  21. h('p', { class: 'mb10' }, '检测到有新版本'),
  22. h('p', { style: { justifyContent: 'flex-end' } }, [
  23. h('button', { class: 'el-button', onClick: ignore }, '忽略'),
  24. h('button', { class: 'el-button el-button--primary', onClick: Refresh, }, '刷新')
  25. ]),
  26. ]
  27. notice = ElNotification({
  28. title: '提示',
  29. type:"warning",
  30. dangerouslyUseHTMLString: true,
  31. message: h('div', {}, noticeList),
  32. customClass:"updateTips"
  33. })
  34. }
  35. }
  36. // 忽略
  37. const ignore = () => {
  38. notice.close();
  39. }
  40. // 刷新
  41. const Refresh = () => {
  42. window.location.reload();
  43. }
  44. /**
  45. * @description: 查询是否更新版本
  46. * @param {number} timer 轮询时间
  47. * @param {boolean} immediately 是否立即执行
  48. */
  49. export default async function checkUpdate(timer: number = 60, immediately: boolean = true) {
  50. // 通过立即执行函数,记录首次请求的时间戳,以便与后面轮询得出的时间戳进行对比
  51. previousTimeTag = await getTimeTag()
  52. window.versionMonitor && clearInterval(window.versionMonitor)
  53. // 开启轮询执行judge函数
  54. window.versionMonitor = setInterval(() => {
  55. judge()
  56. }, timer * 1000)
  57. if (immediately) judge() //是否立即执行一次
  58. }