export class Updater { oldScript: string[]; newScript: string[]; dispatch: Record; interVal: any; constructor(options) { this.oldScript = []; this.newScript = []; this.dispatch = {}; this.interVal = null; this.init(); this.timing(options.timer || 2000); } async init() { const html = await this.getHtml(); this.oldScript = this.parserScript(html); } async getHtml() { const html = await fetch('/').then((res) => res.text()); return html; } parserScript(html) { const reg = new RegExp(/]*)?>(.*?)<\/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))); if (arr.length === base) { this.dispatch['no-update']?.forEach((fn) => { // 没有更新 fn(); }); } else { this.dispatch['update']?.forEach((fn) => { // 有新版本更新 fn(); }); } } // 开启定时查询 timing(time) { this.interVal = setInterval(async () => { const newHtml = await this.getHtml(); this.newScript = this.parserScript(newHtml); this.compare(this.oldScript, this.newScript); }, time); } // 关闭定时器 closeInterVal() { if (this.interVal) { clearInterval(this.interVal); this.interVal = null; } } }