1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- import { h } from 'vue'
- import { ElNotification } from 'element-plus'
- // 用于记录时间戳的变量,时间戳是响应头中的etag和last-modified字段其中之一
- let previousTimeTag: string | null = '';
- async function getTimeTag() {
- const response = await fetch(`${window.location.protocol}//${window.location.host}`, {
- method: 'HEAD',
- cache: 'no-cache'
- })
- // 以响应体的etag或者last-modified为时间戳
- return response.headers.get('etag') || response.headers.get('last-modified')
- }
- let notice:any = null;
- async function judge() {
- // 获取当前最新的时间戳
- const currentTimeTag = await getTimeTag()
- // 检测到最新请求的时间戳和上一次不一致,即文件发生变化
- if (previousTimeTag !== currentTimeTag) { // 需要更新的逻辑
- // 监听是否更新
- const noticeList: any[] = [
- h('p', { class: 'mb10' }, '检测到有新版本'),
- h('p', { style: { justifyContent: 'flex-end' } }, [
- h('button', { class: 'el-button', onClick: ignore }, '忽略'),
- h('button', { class: 'el-button el-button--primary', onClick: Refresh, }, '刷新')
- ]),
- ]
- notice = ElNotification({
- title: '提示',
- type:"warning",
- dangerouslyUseHTMLString: true,
- message: h('div', {}, noticeList),
- customClass:"updateTips"
- })
- }
- }
- // 忽略
- const ignore = () => {
- notice.close();
- }
- // 刷新
- const Refresh = () => {
- window.location.reload();
- }
- /**
- * @description: 查询是否更新版本
- * @param {number} timer 轮询时间
- * @param {boolean} immediately 是否立即执行
- */
- export default async function checkUpdate(timer: number = 60, immediately: boolean = true) {
- // 通过立即执行函数,记录首次请求的时间戳,以便与后面轮询得出的时间戳进行对比
- previousTimeTag = await getTimeTag()
- window.versionMonitor && clearInterval(window.versionMonitor)
- // 开启轮询执行judge函数
- window.versionMonitor = setInterval(() => {
- judge()
- }, timer * 1000)
- if (immediately) judge() //是否立即执行一次
- }
|