我在尝试找到自己的解决方案时发现了这个问题,并想分享我最终的结果,以防万一它可能对其他人有帮助。
简而言之,当我向 localStorage 添加一个值时,我将它的键放入一个数组中。然后,在向 localStorage 写入其他内容之前,我会遍历这些键并获取它们的长度之和,以确保我没有超过我认为合适的阈值。
如果 localStorage 大于 2Mb(在这种情况下),则从 localStorage 中删除第一项,从数组中删除该条目,然后写入新条目。
// check the size of localStorage
var localStorageArray = [];
var localStorageSize = 0;
for ( var i=0; i < localStorageArray.length; i++ ) {
localStorageSize += localStorage.getItem(localStorageArray[i]).length;
}
// save to localStorage if it has not been saved already
if ( !localStorage.getItem(key) ){
if ( localStorageSize < 2000000 ) {
localStorage.setItem(key, value);
localStorageArray.push(key);
} else {
localStorage.removeItem(localStorageArray[0]);
localStorageArray.shift();
localStorage.setItem(key, value);
localStorageArray.push(key);
}
}