大家好,我的开源项目PakePlus可以将网页/Vue/React项目打包为桌面/手机应用并且小于5M只需几分钟,官网地址:pakeplus.com
当控制台报这个错误的时候,往往是因为本地存储超过5M限额了,所以就会报错,在浏览器环境中,LocalStorage和SessionStorage都是上限5M的容量,超过之后就不能再存储东西了,一般来讲不会超过,但是对于大型一点的项目,或者这里面存储图片的情况,就会出现这种错误。
如果查看使用了多少?
// 计算当前已使用的localStorage容量
function getLocalStorageUsage() {
let total = 0;
for (let key in localStorage) {
if (localStorage.hasOwnProperty(key)) {
total += (localStorage[key].length + key.length) * 2; // UTF-16编码,每个字符2字节
}
}
return total; // 返回字节数
}
// 转换为更友好的格式
function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
// 使用示例
const usage = getLocalStorageUsage();
console.log(`LocalStorage使用量: ${formatBytes(usage)}`);
可以看到,确实快超了:
查看SessionStorage容量
sessionStorage的存储容量上限也是5M,查看使用了多少:
function getSessionStorageUsage() {
let total = 0;
for (let key in sessionStorage) {
if (sessionStorage.hasOwnProperty(key)) {
total += (sessionStorage[key].length + key.length) * 2;
}
}
return total;
}
const sessionUsage = getSessionStorageUsage();
console.log(`SessionStorage使用量: ${formatBytes(sessionUsage)}`);
解决方案
当LocalStorage容量超出限制时,可以采取IndexedDB方案,因为IndexedDB的存储容量更大