vue 前端页面无操作时,执行某些操作

25 篇文章 0 订阅
该博客介绍了如何通过JavaScript监听用户的鼠标、键盘和滚动事件,实现当用户长时间无操作时自动登出系统,以保护用户数据安全。通过设置定时器,在达到预设的无操作分钟后提示用户即将退出,并在一段时间后执行登出操作。这种方法有助于防止未经授权的他人使用电脑访问用户信息。
摘要由CSDN通过智能技术生成

需求:

用户长时间不再操作电脑的时候,应该给用户自动退出系统,这样可以防止有别人使用电脑操作上一个用户的数据。
或用户长时间不操作,隐藏鼠标等。

思路

  • 监听鼠标移动以及键盘操作。
  • 设置timer,timer到达指定值后进行跳转并提示。
  • 开启timer并且关闭timer

实现

设定一个计数值,利用js原生的事件,对鼠标,键盘进行监听,如果一有触发的鼠标,键盘的话,就将计数值清零,否则,计数值一直累加,当累加到一个目标值,即那个无操作退出系统的时间就可以触发退出系统函数。

data () {
    return {
        count: 0
        }
},
mounted () {
    // 监听鼠标
    document.onmousemove = (event) => {
      let x1 = event.clientX
      let y1 = event.clientY
      if (this.x !== x1 || this.y !== y1) {
        this.count = 0
      }
      this.x = x1
      this.y = y1
    }
    // 监听键盘
    document.onkeydown = () => {
      this.count = 0
    }
    // 监听Scroll
    document.onscroll = () => {
      this.count = 0
    }
    this.setTimer()
  },
// 最后在beforeDestroy()生命周期内清除定时器:
  beforeDestroy () {
    this.clearTimer()
  },
methods: {
    clearTimer () {
      clearInterval(window.myTimer)
      window.myTimer = null
    },
    setTimer () {
      this.count = 0
      if (!window.myTimer) {
        window.myTimer = window.setInterval(this.cookieTimeout, 1000)
      }
    },
    cookieTimeout () {
    // 判断用户5分钟无操作就自动登出
      let outTime = 5
      this.count++
      if (this.count === outTime * 60) {
        this.$message({
          message: '系统已经五分钟无操作,将在十秒后退出登录,如不想退出系统,请任意操作鼠标键盘...',
          type: 'error'
        })
        setTimeout(this.logout, 10000)
        // console.log('aaaa', this.count)
      }
    },
    logout () {
      // console.log('bbb', this.count)
      if (this.count >= 5 * 60) {
        sessionStorage.setItem('loginname', '')
        this.$router.replace({name: 'Login'})
      }
    },
}

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值