Check the size of LocalStorage In JavaScript With a Few Lines Of Code
LocalStorage is good for storing temporary settings on a site without any setup. But it is limited to a small amount. For example, Chrome has a limit of 10mb for LocalStorage and SessionStorage combined. So it is important to verify a website or other form of client side JS application does not use too much of it. LocalStorage is string based, so it is easy to check the current amount used:
function displayLocalStorageMemory() { let total = 0; for (let location in localStorage) { // Count the value as well as the key length. x2 because JavaScript characters // are UTF-16 meaning they occupy 8 bytes. let lineLength = ((localStorage[location].length + location.length) * 2); // Do not count properties that do not give strings like setItem() if (isNaN(lineLength)) { lineLength = 0; } total += lineLength; // Keys can have huge lengths, so limit them for display purposes console.log(`${location.substr(0,50)} = ${(lineLength / 1024).toFixed(2)} KB`); }; console.log("Total = " + (total / 1024).toFixed(2) + " KB"); } displayLocalStorageMemory();
This was adapted from from this Stack Overflow answer: https://stackoverflow.com/a/15720835
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2018/checkLocalStorageMemory.js











