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

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

为了安全,项目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()
            }
        }
    }
}
相关推荐
deli0072 小时前
手机20%突然关机?电量百分比是估的,SOC曲线4组实测
前端
深蓝AI12 小时前
Meta 开源用了八年的设计系统 astryx:连坐两天 GitHub 总榜第一,组件库开始写给 agent 的说明书
前端·人工智能
IT_陈寒13 小时前
Vue的watch把我坑惨了,原来要这样用才靠谱
前端·人工智能·后端
1-1=013 小时前
Vue 3 模板语
前端·javascript·vue.js
用户76103044737113 小时前
【转战智能眼镜开发】ROKID AIUI 小游戏 亚马逊标枪项目实战讲解
前端
风卿13 小时前
看着AI写代码太孤独了,来欣赏星云吧:一个DSH 装饰插件
前端·javascript
牧艺13 小时前
弹层不用再手算坐标了:CSS Anchor Positioning 从原理到可上线
前端·javascript·css
用户老李13 小时前
YOLO 目标检测自学教程 07:YOLOv3——多尺度预测
前端
moshuying14 小时前
ESP32 墨水屏金价牌(上):从点亮到把图片推过去
前端
李剑一14 小时前
别再抬杠,前端岗已经没了!无论前后端,我们最终都要成“全干”工程师
前端·面试