localStorage: Total, Used and Free

Seeing an interest in knowing the amount of space used and what is left in localStorage, I realized I needed this as well in one of my apps. A little research indicated there was no simple one line solution like localStorage.how_much_is_left. But I found some JavaScript code that gives a pretty good approximation. I converted this to Basic in the example below.

Notes: #DATA# can be different as long as it is not any key your app is using in localStorage. 1 byte of stored data takes 2 bytes of localStorage. The smaller the filldata the longer the code takes to run. Speed could be an issue on a slow computer. In this example it is set to 200kb (requiring 50 loops to get to a 10mb localStorage limit). So the free space can be as much as 200kb more. If I know the length of data the user just created for storing (multiplied by 2) and the freedata is not less, I’m good to go.

Recommend testing this code with Start in Desktop Browser (F5) since it fills up localStorage and must fully execute to get to the clean up line. For extra safety sake, add a localStorage.removeItem(#DATA#) to run at the start of your app.

Start a new project, add Lable1 and the following code:

Function TestLocalStorage()
  used = Math.round((JSON.stringify(localStorage).length/1024)*2) 'used = what is currently being used by ALL projects deployed to same location
  filldata = String(200000,"A") 'add 200kb to localStorage in each loop
  C = filldata
       C = C & filldata
    Catch (err)  
      total = Math.round((JSON.stringify(localStorage).length/1024)*2)
      free = total - used
      alert("Total: " & total & "kb, Used: " & used & "kb, Free: " & free & "kb") 
      Exit Do
    End Try
  localStorage.removeItem("#DATA#") 'clean up very necessary
End Function  

Function Label1_onclick()
  Call TestLocalStorage()  
End Function


Thanks, John. Would you post the JavaScript version as well?

Here’s the JavaScript version. Not tested:

function checkLocalStorage() {

  const used = Math.round((JSON.stringify(localStorage).length/1024)*2);
  // 'used' is current usage in KB

  for (var i = 0, data = "1".repeat(10000); ; i++) {
      try { // Pushes another 10000 "1" values in until localStorage maxes out
          localStorage.setItem("DATA", data);
          data = data +  "1".repeat(100000);
      } catch(e) {
          let total = Math.round((JSON.stringify(localStorage).length/1024)*2);
          // 'total' is usage after it maxed out (total capacity)
          console.log("Total: " + total + " kB");
          console.log("Used: " + used + " kB");
          console.log("FREE: " + (total-used) + " kB"); // Uses previous calculations

  // Removes item used to test localStorage after usage

End JavaScript