700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 前端react 实现监控鼠标移动超时未操作踢出登录页面

前端react 实现监控鼠标移动超时未操作踢出登录页面

时间:2021-10-22 04:33:21

相关推荐

前端react 实现监控鼠标移动超时未操作踢出登录页面

前言

现有系统超时踢出登录实现的是页面操作调取服务时获取,这样就有一个弊端,列如:在未调取服务时,系统填写完相关信息点击提交才知道登录超时踢出登录,用户实用性不佳。

现在想到一个方法就是前端获取用户鼠标是否移动,未移动一定时间后,前端实现踢出登录操作。

1.给页面最外层的div增加监听事件

let ICE_CONTAINER = document.getElementById('app');//鼠标最后的操作时间let lastTime = new Date().getTime();//当前时间let currentTime = new Date().getTime();//flag判断是否为登录页let timeType = false;ICE_CONTAINER.addEventListener('mousemove', function() {// 更新最后的操作时间console.log('鼠标移动了')lastTime = new Date().getTime();})

2.写个定时器监听页面

timeType 判断页面是否为登录页,如果是不执行踢出登录操作

testTime = () => {//定时器timeType = window.location.href.indexOf('login') < 0;//更新当前时间currentTime = new Date().getTime();//判断是否超时if (currentTime - lastTime > timeOut) {//timeType if (timeType) {console.log('超时拉')// 超时操作Msg.alert('长时间未操作,请重新登录!');Tools.logout();lastTime = new Date().getTime();} else {lastTime = new Date().getTime();console.log('我不会踢出的')}}}

3.调取后端接口,配置踢出登录时间

这样做目的:每次踢出登录时间更改时,不需要发布版本,更改数据库配置就可以了

//设置超时时间: 60分let timeOut = 60 * 1000; //获取定时器时间const url = `${API_UPLOAD_URL}/kaptcha/getOutTime`;const xhr = new XMLHttpRequest();xhr.open('POST', url, true);xhr.setRequestHeader('Content-Type', 'application/json');xhr.responseType = 'json'; //返回类型blobxhr.send();xhr.onload = function () {//定义请求完成的处理函数if (this.status === 200) {if (this.response) {timeOut = timeOut * this.response.data;//成功执行定时器window.setInterval(testTime, 5000);}}};

好了,到这里一个简单的前端实现踢出登录操作就实现了,完整代码:

import {Tools, Msg} from './tools'import {KaptchaService} from '../api/kaptcha-service';//设置超时时间: 60分let timeOut = 1 * 60 * 1000;let lastTime = new Date().getTime();let currentTime = new Date().getTime();let ICE_CONTAINER = document.getElementById('app');let quit;class OvertimeLogin {static setMousemove () {/* 检测鼠标移动事件 */ICE_CONTAINER.addEventListener('mousemove', function() {// 更新最后的操作时间console.log('鼠标移动了')lastTime = new Date().getTime();})}static testTime() {//更新当前时间currentTime = new Date().getTime();console.log('currentTime', currentTime)//判断是否超时if (currentTime - lastTime > timeOut) {if (window.location.href.indexOf('login') < 0) {console.log('超时拉')// 超时操作Msg.alert('长时间未操作,请重新登录!');Tools.logout();lastTime = new Date().getTime();} else {lastTime = new Date().getTime();}}}static setOutTime() {//获取超时时间&&执行定时函数const Service = new KaptchaService();Service.getOutTime().then(res => {if (res) {timeOut = timeOut * res;this.setMousemove();quit = window.setInterval(this.testTime, 5000);}});}static quitTime () {window.clearInterval(quit);}}export {OvertimeLogin}

结束语:小菜鸡一枚,不对的地方,请谅解!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。