查询网站是否更新

<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      previousTimeTag: ''
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      this.previousTimeTag = await this.getTimeTag()
      window.versionMonitor && clearInterval(window.versionMonitor)
      window.versionMonitor = setInterval(() => {
        this.judge()
      }, 60 * 1000)
    },
    async getTimeTag() {
      const response = await fetch(`${window.location.protocol}//${window.location.host}`, {
        method: 'HEAD',
        cache: 'no-cache'
      })
      // 以响应体的etag或者last-modified为时间戳
      return response.headers.get('etag') || response.headers.get('last-modified')
    },
    async judge() {
    // 获取当前最新的时间戳
      const currentTimeTag = await this.getTimeTag()
      // 检测到最新请求的时间戳和上一次不一致,即文件发生变化
      if (this.previousTimeTag !== currentTimeTag) {
        window.location.reload()
      }
    }
  }
}
</script>

 

posted @ 2023-01-11 17:15  zy-lzh  阅读(56)  评论(0)    收藏  举报