前端重新部署通知用户刷新

2023-09-21 08:43:17 浏览数 (1)

方案:通过轮询对比scripthash信息,不一致就触发更新操作 新建utils/updateApp.js文件

代码语言:javascript复制
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里进行引入

代码语言:javascript复制
import "@/utils/updateApp"

0 人点赞