项目中实现前端页面更新提示用户刷新页面

[npm 组件包地址]

## 安装

```
npm i auto-update-html
```

### 使配置 在 main.js 文件中引入组件和样式

```
import 'auto-update-html';
```

核心思路就是通过轮询获取前端首页html,然后从中分析script有无更新 

const html = await fetch('/?_timestamp=' + Date.now()).then((resp) => resp.text());

全部代码 

/*
 * @Author: Jackie
 * @Date: 2023-06-06 13:36:13
 * @LastEditTime: 2023-06-06 13:46:54
 * @LastEditors: Jackie
 * @Description: 自动检测前端页面更新,提示用户刷新前端页面
 * @FilePath: /auto-html/auto-update.js
 * @version: 
 */

let lastSrcs; //上一次获取script地址

const scriptReg = /\<script.*src=["'](?<src>[^"']+)/gm;

/**
 * 获取最新页面中script链接
 */
async function extractNewScripts() {
    const html = await fetch('/?_timestamp=' + Date.now()).then((resp) => resp.text());
    console.log(html);
    scriptReg.lastIndex = 0;
    let result = [];
    let match;
    while ((match = scriptReg.exec(html))) {
        result.push(match.groups.src);
    }
    return result;
}

async function needUpdate() {
    const newScripts = await extractNewScripts();
    console.log(newScripts);
    if (!lastSrcs) {
        lastSrcs = newScripts;
        return false;
    }
    let result = false;
    if (lastSrcs.length !== newScripts.length) {
        return true;
    }
    for (let i = 0; i < lastSrcs.length; i++) {
        if (lastSrcs[i] !== newScripts[i]) {
            result = true;
            break;
        }
    }
    lastSrcs = newScripts;
    return result;
}

const DURATION = 2000;
function autoRefresh() {
    setTimeout(async () => {
        const willUpdate = await needUpdate();
        console.log(willUpdate);
        if (willUpdate) {
            const result = confirm("页面有更新,点击确定刷新页面");
            if (result) {
                location.reload();
            }
        }
        autoRefresh();
    }, DURATION);
}

autoRefresh();

posted @ 2023-06-07 11:33  JackieDYH  阅读(86)  评论(0编辑  收藏  举报  来源