方案:通过轮询对比script
的hash
信息,不一致就触发更新操作
新建utils/updateApp.js
文件
import { ElMessageBox } from 'element-plus'
const getHtml = async () => {
return await fetch('/').then(res => res.text())//读取index html
}
const parserScript = (html) => {
const reg = new RegExp(/<script(?:s [^>]*)?>(.*?)</scripts*>/ig)
return html.match(reg) //匹配script标签
}
let flag = true
const compare = (oldArr, newArr) => {
const base = oldArr.length
const arr = Array.from(new Set(oldArr.concat(newArr)))
//如果新旧length 不一样 触发更新通知
if (arr.length != base && flag) {
flag = false
ElMessageBox.confirm('网页有更新,是否立即刷新?', '提示', { type: 'warning' }).then(() => {
location.reload()
})
}
}
let oldScript = null
const init = async () => {
const html = await getHtml()
oldScript = parserScript(html)
}
init()
setInterval(async () => {
const newHtml = await getHtml()
const newScript = parserScript(newHtml)
compare(oldScript, newScript)
}, 5000)
在main.js
里进行引入
import "@/utils/updateApp"