If the user does not operate the page for 30 minutes, return to the user login page

       1. Description

       Due to the need for security and security considerations, it is necessary to automatically log out to the login page if the user does not operate the page within 30 minutes. There are many implementation schemes. For example: use session: the back-end developer sets the expiration time of the session , It will be cleared automatically if there is no request for a long time (for example, 30 minutes), to achieve the purpose of automatic exit without operation for a long time, the front-end global monitoring of click events, combined with websocket to push user status in real time, etc.

        Two, ideas

        Talk about a solution that does not need back-end cooperation, and the front-end realizes this function; user operations: moving, dragging, clicking, scrolling, etc. Most of the basic operations require the user to click and realize the idea:

       1. Monitor the user's click time globally and save the user's last click event: lastClickTime

       2. Start a timer to record the current time in real time: nowTime

       3. How long the user does not operate the page: noOperateTime

       When nowTime - lastClickTime > noOperateTime , perform user exit operation

          3. Code implementation

       The code is as follows, a component that is directly encapsulated, you can directly import the component in app.vue when you use it

<template>
  <div></div>
</template>
<script>

export default {
  data() {
    return {
      timer: null,
      noOperateTime: 1000 * 60 * 30 // 用户不操作的时间
    }
  },
  created() {},
  mounted() {
    /*
      第一步:
        组件初始化加载就绑定监听点击事件,注意:addEventListener的第三个参数,这里要加上。
        因为第三个参数决定了是冒泡还是捕获(false冒泡默认,true捕获),因为绑定监听点击事件,我们是在最
        顶层的DOM位置进行捕获点击事件,所以第三个参数true,要加上的,这样的话,内层的任意地方的点击事件
        我们就都能监听到了,然后存储一下点击的时间
    */
    window.addEventListener(
      'click',
      () => {
        // 为了方便,我们把点击事件的时间直接存到sessionStorage中去,这样方便获取比较
        sessionStorage.setItem('lastClickTime', new Date().getTime())
      },
      true
    )
    this.isTimeOut()
  },
  beforeDestroy() {
    // 最后一步,离开页面的时候,清除一下定时器,也解绑点击事件
    clearInterval(this.timer)
    window.removeEventListener('click', () => {}, true)
  },
  methods: {
    isTimeOut() {
      clearInterval(this.timer)
      this.timer = setInterval(() => {
        let isLoginHref = window.location.pathname
        if (!isLoginHref.includes('/login')) {
          let lastClickTime = Number(sessionStorage.getItem('lastClickTime'))
          let nowTime = new Date().getTime()
          if (nowTime - lastClickTime > this.noOperateTime) {
            this.$message.error('您已经30分钟没有操作产康运营管理平台,请重新登录使用。')
            // 退出逻辑
            this.$router.push('/login')
          }
        }
      }, 1000 * 60)
    }
  }
}
</script>

Guess you like

Origin blog.csdn.net/qq_35432904/article/details/127846812