Calculating usage of localStorage space

2019-01-05 08:40发布

I am creating an app using the Bespin editor and HTML5's localStorage. It stores all files locally and helps with grammar, uses JSLint and some other parsers for CSS and HTML to aid the user.

I want to calculate how much of the localStorage limit has been used and how much there actually is. Is this possible today? I was thinking for not to simply calculate the bits that are stored. But then again I'm not sure what more is there that I can't measure myself.

12条回答
【Aperson】
2楼-- · 2019-01-05 08:49

To add to the browser test results:

Firefox i=22.

Safari Version 5.0.4 on my Mac didn't hang. Error as Chrome. i=21.

Opera Tells the user that the website wants to store data but doesn't have enough space. The user can reject the request, up the limit to the amount required or to several other limits, or set it to unlimited. Go to opera:webstorage to say whether this message appears or not. i=20. Error thrown is same as Chrome.

IE9 standards mode Error as Chrome. i=22.

IE9 in IE8 standards mode Console message "Error: Not enough storage is available to complete this operation". i=22

IE9 in older modes object error. i=22.

IE8 Don't have a copy to test, but local storage is supported (http://stackoverflow.com/questions/3452816/does-ie8-support-out-of-the-box-in-localstorage)

IE7 and below Doesn't support local storage.

查看更多
淡お忘
3楼-- · 2019-01-05 08:51

IE8 implements the remainingSpace property for this purpose:

alert(window.localStorage.remainingSpace);  // should return 5000000 when empty

Unfortunately it seems that this is not available in the other browsers. However I am not sure if they implement something similar.

查看更多
做个烂人
4楼-- · 2019-01-05 08:51

You can use the below line to accurately calculate this value and here is a jsfiddle for illustration of its use

alert(1024 * 1024 * 5 - escape(encodeURIComponent(JSON.stringify(localStorage))).length);
查看更多
可以哭但决不认输i
5楼-- · 2019-01-05 08:51

Ran into this today while testing (exceeding storage quota) and whipped up a solution. IMO, knowing what the limit is and where we are in relation is far less valuable than implementing a functional way to continue storing beyond the quota.

Thus, rather than trying to do size comparisons and capacity checks, lets react when we've hit the quota, reduce our current storage by a third, and resume storing. If said reduction fails, stop storing.

set: function( param, val ) { 
    try{
        localStorage.setItem( param, typeof value == 'object' ? JSON.stringify(value) : value )
        localStorage.setItem( 'lastStore', new Date().getTime() )
    }
    catch(e){
      if( e.code === 22 ){
        // we've hit our local storage limit! lets remove 1/3rd of the entries (hopefully chronologically)
        // and try again... If we fail to remove entries, lets silently give up
        console.log('Local storage capacity reached.')

        var maxLength = localStorage.length
          , reduceBy = ~~(maxLength / 3);

        for( var i = 0; i < reduceBy; i++ ){
          if( localStorage.key(0) ){
            localStorage.removeItem( localStorage.key(0) );
          }
          else break;
        }

        if( localStorage.length < maxLength ){
          console.log('Cache data reduced to fit new entries. (' + maxLength + ' => ' + localStorage.length + ')');
          public.set( param, value );
        }
        else {
          console.log('Could not reduce cache size. Removing session cache setting from this instance.');
          public.set = function(){}
        }
      }
    }
}

This function lives within a wrapper object, so public.set simply calls itself. Now we can add to storage and not worry what the quota is or how close we are too it. If a single store is exceeding 1/3rd the quota size is where this function will stop culling and quit storing, and at that point, you shouldn't be caching anyways, right?

查看更多
三岁会撩人
6楼-- · 2019-01-05 08:54

You may be able to get an approximate idea by using the JSON methods to turn the whole localStorage object to a JSON string:

JSON.stringify(localStorage).length

I don't know how byte-accurate it would be, especially with the few bytes of added markup if you're using additional objects - but I figure it's better than thinking you're only pushing 28K and instead doing 280K (or vice-versa).

查看更多
走好不送
7楼-- · 2019-01-05 08:54

You can test your browser with this web storage support test

I tested Firefox on both my android tablet and windows laptop and Chromium just on windows results:

  1. Firefox(windows):

    • localStorage: 5120k char
    • sessionStorage: 5120k char
    • localStorage: *not supported
  2. Firefox(android):

    • localStorage: 2560k char
    • sessionStorage: Unlimited (exactly test runs up to 10240k char == 20480k byte)
    • localStorage: not supported
  3. Chromium(windows):

    • localStorage: 5120k char
    • sessionStorage: 5120k char
    • localStorage: not supported

Update

On Google Chrome Version 52.0.2743.116 m (64-bit) limits where a little bit lower on 5101k characters. This means max available may change in versions.

查看更多
登录 后发表回答