Skip to content

Instantly share code, notes, and snippets.

@vishnu-prasad-r
Created January 28, 2014 01:58
Show Gist options
  • Save vishnu-prasad-r/8661137 to your computer and use it in GitHub Desktop.
Save vishnu-prasad-r/8661137 to your computer and use it in GitHub Desktop.
Javascript snippet to use HTML5 localStorage easily. Supports storing any kind of data. Handles commonly occuring exceptions like localStorage quota being exceeded and browser not supporting localStorage. .
/*Javascript snippet to use HTML5 localStorage easily.
Properly handles situation like 'localStorage not being supported by the browser' and excedding localSorage quota.
Supports storing any kind of data */
/*key should be String, value can be any Javascript object */
function writeToLocalStorage(key,value)
{
if(typeof(Storage) == 'undefined')
{
alert("Your browser doesn't support HTML5 LocalStorage which this site make use of. Some features may not be available. Consider upgrading your browser to the latest version");
return false;
}
value = JSON.stringify(value); //serializing non-string data types to string
try
{
window.localStorage.setItem(key, value);
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR) {
alert('Local storage Quota exceeded! .Clearing localStorage');
localStorage.clear();
window.localStorage.setItem(key, value); //Try saving the preference again
}
}
return true;
}
function readFromLocalStorage(key)
{
if(typeof(Storage) == 'undefined')
{
//Broswer doesnt support local storage
return null;
}
value = JSON.parse(localStorage.getItem(key));
return value;
}
@SaidTorres3
Copy link

23 line, what is QUOTA_EXCEEDED_ERR ?
44 line, var value was not declare.

23: https://developer.apple.com/documentation/webkitjs/fileerror/1632754-quota_exceeded_err?changes=_5_8&language=objc
44: 6

@verybigelephants
Copy link

verybigelephants commented Feb 14, 2023

i mean, thanks for the function, but this is indenting from hell

here's a reformatted version in case anyone wants to copy paste it:

function writeToLocalStorage(key,value){
	if(typeof(Storage) == 'undefined'){
		alert("Your browser doesn't support HTML5 LocalStorage which this site make use of. Some features may not be available. Consider upgrading your browser to the latest version");
		return false;
	}

	value = JSON.stringify(value); //serializing non-string data types to string

	try{
		window.localStorage.setItem(key, value);
	}catch(e){
		if (e == QUOTA_EXCEEDED_ERR){
			alert('Local storage Quota exceeded! .Clearing localStorage');
			localStorage.clear();
			window.localStorage.setItem(key, value); //Try saving the preference again
		}
	}

	return true;
}

function readFromLocalStorage(key){
	if(typeof(Storage) == 'undefined'){
		//Broswer doesnt support local storage
		return null;
	}

	value = JSON.parse(localStorage.getItem(key));
	return value;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment