前提: 登录类的页面,用户在登录进入系统后,如果长时间无操作,都会有自动退出功能。
项目中使用的是监听页面是否被点击来刷新用户无操作是自动退出的时长。
一般是对 window.document 添加 onmousedown,来刷新时间。
// 如果登录,每次操作页面,更新sessionStorage存入的操作时间
window.document.onmousedown = () => {
// console.log("开始", new Date().getTime())
if (window.sessionStorage.getItem('xxxLastTime') !== null) {
window.sessionStorage.setItem('xxxLastTime', new Date().getTime())
}
}
const checkTimeout = () => {
let currentTime = new Date().getTime() // 当前时间
let lastTime = window.sessionStorage.getItem('xxxLastTime') //上次操作的时间
// 判断是否超时
if (currentTime - lastTime >= timeOut && lastTime !== null) {
// 注销账号的时候传入登录获取验证码时的uuid
let uuid = sessionStorage.getItem('xxxUUID') || ''
// console.log(`注销账号的时候传入登录获取验证码时的uuid=${uuid}`);
proxy.$axios.post(config.PERMISSIONSYSTEM.URL_LOGOUT, { uuid }).then(() => {
// 注销账号成功的话将uuid本地缓存删除
sessionStorage.removeItem('xxxUUID')
sessionStorage.removeItem('xxxLastTime')
store.dispatch('user/userLogout')
})
.catch((error) => {
console.log(error)
store.dispatch('user/userLogout')
})
}
}
但是对于iframe 引入的外部页面,再点击或者操作页面事件时,却获取不到监听,此时就需要对iframe页面做自定义事件处理。
<template>
<iframe :key="$route.path + iframeUrl" :src="iframeUrl" id="iframeContainer"></iframe>
</template>
<script>
import {computed, onMounted, onUpdated} from 'vue';
import { useStore } from 'vuex';
export default {
setup(){
// 引用store
const store = useStore();
let iframeUrl = computed(() => store.getters["layout/getIframeUrl"])
// 第一次进入时,监听 iframe 的页面点击事件
onMounted(() => {
const iframe = document.getElementById('iframeContainer');
iframe.onload = function() {
iframe.contentDocument.onmousedown = function () {
console.log('点击了iframe页面')
if (window.sessionStorage.getItem('xxxLastTime') !== null) {
window.sessionStorage.setItem('xxxLastTime', new Date().getTime())
}
};
}
})
// 当iframe发生变化时,监听 iframe 的页面点击事件
onUpdated(() => {
const iframe = document.getElementById('iframeContainer');
iframe.onload = function() {
iframe.contentDocument.onmousedown = function () {
console.log('点击了变更的iframe页面')
if (window.sessionStorage.getItem('xxxLastTime') !== null) {
window.sessionStorage.setItem('xxxLastTime', new Date().getTime())
}
};
}
})
return {
iframeUrl
}
}
}
</script>
当点击iframe页面时效果如下: