如何判断浏览器同源标签页数量

需求:最近接到一个优化,项目在登录后,如果用户想在新的标签页中直接打开项目中的链接,无需再次登录

为了安全,项目token 都存在sessionStorage中的,关闭页面后即sessionStorage存储的数据自动清空,但是sessionStorage存储同源标签页无法共享,只有localStorage才能相互共享。

我在网上看了很多方法,最后还是采用localStorage + sessionStorage的方法相结合

思路 token仍缓存至localStorage,但是关闭最后一个标签页面后,清空localStorage

首先保证新的标签页有唯一的uuid,即时刷新也不会变化

js 复制代码
this.uuid = sessionStorage.getItem('uuid') ?? ''
if (!this.uuid) {
    this.uuid = String(Date.now())
    setSession('uuid', this.uuid)
}

其次我会往localStorage中存一个token 和 新的数组uuids

js 复制代码
localStorage.setItem('token', your token)
const uuids = localStorage.getItem('uuids') ?? JSON.stringify([])
const arr: Array<string> = JSON.parse(uuids)
if (!arr.includes(this.uuid)) {
    arr.push(this.uuid)
    localStorage.setItem('uuids', JSON.stringify(arr))
}

然后监听页面销毁,并在localStorage中uuids数组删除当前页面的uuid,这样就能判断同源打开了几个页面,如果当前是最后一个,就执行localStorage.clear()

js 复制代码
created() {
    window.addEventListener('beforeunload', this.beforeunload)
}

beforeDestroy() {
    window.removeEventListener('beforeunload', this.beforeunload)
}

beforeunload() {
    const uuids = getLocal('uuids')
    if (uuids) {
        const arr: Array<string> = JSON.parse(uuids)
        const index = arr.indexOf(this.uuid)
        if (index > -1) {
            arr.splice(index, 1)
            localStorage.setItem('uuids', JSON.stringify(arr))
            if (arr.length === 0) {
                localStorage.clear()
            }
        }
    }
}
相关推荐
其实防守也摸鱼12 分钟前
前端应用的离线暂停更新策略:构建稳定可靠的渐进式部署方案
服务器·前端·数据库·学习·ai·命令行·linux系统
太平洋月光20 分钟前
Antv G2中自定义技巧📊
前端·数据可视化
shmily麻瓜小菜鸡31 分钟前
前端“伪防盗链”方案
前端·javascript·vue.js·bootstrap·echarts
mayaairi32 分钟前
JS数组完全指南(含十大操作详解)
开发语言·前端·javascript
IT_陈寒1 小时前
Python的线程池把我CPU跑满了,原来少传了个参数
前端·人工智能·后端
喜欢的名字被抢了1 小时前
写-Chrome-扩展时踩过的那些-MV3-的坑
前端·chrome
网安老伯1 小时前
网络安全基础要点知识介绍(非常详细),零基础入门到精通,看这一篇就够了
运维·前端·网络协议·web安全·网络安全·职场和发展
AndyHeee1 小时前
Linux 内核底层机制:设备树(Device Tree)的数据结构与内存组织
linux·前端·数据结构
wuqingshun3141591 小时前
springBoot是如何通过main方法启动web项目的?
前端·spring boot·后端
xxwl5851 小时前
HTML 小总结:从骨架到枝叶,系统掌握网页结构
前端·html