场景
假设打开了3个标签页,在其中一个标签页点击退出登录时,3个标签页均需要退出
实现(BroadcastChannel)
现有退出登录函数doLogout
则在其执行时,引入BroadcastChannel,代码如下:
// 退出登录
const doLogout = () => {
removeCookie(TOKEN)
localStorage.clear()
sessionStorage.clear()
const logOut = new BroadcastChannel('channel_1')
logOut.postMessage('logOut')
location.replace('/login')
}
此时,退出登录时,便会向其他页签发出广播,因此,还需要添加一个监听的动作,代码如下:
// 监听退出登录
const logChannel = new BroadcastChannel('channel_1')
logChannel.onmessage = (e) => {
if (e.data === 'logOut') {
location.replace('/login')
}
}
至此便已完成该功能。