Sideshow
Sideshow

Reputation: 1351

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.

Upvotes: 0

Views: 2369

Answers (3)

Cat Chen
Cat Chen

Reputation: 2415

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'; }

Upvotes: 1

Sideshow
Sideshow

Reputation: 1351

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

Upvotes: 0

Grevling
Grevling

Reputation: 466

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';
}

Upvotes: 0

Related Questions