1

How am I able to store the original password to my local storage?

I have two inputs username and password:

<input id="myInput" type="text" name="myInput" placeholder="Input">
<input id="myPW" type="password" name="myPassword" placeholder="Password">

What I want to do in my javascript is to store my username, password converted to Base64, and the original data of password. But it only store the username and Base64 password. The original password won't stored. How am I able to fix it?

  • `for...in...` is for objects not arrays: [Why is using “for…in” with array iteration a bad idea?](https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea) – Andreas Feb 28 '19 at 07:14

2 Answers2

2

Because you set inpw.value to empty string before using it to push the original password.

  userArray.push(inp.value);
  localStorage.setItem('user', JSON.stringify(userArray));
  inp.value = "";

  passArray.push(window.btoa(inpw.value));
  localStorage.setItem('pass', JSON.stringify(passArray));
  inpw.value = ""; // This makes next inpw.value equals ""

  origPassArray.push(inpw.value); // So this will push an empty string to the array
  localStorage.setItem('orig', JSON.stringify(origPassArray));
  inpw.value = "";
holydragon
  • 6,158
  • 6
  • 39
  • 62
1

You inpw is emty after line inpw.value = ""; In addition, don't repeat your self. I do some refactor. You should write functions to get the credential to localstore like

const storedValue = ['user', 'pass', 'origin']

const credential = getCredentialFromStore(storedValue)

const getCredentialFromStore = (storedValue) => {
  const result = []
  storedValue.forEach(item => {
    result[item] = localStorage.getItem(item) ? JSON.parse(localStorage.getItem(item)) : [];
  })
  return result
}

And also write some function to set the credential to localstore like

const addToCredential = (credential, key, value) => {
  credential[key].push(value);
  localStorage.setItem(key, JSON.stringify(credential[key]));
  return credential
}

Using :

addToCredential(credential, 'user', inp.value)
addToCredential(credential, 'pass', window.btoa(inpw.value))
addToCredential(credential, 'orig', inpw.value)
Vu Luu
  • 792
  • 5
  • 16