Reputation: 409
I'm trying to test my local storage so I've tried a few examples. this example worked before but now its not. not sure what happened
Now I am trying this code and nothing pops up on if else, it just says local storage is
function lsTest() {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
var elem = document.getElementById('status');
if (lsTest() === true) {
elem.innerHTML += 'available.';
} else {
elem.innerHTML += 'unavailable.';
}
html
<div id="status">Local Storage is </div>
full code http://tny.cz/39896a73
Upvotes: 0
Views: 70
Reputation: 4730
There is no issue with your method, but I didn't see any call to this method. To make it functional, you need to call it with some event. Like: button / anchor onlick, window load / ready as following:
Javascript:
window.onload = function(){lsTest();}
jQuery:
jQuery(document).ready(function(){
lsTest();
});
However, if you just want to check the browser compatibility of localStorage / sessionStorage then if(typeof(Storage) !== undefined){}
is quite useful.
Upvotes: 0
Reputation: 1762
Try this, using a webserver as Nimrodx said.
window.onload = function(){
function lsTest(){
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
console.log(e);
return false;
}
}
var elem = document.getElementById('status');
if(lsTest() === true){
elem.innerHTML += 'available.';
}
else{
elem.innerHTML += 'unavailable.';
}
};
Upvotes: 0
Reputation: 1555
You should open your page using a webserver and not your local file system. The browser saves the localstorage data based on the host(domain). This prevents cross site local storage access.
Upvotes: 1