实现新版本发布提醒用户

305 阅读1分钟

需求场景

  • 对于B端用户,经常页面打开后长期不关闭,可以及时通知更新
  • 终端屏类型,无人控制
  • 功能更新需要及时反馈给客户

适用项目

  • react、vue、ng 等常规构建的单页面应用

实现思路

  • 通过 fetch 拿到服务器最新的 html 文件
  • 正则获取 html 新的 hash 值
  • 对比当前 hash 和最新的 hash ,不同则说明服务器的文件有更新

Demo 演示

// check-update.js
async function check() {
  const res = await fetch(`${location.origin}${location.pathname}?stamp=${Date.now()}`)
  const text = await res.text() // 服务器最新的 html
  const new_hash = text.match(/src="(.*)index(.*).js"><\/script>/)[2]
  const current_hash = document.getElementsByTagName('script')[0].src.match(/index(.*).js/)[1] // 当前hash
  if(new_hash !== current_hash) {
    confirm('有新版本发布, 是否更新') && location.reload()
  }
}
function checkUpdate() {
    setInterval(check, 10000) // 轮询检查
}
export default checkUpdate

在 vue 等项目中可以判断环境变量,开发环境不需要检查

import App from './App.vue'
import router from './router'
import checkUpdate from  './check-update.js'
const isDevelopment = import.meta.env.MODE === 'development' // vite
if(!isDevelopment) {
  console.log('启动更新检查')
  checkUpdate()
}