vue给iframe页面添加点击事件,刷新用户无操作时自动退出时间

前提: 登录类的页面,用户在登录进入系统后,如果长时间无操作,都会有自动退出功能。

项目中使用的是监听页面是否被点击来刷新用户无操作是自动退出的时长。

一般是对 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页面时效果如下:

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值