使用storage事件实现前端单点登录

解决问题:

同一浏览器,同一地址,登录不同账户A和B,先登录A,再登录B,在账号A的页面弹出登出提示。

实现方案

window下监听storage事件,进行提示或登出处理

代码



<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="">
head>
<body>
    
    <button type="button" onclick="login(0)">登录账号Abutton>
    
    <button type="button" onclick="login(1)">登录账号Bbutton>
    <script src="login.js">script>
body>
html>


<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>child pagetitle>
    <link rel="stylesheet" href="">
head>
<body>
    <h1>child pageh1>
    <script src="login.js">script>
body>
html>

index.html中的两个按钮只是简单模拟登录,即根据点击在cookie中写入不同的token,child.html是为了使应用不再同一页面下,在单页应用中,此方法也适用

const TOKEN_KEY = 'access_token';
const TOKENS_LIST = ['LSDJFOUNLDK2=SDF=21DFS', 'SFWIQFNLKA=SDFSF2KJ23LKJ'];//两个模拟token

(function() {
    window.addEventListener('storage', _storageEventHandler);//添加监听器
})();

/**
 * 监听localStorage中的token字段改变,提示用户退出提示
 * @param  {Object} event localStorage变更事件对象
 */
function _storageEventHandler(event) {
    console.info('localStorage.access_token的值:' + localStorage.access_token)
    if (TOKEN_KEY === event.key) {
        if (__isUsable(event.newValue) && __isUsable(event.oldValue) && event.newValue !== event.oldValue) {
        //TODO 登出处理逻辑
            console.info('old token:' + event.oldValue)
            console.info('new token:' + event.newValue)
            console.log('log out');
        }
    }

    /**
     * 判断值是否存在
     */
    function __isUsable(value) {
        return value && value !== "undefined";
    }
}

/**
 * 模拟登陆
 * @param  {Number} account 0为登录A账号,1为登录B
 */
function login(account) {
    console.info('账号' + (account + 1) + '已登录')
    _simulateLogin(TOKENS_LIST[account]);
    localStorage.access_token = document.cookie.substr(13);
}

/**
 * 模拟登陆,将token写入cookie
 * @param  {[type]} token [description]
 * @return {[type]}       [description]
 */
function _simulateLogin(token) {
    document.cookie = "access_token=" + token;
}

如代码文件中的注释缩写,代码相对简单,只是一种思路。

欢迎随时沟通

相关引用
MDN storage

你可能感兴趣的:(前端,前端)