Skip to content

Instantly share code, notes, and snippets.

@danott
Created April 26, 2011 15:51
Show Gist options
  • Save danott/942522 to your computer and use it in GitHub Desktop.
Save danott/942522 to your computer and use it in GitHub Desktop.
Override localStorage and sessionStorage's getter and setter function to allow for objects/arrays to be stored as well.
/* json_storage.js
* @danott
* 26 APR 2011
*
* Building on a thread from Stack Overflow, override localStorage and sessionStorage's
* getter and setter functions to allow for storing objects and arrays.
*
* Original thread:
* http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage
*/
Storage.prototype._setItem = Storage.prototype.setItem;
Storage.prototype.setItem = function(key, value)
{
this._setItem(key, JSON.stringify(value));
}
Storage.prototype._getItem = Storage.prototype.getItem;
Storage.prototype.getItem = function(key)
{
try
{
return JSON.parse(this._getItem(key));
}
catch(e)
{
return this._getItem(key);
}
}
@nddipiazza
Copy link

does not work on localStorage.someVar = 'someVal' format

@dudewad
Copy link

dudewad commented Sep 29, 2020

It shouldn't, it's overriding a method not an accessor.

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