简体   繁体   中英

HTML5 localStorage redirect based on value

I am trying to redirect the user to another page based on a value held in HTML5 localStorage.

var user=localStorage.getItem('uname');
if(user==""||user==null)
{
    window.location='secure.html';
}

This redirects even when localStorage has supposedly been cleared.

Is there any way to check what is held in localStorage . I have used alerts which show 'null' but the redirect still happens.

When localStorage is cleared, localStorage.getItem('uname') will be null . If you don't want to redirect when it's cleared, remove this condition for redirection. If you want to redirect only when it's empty string, do this:

if (localStorage.getItem('uname') === "") { window.location='secure.html'; }

Try to check if the length of the object is 0 instead

var user=localStorage.getItem('uname');
if(user.length == 0)
{
   window.location='secure.html';
}

But, if you are going to redirect the user if the "uname" is not null:

var user=localStorage.getItem('uname');
if(user.length != 0)
{
   window.location='secure.html';
}

There seems to be confusion between user==""||user==null

var user=localStorage.getItem('uname');
if(user==null)
{
    window.location='secure.html';
}

so far seems to be working

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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