网站检测更新提示

2023-05-12 22:32:26

记录下检测vue项目代码更新并提示的简易实现

背景

系统新功能上线后需要提示用户刷一下页面才能体验,下面介绍一种纯前端的简单实现方式。

实现方法介绍

该方法适用于vue做的单页应用项目。

思路:轮询比较首页(index)页面内引用脚本的hash值,判断脚本有无变化,有变化就通知用户并进行页面刷新。

参考代码

可以在vue项目App.vue的创建回调中参考增加如下代码来实现。


const axios = require('axios');
let resp = await axios({
  method: 'get',
  url: '/',
  responseType: 'html'
})
let oldScript = resp.data.match(new RegExp(/<script(?:\s+[^>]*)?>(.*?)<\/script\s*>/ig))
let tipTimer = setInterval(async () => {
  let newHtml = await axios({
    method: 'get',
    url: '/',
    responseType: 'html'
  })
  let newScript = newHtml.data.match(new RegExp(/<script(?:\s+[^>]*)?>(.*?)<\/script\s*>/ig))
  const oldScriptLen = oldScript.length
  const arr = Array.from(new Set(oldScript.concat(newScript)))
  if (arr.length !== oldScriptLen) {
    this.$notify({
      title: '更新提醒',
      message: '检测到系统功能有升级,关闭提示后自动刷新获取更新',
      type: 'success',
      duration: 0,
      onClose: () => {
         location.reload();
    }
    });
    clearInterval(tipTimer);
  }
}, 7000)
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-ND 3.0 许可协议。可自由转载、引用,但需署名作者且注明文章出处。如转载至微信公众号,请在文末添加作者公众号二维码。

扫描下方二维码阅读当前文章

浏览器、微信扫码

评 论:

好文推荐
每天进步一点点~