项目更新后提示刷新页面
220 字小于 1 分钟
2024-12-28
代码实现
import axios from 'axios'
export class Updater {
constructor(timer) {
this.oldScript = []
this.newScript = []
this.dispatch = {}
this.init()
this.timing(timer)
}
async init() {
const html = await this.getHtml()
this.oldScript = this.parserScript(html)
}
async getHtml() {
const text = await axios('/').then((res) => res.data)
return text
}
parserScript(html) {
const reg = new RegExp(/<script(?:\s+[^>]*)?>(.*?)<\/script\s*>/gi)
return html.match(reg)
}
// 发布订阅通知
on(key, fn) {
(this.dispatch[key] || (this.dispatch[key] = [])).push(fn)
return this
}
compare(oldArr, newArr) {
const base = oldArr.length
const arr = Array.from(new Set(oldArr.concat(newArr)))
// 如果新旧length 一样无更新
if (arr.length === base) {
this.dispatch['no-update'].forEach((fn) => {
fn()
})
} else {
// 否则通知更新
this.dispatch['update'].forEach((fn) => {
fn()
})
}
}
timing(time = 10000) {
// 轮询
setInterval(async () => {
const newHtml = await this.getHtml()
this.newScript = this.parserScript(newHtml)
this.compare(this.oldScript, this.newScript)
}, time)
}
}
用法
import { Updater } from './updateServer'
// 实例化该类
const updateServer = new Updater(3000)
// 未更新通知
// updateServer.on('no-update', () => {
// console.log('项目未更新')
// })
// 更新通知
updateServer.on('update', () => {
console.log('项目已更新')
})