bigdowg
bigdowg

Reputation: 409

Javascript not working on simple test page

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

https://stackoverflow.com/questions/30116818/how-to-use-local-storage-form-with-html-and-javascript?noredirect=1#comment48344527_30116818/

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

Answers (3)

Parkash Kumar
Parkash Kumar

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();
});

DEMO

However, if you just want to check the browser compatibility of localStorage / sessionStorage then if(typeof(Storage) !== undefined){} is quite useful.

Upvotes: 0

SharpEdge
SharpEdge

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

Dibran
Dibran

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

Related Questions