LocalStorage Crashes Browser

localStorageTest stores the incremental value in localStorage until it reaches the browser local storage size limits.

function localStorageTest(key, len) {
   var value = window.localStorage.getItem(key); 
   value = (value == null)?"":value;
   var numIters = len - value.length;
   while(numIters--) {
       value += "1";
       window.localStorage.setItem(key, value);
       if (window.localStorage.getItem(key) != value) {
           console.log("limit reached at " + (value.length-1).toString() + " bytes");
           break;
       }
   }
   console.log("stored " + value.length + " bytes");
}

Chrome:

localStorageTest("1", 80000);
<browser crashed>

Firefox:

localStorageTest("1", 50000);
<browser crashed>

Suspecting an increase in browser memory usage, I wrote localStorageIncrementalTestthat does the same thing as localStorageTestbut sets up periods of inactivity of 5 seconds between its operations using a call setTimeOut.

var increment = 5000;

function localStorageIncrementalTest(key, len) {
   var value = window.localStorage.getItem(key); 
   value = (value == null)?"":value;
   var numIters = len - value.length;
   var limitReached = false;
   while(numIters--) {
       value += "1";
       window.localStorage.setItem(key, value);
       if (window.localStorage.getItem(key) != value) {
           console.log("limit reached at " + (value.length-1).toString() + " bytes");
           limitReached = true;
           break;
       }
   }
   console.log("stored " + value.length + " bytes");
   if (!limitReached) {
       setTimeout(function() {
           localStorageIncrementalTest(key, len+increment);
       }, 5000);    
   }
}

Chrome:

localStorageIncrementalTest("1", 30000);
stored 30000 bytes
stored 35000 bytes
...
stored 1800000 bytes
<browser crashed>

Firefox:

localStorageIncrementalTest("1", 30000);
stored 30000 bytes
stored 35000 bytes
...
stored 60000 bytes
<browser crashed>

So localStorageIncrementalTestlets us store more in localStorage than localStorageTestbefore the browser crashes.

Can someone explain the reasons for the browser crash and a possible solution to avoid the same?

I am using Chrome 28.0.1500.71 and Firefox 26.0

Update :

function getRandomValue(size) {
    var value = "";
    for (var i = 0; i < size; i++) {
            value += Math.ceil(Math.random()*5);
    }
    return value;
}

function localStorageTest2() {
    for (var i = 0; i < 70000; i++) {
        window.localStorage.setItem("1", getRandomValue(20000));
    }
}

Chrome:

localStorageTest2();
<browser crashed>

Firefox:

localStorageTest2();
<browser crashed>

Testing localStorage2also caused a browser crash.

+4
1

, , crbug.com bugzilla.mozilla.com.

localStorage . API, , , .

, - setItem(x, y) , . localStorage.setItem(x, y); if (y == localStorage.getItem(x)) { ... } if, , .

, IndexedDB.

Chrome API- FileSystem API -SQL, , .

0

Source: https://habr.com/ru/post/1526370/


All Articles