Augment Storage Prototype with getObject, setObject


/ Published in: JavaScript
Save to your folder(s)

Provides getter/setter functionality for objects in local storage. Utilizes JSON.stringify and JSON.parse.


Copy this code and paste it in your HTML
  1. if (window.Storage) {
  2.  
  3. Storage.prototype.setObject = function(key, value) {
  4. this.setItem(key, JSON.stringify(value));
  5. }
  6.  
  7. Storage.prototype.getObject = function(key) {
  8. try {
  9. return JSON.parse(this.getItem(key));
  10. }
  11. catch(e) {
  12. return null;
  13. }
  14. }
  15.  
  16. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.