简体   繁体   English

如何检查已使用了多少离线存储

[英]How to Check that how much offline storage has been Used

I am using offline storage and want to clear it when storage memory is full. 我正在使用离线存储,并且想在存储空间已满时清除它。 All I want is to know that how to get used storage. 我只想知道如何使用旧存储。 I am using the following code to clear offline storage: 我正在使用以下代码清除脱机存储:

  localStorage.clear();

You could use localStorage.length to get the count of elements in the storage. 您可以使用localStorage.length来获取存储中元素的数量。 But it is unlikely that it will directly give away the size (in bytes) of how much storage is used - unless you are storing monotonic data that lets you predict the size based on the count of keys. 但是它不太可能直接放弃使用多少存储空间的大小(以字节为单位)-除非您存储单调数据,该数据可以让您根据键的数量来预测大小。

But you do get a QUOTA_EXCEEDED_ERR exception when setting values if you do exceed the available limit. 但是,如果您设置的值超出可用限制,则确实会收到QUOTA_EXCEEDED_ERR异常。 So, just wrap your code in a try..catch and if you do get error.type as QUOTA_EXCEEDED_ERR , then you could clear the space. 因此,只需将代码包装在try..catch ,如果确实收到error.type作为QUOTA_EXCEEDED_ERR ,则可以清除空间。

You could also iterate over all items in the storage to get its full size. 您还可以遍历存储中的所有项目以获取其完整大小。 But I would not do that given that it might take a bit of time as the storage increases. 但是鉴于存储量的增加可能会花费一些时间,因此我不愿意这样做。 In case you are interested, something like this would work: 如果您有兴趣,可以使用以下方法:

var size = 0;

for (var i = 0, len = localStorage.length; i < len; ++i) {
  size += localStorage.getItem(localStorage.key(i)).length;
}

console.log("Size: " + size);

Ref: What happens when localStorage is full? 参考: localStorage满时会发生什么?

PS: I tried to get the size by iterating over the localStorage keys, and adding the size, but the browser tab crashed. PS:我试图通过遍历localStorage键并添加大小来获取大小,但是浏览器选项卡崩溃了。 So I'd say relying on the QUOTA_EXCEEDED_ERR is better. 所以我想依靠QUOTA_EXCEEDED_ERR更好。

UPDATE 更新

You could also get a rough estimate of size using JSON.stringify(localStorage).length . 您还可以使用JSON.stringify(localStorage).length粗略估计大小。 Which seems faster than iterating over the keys, and doesn't crash the browser. 这似乎比遍历键更快,并且不会使浏览器崩溃。 But keep in mind that it contains additional JSON characters (such as { , } , , and " ) as browser would use them to wrap the keys and values. So the size would be slightly higher than the actual value. 但请记住,它包含额外的JSON字符(如{}," )的浏览器将使用它们来包装键和值。所以大小会比实际值略高。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM