typescript
let lastSrcs: any; //上一次获取到的script地址
const scriptReg = /<script.*?type=['"]module['"].*?src=['"](.*?)['"].*?>/g;
/**
* 获取最新页面中的script链接
*/
async function extractNewScript() {
const env = import.meta.env.MODE
if (env !== "production" ) return
const html = await fetch('/?_timestamp=' + Date.now()).then((res) => res.text());
const result:any[] = [];
// let match: any;
scriptReg.lastIndex = 0
const match = scriptReg.exec(html)
if(match)result.push(match[1]);
return result;
}
async function needUpdate() {
const newScripts:any = await extractNewScript();
if (!lastSrcs) {
lastSrcs = newScripts;
return false;
}
let result = false;
if (lastSrcs.length !== newScripts.length) {
result = true;
}
for (let i = 0; i < lastSrcs.length; i++) {
if (lastSrcs[i] !== newScripts[i]) {
result = true;
break;
}
}
lastSrcs = newScripts
return result
}
const DURATION = 10000;
function autoRefresh() {
setTimeout(async () => {
const willUpdate = await needUpdate();
if (willUpdate) {
const result = confirm("页面有更新,点击确定刷新页面");
if (result) {
location.reload();
}
}
autoRefresh();
}, DURATION);
}
autoRefresh()
main.ts
import '@/utils/auto.update'