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

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

为了安全,项目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()
            }
        }
    }
}
相关推荐
Jeremy_Lee1232 分钟前
grafana 批量视图备份及恢复(含数据源)
前端·网络·grafana
import_random8 分钟前
[python]conda
前端
亲亲小宝宝鸭9 分钟前
写了两个小需求,终于搞清楚了表格合并
前端·vue.js
BUG收容所所长11 分钟前
栈的奇妙世界:从冰棒到算法的华丽转身
前端·javascript·算法
xingba19 分钟前
重写IE的showModalDialog模态框以兼容现代浏览器
前端·javascript·google
前端小巷子20 分钟前
Promise 静态方法:轻松处理多个异步任务
前端·面试·promise
梨子同志25 分钟前
JavaScript Set 和 Map 数据结构
前端·javascript
初辰ge29 分钟前
做个大屏既要不留白又要不变形还要没滚动条,我直接怒斥领导,大屏适配就这四种模式
前端·javascript
Face32 分钟前
路由Vue-router 及 异步组件
前端·javascript·vue.js
Nano33 分钟前
Axios 进阶指南:掌握请求取消与进度监控的艺术
前端