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

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

为了安全,项目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()
            }
        }
    }
}
相关推荐
小徐_23334 小时前
wot-ui-cli 1.1.0 发布:支持 OpenCode、Antigravity,wot-ui 图标迁移不再靠猜
前端
__zRainy__4 小时前
Node.js Web 框架选型指南:从 Express 到 Hono 的全景对比
前端·node.js·express·koa·nestjs·egg·fastify
西瓜有点饿4 小时前
PostCSS 和 UnoCSS 的作用和区别
前端·postcss
伟大的兔神5 小时前
我做了一个本地优先的 AI 图片工作台:Loomora v1.0.0 正式发布
前端·javascript·vue.js
90后的晨仔6 小时前
uni-app项目 Vue3 状态管理 Pinia 完全指南:从概念到实战的深度解析
前端
90后的晨仔7 小时前
uni-app 在 iOS 平台跳转页面时移除底部安全区域的完整技术指南
前端
用户938515635077 小时前
React + JWT 登录鉴权底层原理与工程化实践
前端·react.js
zww89491117 小时前
家政派单系统开发实战:架构设计与派单算法指南
前端·系统架构
fangzhanpeng1687 小时前
(前端)2.js变量作用域样例
开发语言·前端·javascript
赵广陆7 小时前
企业实战:web服务集成
前端·pycharm·fastapi