如何找到localStorage的大小 [英] How to find the size of localStorage
问题描述
我目前正在开发一个将使用HTML5的localStorage的网站。我已经阅读了所有关于不同浏览器的大小限制。但是,我还没有看到如何找出localStorage实例的当前大小。 这个问题似乎表明JavaScript没有内置的显示给定大小的方式变量。 localStorage是否有我没见过的内存大小属性?有没有简单的方法来做到这一点,我错过了?
我的网站是为了让用户在'离线'模式下输入信息,所以能够当存储器已满时给他们一个警告是非常重要的。
在Chrome控制台执行此代码段
var _lsTotal = 0,_xLen,_x; for(_x in localStorage){_ xLen =((localStorage [_x] .length + _x.length)* 2); _ lsTotal + = _ xLen; console.log(_x.substr(0,50)+=+(_xLen / 1024).toFixed(2)+KB)}; console.log(Total =+(_lsTotal / 1024).toFixed (2)+KB);
或将此文本添加到书签的位置字段中以便使用
javascript:var x,xLen,log = [],total = 0; for(x in localStorage){xLen =((localStorage [x] .length * 2 + x.length * 2)/ 1024); log.push(x.substr(0,30)+=+ xLen.toFixed(2)+KB);总+ = xLen}; if(total> 1024){log.unshift(Total =+(total / 1024).toFixed(2)+MB);} else {log.unshift(Total =+ total.toFixed(2 )+KB);};警报(log.join( \\\
));
P.S。片段根据评论中的请求进行更新。现在计算包括密钥本身的长度。
每个长度乘以2,因为javascript中的char存储为UTF-16(占用2个字节)
I am currently developing a site that will make use of HTML5's localStorage. I've read all about the size limitations for different browsers. However, I haven't seen anything on how to find out the current size of a localStorage instance. This question seems to indicate that JavaScript doesn't have a built in way of showing the size for a given variable. Does localStorage have a memory size property that I haven't seen? Is there an easy way to do this that I'm missing?
My site is meant to allow users to enter information in an 'offline' mode, so being able to give them a warning when the storage is almost full is very important.
Execute this snippet in Chrome console
var _lsTotal=0,_xLen,_x;for(_x in localStorage){_xLen= ((localStorage[_x].length + _x.length)* 2);_lsTotal+=_xLen; console.log(_x.substr(0,50)+" = "+ (_xLen/1024).toFixed(2)+" KB")};console.log("Total = " + (_lsTotal / 1024).toFixed(2) + " KB");
or add this text in the field 'location' of a bookmark for convenient usage
javascript: var x, xLen, log=[],total=0;for (x in localStorage){xLen = ((localStorage[x].length * 2 + x.length * 2)/1024); log.push(x.substr(0,30) + " = " + xLen.toFixed(2) + " KB"); total+= xLen}; if (total > 1024){log.unshift("Total = " + (total/1024).toFixed(2)+ " MB");}else{log.unshift("Total = " + total.toFixed(2)+ " KB");}; alert(log.join("\n"));
P.S. Snippets are updated according to request in the comment. Now the calculation includes the length of the key itself. Each length is multiplied by 2 because the char in javascript stores as UTF-16 (occupies 2 bytes)
这篇关于如何找到localStorage的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!