How to fill JavaScript localStorage to its max capacity quickly?

Home / javascript / How to fill JavaScript localStorage to its max capacity quickly?

Question:
I have an application that uses localStorage frequently. Sometimes I reach localStorage max capacity and I catch the exception and clean some old data.
try {
localStorage.setItem(myKey, myData);
}catch(error){
// empty some old data in localStorage and re-insert myKey and myData
}

Everything is fine except that I cannot test it easily. I am looking for a way to fill my localStorage to its max capacity quickly so I can test the code in different conditions and browsers.


Answer:
Most browser have 5mb – 10mb localStorage, for example, chrome has 5mb. Use a for loop to test the limits of your localStorage, and catch once it is exceeding the limit.

Then output the result.

Try this one:

https://jsfiddle.net/dalinhuang/6aeb3fcr/
if (localStorage && !localStorage.getItem(‘size’)) {
var i = 0;
try {
// Test up to 10 MB
for (i = 250; i <= 10000; i += 250) { localStorage.setItem('test', new Array((i * 1024) + 1).join('a')); } } catch (e) { localStorage.removeItem('test'); localStorage.setItem('size', i - 250); } } console.log('max localStorage size: ' + localStorage.getItem('size') + 'kb'); REF: Read more

Leave a Reply

Your email address will not be published. Required fields are marked *