localStorageTest
在localStorage中存儲遞增值,直到達到瀏覽器的localStorage大小限制。localStorage導致瀏覽器崩潰
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");
}
鉻:
localStorageTest("1", 80000);
<browser crashed>
火狐:
localStorageTest("1", 50000);
<browser crashed>
懷疑瀏覽器內存的使用量增加,我寫了localStorageIncrementalTest
它做同樣的事情爲localStorageTest
,但提出的5空閒週期在其操作之間的秒數,使用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);
}
}
鉻:
localStorageIncrementalTest("1", 30000);
stored 30000 bytes
stored 35000 bytes
...
stored 1800000 bytes
<browser crashed>
火狐:
localStorageIncrementalTest("1", 30000);
stored 30000 bytes
stored 35000 bytes
...
stored 60000 bytes
<browser crashed>
所以localStorageIncrementalTest
使我們能夠比localStorageTest
在更多的localStorage存儲崩潰的瀏覽器。
任何人都可以解釋瀏覽器崩潰背後的原因,並避免相同的可能的解決方案?
我使用Chrome 28.0.1500.71,和Firefox 26.0
更新:
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));
}
}
鉻:
localStorageTest2();
<browser crashed>
火狐:
localStorageTest2();
<browser crashed>
測試localStorage2
也導致瀏覽器崩潰。