6

is there a way to detect if local storage has reached its maximum value to store? Or at least something like an error message that tells that i can't store anymore because i have reached the maximum size? I want to catch this so i can remove the oldest items in my local storage and insert new ones.

I am using local storage to store some of my queries from my database so users would be able to load them immediately if that specific item exist on local storage. if not then, that is the time i retrieve the data in the server.

4

1 Answer 1

8

Upon attempting to add to localstorage, if there is not enough space, this error will be thrown. In you particular scenario, you could use this event to free up some space.

try {
  localStorage.setItem("name", "Hello World!"); //saves to the database, "key", "value"
} catch (e) {
  if (e == QUOTA_EXCEEDED_ERR) {
    alert('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
  }
}

credit to - http://chrisberkhout.com/blog/localstorage-errors/

2
  • 2
    For those who don't visit the credited link it should be mentioned that this will not work correctly for all current versions of major browsers. Checking e.code === "22" || e.code === "1024" will probably be sufficient to cover those in most cases. (Tested in current versions of Chrome, Firefox(+Dev-Edition), Opera, Edge, IE.)
    – Wolfone
    Commented Aug 3, 2018 at 7:34
  • I've just checked that and all latest browsers Chrome, Safari, Firefox have the same "QuotaExceededError" expection.name Commented Jul 14, 2022 at 8:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.