Skip to content

Instantly share code, notes, and snippets.

@emanb29
Forked from danott/json_storage.js
Last active September 1, 2020 23:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save emanb29/59bfb10ef6b9bc3d89db to your computer and use it in GitHub Desktop.
Save emanb29/59bfb10ef6b9bc3d89db to your computer and use it in GitHub Desktop.
Getters and setters for localStorage allowing it to transparently store objects using es6's Proxy
/* 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
*
* Modified by emanb29 to include actual getters and setters
*/
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);
}
}
localStorage = new Proxy(localStorage, {
get: function(target, name) {
return localStorage.getItem(name);
},
set: function(target, name, val) {
localStorage.setItem(name, val);
}
})
@khasky
Copy link

khasky commented Sep 1, 2020

Read-only global 'localStorage' should not be modified.

@emanb29
Copy link
Author

emanb29 commented Sep 1, 2020

Oh, this is 100% a hack.

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