I have been searching about this many hours still nothing solved my problem:can't check if a key does exist in the localStorage
.
In my chat application,Once the user opens a new tab, I want to check if there is registered user already,I do that using localStorage variable in the following way:
window.addEventListener('load', function () {
var s=localStorage.getItem("localStor");
if (s === null){
console.log("is null"); //does not enter here
}else{
console.log(s); // prints [object *O*bject]
console.log(JSON.parse(s).name); //getting an error (see below)
}
}, false);
When parsing I get the error:
Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (
<anonymous>
)
The first place I set localStor
item in the localStorage
is only after registering and it is inside a function that is called only when clicking on a button HTML
element.But logically it should not enter in the else
from the first place.
Any idea why this isn't working? any help is appreciated.