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; }; 
3
  • 1
    possible duplicate of How to find the size of localStorage Commented Feb 9, 2014 at 19:50
  • 1
    You can look at arty.name/localstorage.html Commented Feb 9, 2014 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! Commented Feb 9, 2014 at 20:11

1 Answer 1

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 } 
Sign up to request clarification or add additional context in comments.

2 Comments

@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.
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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.