Calculating usage of localStorage space
Solution 1:
You may be able to get an approximate idea by using the JSON methods to turn the whole localStorage object to a JSON string:
JSON.stringify(localStorage).length
I don't know how byte-accurate it would be, especially with the few bytes of added markup if you're using additional objects - but I figure it's better than thinking you're only pushing 28K and instead doing 280K (or vice-versa).
Solution 2:
I didn't find a universal way to get the remaining limit on the browsers I needed, but I did find out that when you do reach the limit there is an error message that pops up. This is of-course different in each browser.
To max it out I used this little script:
for (var i = 0, data = "m"; i < 40; i++) {
try {
localStorage.setItem("DATA", data);
data = data + data;
} catch(e) {
var storageSize = Math.round(JSON.stringify(localStorage).length / 1024);
console.log("LIMIT REACHED: (" + i + ") " + storageSize + "K");
console.log(e);
break;
}
}
localStorage.removeItem("DATA");
From that I got this information:
Google Chrome
- DOMException:
- code: 22
- message: "Failed to execute 'setItem' on 'Storage': Setting the value of 'data' exceeded the quota."
- name: "QuotaExceededError"
Mozilla Firefox
- DOMException:
- code: 1014
- message: "Persistent storage maximum size reached"
- name: "NS_ERROR_DOM_QUOTA_REACHED"
Safari
- DOMException:
- code: 22
- message: "QuotaExceededError: DOM Exception 22"
- name: "QuotaExceededError"
Internet Explorer, Edge (community)
- DOMException:
- code: 22
- message: "QuotaExceededError"
- name: "QuotaExceededError"
My solution
So far my solution is to add an extra call each time the user would save anything. And if the exception is caught then I would tell them that they are running out of storage capacity.
Edit: Delete the added data
I forgot to mention that for this to actually work you would need to delete the DATA
item that was set originally. The change is reflected above by using the removeItem() function.