简体   繁体   English

如果找不到本地存储,则重定向到登录页面

[英]Redirect to login page if localstorage not found

The aim is if the user logout or localStorage is not found it should automatically redirect to login page and it will logout all opened tabs in the same browser. 目的是如果未找到用户注销或localStorage ,则应自动重定向到登录页面,并将注销同一浏览器中所有打开的选项卡。 If the user presses logout button, it will redirect to the login page or else if the user manually clears browsing history(that time localStorage seems empty) it will automatically redirect to login page. 如果用户按下注销按钮,它将重定向到登录页面;否则,如果用户手动清除浏览历史记录(此时localStorage似乎为空),它将自动重定向到登录页面。 The following code did not work when opened with single tab and if he deletes browser history( localStorage empty). 如果使用单个选项卡打开以下代码,并且他删除了浏览器历史记录( localStorage空),则以下代码将不起作用。 Any suggesstions? 有什么建议吗?

function signOutAllTab() {
    var allTabLogOut = 'allTabLogOut';
    try {
        localStorage.setItem(allTabLogOut, allTabLogOut);
        //localStorage.removeItem(allTabLogOut);
        return true;
    } catch (e) {
        return false;
    }
}

window.addEventListener('storage', function (event) {
    if (event.key == 'logout-event') {
        window.location = 'signin?logoutAllTabs=yes';
    }
}, false);

$(document).ready(function () {
    if (signOutAllTab() && signOutTabs) {
        $('#allSignOut').on('click', function () {
            localStorage.setItem('logout-event', 'logout');
            return true;
        });
        setInterval(function () {
            if (!localStorage.getItem("allTabLogOut"))
                localStorage.setItem('logout-event', 'logout' + Math.random());
        }, 1000);
    }
}); 

Regards, 问候,

Sasi 萨西

Single tab not work is because that When a page of a homologous page modifies localstorage, the remaining homologous pages trigger the storage event as soon as they are registered. 单个选项卡不起作用是因为当同源页面的页面修改本地存储时,其余的同源页面在注册后立即触发存储事件。 It's just like one tab is watching others' change. 就像一个标签正在注视其他标签的更改一样。 If you want single tab watch itself, you could code like this: 如果您想要单选项卡手表本身,则可以这样编写代码:

 var orignalremoveItem = localStorage.removeItem;
    localStorage.removeItem = function(key,newValue){
        var removeItemEvent = new Event("removeItemEvent");
        removeItemEvent.key = key;
        window.dispatchEvent(removeItemEvent);
        orignalremoveItem.apply(this,arguments);
    };
    window.addEventListener("removeItemEvent", function (e) {
        if(localStorage.getItem("token")){
            if(e.key=='token'){
                alert("token,delete success");
            }
        }else{
            alert("no token")
        }
    });
    localStorage.removeItem('token');

step 1: 第1步: 在此处输入图片说明

step 2: 第2步: 在此处输入图片说明

step3: 第3步: 在此处输入图片说明

step4: 第四步: 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM