Vue項目實現用戶長時間不操作,自動退出登錄

Vue項目實現用戶長時間不操作,自動退出登錄

1.實現思路

使用 mouseover事件來監測是否有用戶操作頁面,然後寫一個定時器間隔特定時間檢測是否長時間未操作頁面,如果是清除token,提示登錄已過期請重新登錄

每隔10s去檢查一下用戶是否過了10秒 未操作頁面
因爲我這邊是單點登錄所以用戶10秒 未操作就要跳轉到單點登錄系統,所以跳轉這一塊按實際情況來修改

(1)在 util 文件夾下創建一個 auto_loginout.js 文件

 

code
 import router from '@/router'
export default function () {
    let setInterval = null;//定時器
    let timeOut = 10 * 1000 // 設置超時時間: 10秒鐘
    // console.log("開始", new Date().getTime())
    // 初次向sessionStorage存入操作時間
    window.sessionStorage.setItem('lastTime', new Date().getTime())
    // 每次操作頁面,更新sessionStorage存入的操作時間
    window.onload = function () {
        window.document.onmousedown = function () {
            // console.log("開始", new Date().getTime())
            window.sessionStorage.setItem('lastTime', new Date().getTime())
        }
    }
    function checkTimeout() {
        let currentTime = new Date().getTime() // 當前時間
        let lastTime = window.sessionStorage.getItem("lastTime")//上次操作的時間
        // 判斷是否超時
        if (currentTime - lastTime >= timeOut) {
            // console.log("結束", new Date().getTime())
            // 清除定時器
            window.clearInterval(setInterval);
            // 清除sessionStorage
            window.sessionStorage.clear('lastTime')
            // 跳到登陸頁
            if (router.history.current.fullPath !== '/' && router.history.current.fullPath !== '/login') {
                router.push("/login")
                window.location.reload()
            }
        }
    }
    /* 定時器 間隔2秒檢測是否長時間未操作頁面 */
    setInterval = window.setInterval(checkTimeout, 2000)
}

(2)在 main.js 中引用,通過全局方法 Vue.use() 使用

// 自動退出文件路徑
import auto_loginout from '@/util/auto_loginout.js'
Vue.use(auto_loginout)

 先事件設置一下5秒:每隔5s去檢查一下用戶是否過了5秒 未操作頁面
因爲我這邊是單點登錄所以用戶5秒 未操作就要跳轉到單點登錄系統,所以跳轉這一塊按實際情況來修改

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章