Skip to content

Instantly share code, notes, and snippets.

@lukaszhanusik
Forked from vishnu-prasad-r/localstorage.js
Created September 23, 2021 00:53
Show Gist options
  • Save lukaszhanusik/4cdb9f598dbae3a35bec4aa4f6846d3d to your computer and use it in GitHub Desktop.
Save lukaszhanusik/4cdb9f598dbae3a35bec4aa4f6846d3d 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment