How to get the total html5 storage size used by the current application

I need to find the total size obtained by the application using HTML5 sessionStorage/ localStorageat runtime.

I don't need profiler based approaches.

What I'm doing right now is

var data = 0;
for(var v in window.sessionStorage){
 data += window.sessionStorage.getItem(v); 
}

console.log(data);//.length to get char length

And then I copy this value to a text file and check the size.

Ugly and still not helping me. Is there a way (any method) in the HTML5 API that has a built-in?

Thank.

+5
source share
2 answers

No, not a cross browser . In view of IE have it , others - no. But, of course, the remaining size of the domain remaining on the domain can be calculated. The following are examples.

For IE only:

var remSpace = window.localStorage.remainingSpace;

For FF / Chrome / Safari:

 var limit = 1024 * 1024 * 5; // 5 MB
 var remSpace = limit - unescape(encodeURIComponent(JSON.stringify(localStorage))).length;

Opera: 5 , , .

+11

, , , , .

, , 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);
    }
}
0

All Articles