javascriptjqueryofflineoffline-cachingoffline-browsing

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();

Solution

  • You could use localStorage.length to get the count of elements in the storage. 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. 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.

    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?

    PS: I tried to get the size by iterating over the localStorage keys, and adding the size, but the browser tab crashed. So I'd say relying on the QUOTA_EXCEEDED_ERR is better.

    UPDATE

    You could also get a rough estimate of size using 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.