class Updater {
oldScript:any = [];
newScript:any = [];
dispatch:any = {};
constructor() {
this.oldScript = [];
this.newScript = [];
this.dispatch = {};
if(import.meta.env.MODE != 'development'){
this.init(); // 初始化
this.timing();
}
}
async init() {
const html = await this.getHtml();
this.oldScript = this.parserScript(html);
};
async getHtml() {
const html = await fetch('/?t='+new Date().getTime()).then(res => res.text());
return html
};
parserScript(html:any) {
const reg = new RegExp(/<script(?:\s+[^>]*)?>(.*?)<\/script\s*>/ig)
return html.match(reg)
}
on(key:any, fn:any) {
(this.dispatch[key] || (this.dispatch[key] = [])).push(fn)
return this;
}
compare(oldArr:any, newArr:any) {
const base = oldArr.length;
const arr = Array.from(new Set(oldArr.concat(newArr)));
if (arr.length === base) {
// this.dispatch['no-update'].forEach(fn => {
// fn();
// })
} else {
this.dispatch['update'].forEach((fn:any) => {
fn();
})
}
};
async timing() {
setInterval(async () => {
const newHtml = await this.getHtml();
this.newScript = this.parserScript(newHtml);
this.compare(this.oldScript, this.newScript)
}, 10 * 1000);
};
}
export default Updater;
使用:
import Updater from '@/utils/checkedUpDate.ts'
const AutoUpdate = new Updater()
AutoUpdate.on('update',()=>{
setTimeout(async()=>{
const result = confirm('当前网站有更新,请点击确定刷新页面体验');
if(result){
location.reload();
}
},500)
})