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

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

为了安全,项目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()
            }
        }
    }
}
相关推荐
inxunoffice16 分钟前
批量在多个 PDF 的指定位置插入页,如插入封面、插入尾页
前端·pdf
木木黄木木21 分钟前
HTML5 Canvas绘画板项目实战:打造一个功能丰富的在线画板
前端·html·html5
豆芽81923 分钟前
基于Web的交互式智能成绩管理系统设计
前端·python·信息可视化·数据分析·交互·web·数据可视化
不是鱼23 分钟前
XSS 和 CSRF 为什么值得你的关注?
前端·javascript
顺遂时光26 分钟前
微信小程序——解构赋值与普通赋值
前端·javascript·vue.js
anyeyongzhou28 分钟前
img标签请求浏览器资源携带请求头
前端·vue.js
Captaincc37 分钟前
腾讯云 EdgeOne Pages「MCP Server」正式发布
前端·腾讯·mcp
最新资讯动态1 小时前
想让鸿蒙应用快的“飞起”,来HarmonyOS开发者官网“最佳实践-性能专区”
前端
雾岛LYC听风1 小时前
3. 轴指令(omron 机器自动化控制器)——>MC_GearInPos
前端·数据库·自动化
weixin_443566981 小时前
39-Ajax工作原理
前端·ajax