3

I was trying not to use database but the browser local-storage for a login example. I mean when user give 'username' and 'password' it will check from browser local-storage and then be able to login. I am using localStorage.setItem and localStorage.getItem of HTML5 to get the data and show it. Here is my Code-

var user_name=document.getElementById('userName').value;
var user_pswd=document.getElementById('password').value;                  
localStorage.setItem("user", user_name);
localStorage.setItem("pass", user_pswd);                    
// Retrieve                    
document.getElementById("output").innerHTML = localStorage.getItem("user");

It set the data and shows the user name,But is it possible to get the data after restarting the browser?? When I try to login for first time, how can I check with the browser data? Please any help is highly appreciated..

Arashsoft
  • 2,749
  • 5
  • 35
  • 58
Subho
  • 921
  • 5
  • 25
  • 48

1 Answers1

3

restarting browser does not delete local storage data.

you can check if you have data for both keys (userName , password) with following condition

if ((localStorage.getItem("userName") !== null) && (localStorage.getItem("password") !== null))
{
    // you have values for both userName and password
}

for your case you can test if textbox values match the values in local storage

if ((localStorage.getItem("userName") === null) && (localStorage.getItem("password") === null))
{
    localStorage.setItem("user", "Subho"); // writes name and password to local storage if not exists
    localStorage.setItem("pass", "Subho"); 
}

if ( (localStorage.getItem("user") == document.getElementById('userName').value)
{
    if ( (localStorage.getItem("pass") == document.getElementById('password').value)
    {
        // login is successful
    }           
}

however this is not a safe login method , local storage data is accesible by users

Alper Cinar
  • 861
  • 5
  • 12
  • Thank u for ur ans, but can u explain some more.. Let username and paswrd both are 'Subho'. while login how will I check the the value of localStorage with the value of the textbox?? – Subho Oct 30 '14 at 06:18
  • i have updated the answer , but i have to remind you that , this is not a recomended way for user login – Alper Cinar Oct 30 '14 at 06:32
  • is there any other way?? like session or anything?? – Subho Oct 30 '14 at 06:57
  • Same question for me. How to store data using cache or using session? because local storage data is every-time displays on browser's console. – Maulik Nov 13 '17 at 04:44