vue多tab页面全部关闭后自动退出登录

业务场景:主项目是用vue写的单页面应用,但是有多开页面的需求,现在需要在用户关闭了所有的浏览器标签页面后,自动退出登录。

思路:因为是不同的tab页面,我只能用localStorage来通信,新打开一个标签页(页面初次装载时),我就往数组中加一个页面,在(页面关闭或刷新等)页面卸载时移除它。这样就只需要在页面装载时(load事件)判断当前是不是刷新页面就可以了,只要是其他来源就直接登出。

2024-01-06 22:23 更新:修改了页面load事件,在页面数组中无页面时,直接去登录页面了,但是还是得把页面加入到页面数组中,那个return没有必要。这个return会导致进入一个新设备(或者清空了浏览器缓存,即清空了currently_open_page)时,未记录当前页,那么页面数组就是空的,导致打开新页面时也直接去登出了。

代码

import store from '@/store'

const cache_key = 'currently_open_page'

/**
 * 主方法,外部只要调用此方法就可以了
 */
export function mount() {
  window.addEventListener('beforeunload', function () {
    const currentRoute = getCurrentPage()
    delPage(currentRoute)
  })

  window.addEventListener('load', function () {
    // 网页通过“重新加载”按钮或者location.reload()方法加载
    if (window.performance.navigation.type != 1) {
      // 如果页面不是刷新进来,不管是任何来源,都可以认为是新进入页面,此时应该就去登录页面
      if (!getCurrentOpenPageList().length) {
        store.dispatch('user/logout')
      }
      // return
    }

    // 添加新的页面
    const currentRoute = getCurrentPage()
    addPage(currentRoute)
  })
}

/**
 * 获取当前的页面(tab页面),目前就用时间值吧
 * @returns
 */
function getCurrentPage() {
  if (!window._currentPage) {
    window._currentPage = 'page_' + new Date().getTime()
  }
  return window._currentPage
}

/**
 * 获取当前已打开的页面列表
 * @returns
 */
function getCurrentOpenPageList() {
  const t = window.localStorage.getItem(cache_key)
  if (t) {
    return JSON.parse(t)
  } else {
    window.localStorage.setItem(cache_key, JSON.stringify([]))
    return []
  }
}

/**
 * 往缓存中新增页面
 */
function addPage(page) {
  const list = getCurrentOpenPageList()
  list.push(page)
  window.localStorage.setItem(cache_key, JSON.stringify(list))
}

/**
 * 往缓存中移除页面
 */
function delPage(page) {
  const list = getCurrentOpenPageList()
  const findIndex = list.indexOf(page)
  if (findIndex != -1) {
    list.splice(findIndex, 1)
  }
  window.localStorage.setItem(cache_key, JSON.stringify(list))
}

/**
 * 清除所有的页面
 */
export function clearAllPage() {
  window.localStorage.setItem(cache_key, JSON.stringify([]))
}

你可能感兴趣的:(vue.js,前端,javascript)