Skip to content

Instantly share code, notes, and snippets.

@olafdietsche
Last active November 24, 2020 03:36
Show Gist options
  • Save olafdietsche/8905764 to your computer and use it in GitHub Desktop.
Save olafdietsche/8905764 to your computer and use it in GitHub Desktop.
Javascript: get localStorage maximum size
if (!localStorage) {
console.log('unavailable');
} else {
var max = 'x', s;
var lower_bound = 1, upper_bound = 1, middle;
// determine lower and upper bound
try {
while (true) {
localStorage.setItem('test', max);
lower_bound = upper_bound;
upper_bound *= 2;
max = max + max;
}
} catch (e) {
}
// do a binary search
while (upper_bound - lower_bound > 2) {
try {
middle = (lower_bound + upper_bound) / 2;
s = max.substr(0, middle);
localStorage.setItem('test', s);
lower_bound = middle;
} catch (e) {
upper_bound = middle;
}
}
console.log('size=' + lower_bound + '/' + upper_bound + '=' + (lower_bound / 1024).toFixed(1) + 'k');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment