记一次特殊的登录流程

需求:

1.浏览器可以多窗口共享token,无需登录

2.浏览器关闭后,需要重新登录

3.登录后返回上一个页面

解决:

1.多窗口共享token,第一个想到就是localStorage

直接存在客户端,需要就调用

2.浏览器关闭后,需要重新登录

就是需要手动把localStorage清除,但是无法判断是什么时候关闭浏览器的

想到sessionStorage,但是无法多窗口共享,去判断;

新开窗口,sessionStorage就消失了

最后决定用cookie,因为cookie默认的生命周期是,浏览器关闭就清除了

生成cookie

//设置cookie  
function setCookie(name, value, seconds) {
    seconds = seconds || 0; //seconds有值就直接赋值,没有为0    
    var expires = "";
    console.log(seconds);
    if (seconds != 0) { //设置cookie生存时间    
        console.log(seconds);
        var date = new Date();
        date.setTime(date.getTime() + (seconds * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    console.log(name + "=" + escape(value) + expires + "; path=/");
    document.cookie = name + "=" + escape(value) + expires + "; path=/"; //转码并赋值    
}

判断cookie,清除localStorage

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';'); //把cookie分割成组   
    // console.log(ca);
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i]; //取得字符串    
        // console.log(c);
        while (c.charAt(0) == ' ') { //判断一下字符串有没有前导空格    
            c = c.substring(1, c.length); //有的话,从第二位开始取    
        }
        if (c.indexOf(nameEQ) == 0) { //如果含有我们要的name    
            return unescape(c.substring(nameEQ.length, c.length)); //解码并截取我们要值    
        }
    }
    return false;
}

3.回到上一页,通过document.referrer判断

无上一页,去index;

上一页是login,去index;

其他去上一页

  if (document.referrer === '') {
                                window.location.href = "index.html";
                            } else {
                                var str = document.referrer;
                                var arr = str.split("/");
                                if (arr[3] == "login.html") {
                                    window.location.href = "index.html";
                                } else {
                                    window.location.href = document.referrer;
                                }
                            }

问题:

目前仍存在一个问题:

就是关闭所有页面,浏览器尚未关闭

cookie仍在,输入网址,没有去登录,token还在

猜你喜欢

转载自www.cnblogs.com/ssszjh/p/13372880.html