2

I am learning about localStorage and it sounds like each browser gives a domain 5MB.

I wrote this code to cache the data returned from an ajax call and it works. But how do I test to see if localStorage is full? If there is no localStorage space available I imagine that the ajax request should be made again.

Here's my code:

if ( localStorage && localStorage.getItem('myGithub') ) {
  console.log('if statement');
  console.log( JSON.parse( localStorage.getItem( 'myGithub') ) );
  render( JSON.parse( localStorage.getItem( 'myGithub') ) );
}
else {
  console.log('else statment');
  $.ajax({
    url : 'https://api.github.com/users/xxxxxxxxx',
    dataType : 'json',
    success : function (data) {
        if ( localStorage ) {
            localStorage.setItem( 'myGithub', JSON.stringify(data) );    
        }
        console.log(data);
        render(data);
    }
  });
}

//Render method for printing the results to the <body> element.
//Returns html from the ajax call or from localStorage.
function render (myObjx) {
  var results = '';

  for (var prop in myObjx) {
    results += '<p>data.' + prop + ' = ' + myObjx[prop] + '</p>';  
  }

  var printData = $('body').html(results);
  return printData;
};
Mdd
  • 4,140
  • 12
  • 45
  • 70
  • 1
    possible duplicate of [How to find the size of localStorage](http://stackoverflow.com/questions/4391575/how-to-find-the-size-of-localstorage) – Ionică Bizău Feb 09 '14 at 19:50
  • 1
    You can look at http://arty.name/localstorage.html – Olaf Dietsche Feb 09 '14 at 19:54
  • @IonicăBizău I'm looking to test to prevent code from failing in case a maximum size limit has been reached. I am not looking for the current size of localStorage. But thank you for the link! – Mdd Feb 09 '14 at 20:11

1 Answers1

3

You can use the below approach. You can change it as per your requirement.

function checkAvailable(){
    var test = 'test';
    try {
        localStorage.setItem(test, test);
        localStorage.removeItem(test);
        return true;
    } catch(e) {
        return false;
    }
}

  // And you call below to check the availablity

if(checkAvailable() === true){
    // available
}else{
    // unavailable
}
A Paul
  • 8,113
  • 3
  • 31
  • 61
  • @OlafDietsche - He asked "Test if localStorage is full" in his title also in body "But how do I test to see if localStorage is full?" thats why I answered this. – A Paul Feb 09 '14 at 19:59
  • Thanks A Paul. I think this will work. I wanted a test to see if space was availalbe because I am not sure how my current code would work if there was no available space. Thanks! – Mdd Feb 09 '14 at 20:08