vue中js判断长时间不操作界面自动退出登录

1,390 阅读1分钟

前端实现用js判断半个小时不操作界面的话自动跳转到登录页面。

创建一个.js文件,在main.js引入此js(vue框架)

在登录成功的时候保存当前时间

 localStorage.setItem("lastTime",new Date().getTime());

然后在点击的时候更新这个时间

`var lastTime = new Date().getTime();`
`var currentTime = new Date().getTime();`
`var timeOut = 30 * 60 * 1000; //设置超时时间: 30分`

`window.onload = function () {`
    `window.document.onmousedown = function () {`
        `localStorage.setItem("lastTime",new Date().getTime());`
    `}`
`};`
`function checkTimeout() {`
    `currentTime = new Date().getTime(); //更新当前时间`
    `lastTime = localStorage.getItem("lastTime");`
    `// console.log(currentTime - lastTime);`
    `// console.log(timeOut);`
    `if (currentTime - lastTime > timeOut) { //判断是否超时`
        `// console.log("超时");`
        `var url = window.location.href;`
        `var newUrl=url.match(/(\S*)#/)[1];`
``        

```
    window.open(newUrl + '#/login','_self');
}
```

`}`

/* 定时器 间隔30秒检测是否长时间未操作页面 */

 `window.setInterval(checkTimeout, 30000);`

每隔30s去检查一下是否过了30分钟。