需求:最近接到一个优化,项目在登录后,如果用户想在新的标签页中直接打开项目中的链接,无需再次登录####
为了安全性,项目中使用的是sessionStorage,关闭tab后直接清空本地token
实现思路:浏览器已经成功打开A页面,在新tab中再次打开无token B页面,B页面发送事件给A,A接受到后发送给B token
trigger: BroadcastChannel = new BroadcastChannel(EBroadcastChannel.TRIGGER) // 触发
auth: BroadcastChannel = new BroadcastChannel(EBroadcastChannel.SEND_AUTH) // Auth
created() {
this.initEvent()
}
initEvent() {
this.trigger.onmessage = () => {
const token = getSession(ESessionKey.TOKEN)
if (!!token) {
this.auth.postMessage({ token })
}
}
this.auth.onmessage = (event: MessageEvent) => {
const token = getSession(ESessionKey.TOKEN)
if (!token) {
setSession(ESessionKey.TOKEN, event.data.token)
}
}
}