纯前端实现版本更新检测

因为我们的用户会长期保持网页打开状态,有时已经发了新版,他们也不知道,无法使用到最新特性,或者没有看到bug修复,所以最近增加了版本检测功能。

基本原理就是,前端打包时写入当前时间戳到一个文件,作为版本号。前端定时检查版本号是否变化,如果有变化则弹出更新提示。

我们使用的Vuejs框架,使用vue-cli作为打包工具。

第一步

修改package.json文件,在打包以后写入版本文件

"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build && npm run update-version",
    "lint": "vue-cli-service lint",
    "update-version": "echo `date +%s` > dist/version.txt"
  },

第二步

编写检测函数,我把这一块代码放在App.vue文件里, 使用 this.hasUpdate 变量的目的是检测到更新后就不再继续检测。

  created () {
    this.checkVersion()
  },
  methods: {
    showUpdateDialog() {
      this.$confirm('There is an update available, do you want to reload?', 'Notification', {
        confirmButtonText: 'YES',
        cancelButtonText: 'NO',
        type: 'warning'
      }).then(() => {
        window.location.reload()
      });
    },
    async checkVersion () {
      const resp = await fetch(`/version.txt?timestamp=${Date.now()}`);
      const versionNow = parseInt(await resp.text());
      if (versionNow) {
        if (this.version) {
          if (versionNow > this.version) {
            this.hasUpdate = true
            this.showUpdateDialog()
          }
        } else {
          this.version = versionNow
        }
      }
      if (!this.hasUpdate) {
        setTimeout(this.checkVersion, 10 * 1000)
      }
    }
  }
17,660 views, since 2022-05-08