Posted By

EvanHahn on 03/12/12


Tagged

local storage html5 localstorage


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

slashyy77
dop3
Priestd09


JavaScript local storage


 / Published in: JavaScript
 

Here's how to use this:

  • To access something in the local storage, type Evan.local('name'). You may need to use JSON.parse() on this result. Returns null if nothing's there.
  • To assign something in the local storage, type Evan.local('name', value).
  • To remove something from the local storage, type Evan.local('name', null).

This may not work if private browsing is enabled (eg, on Safari for iOS).

  1. // Accessor: local('key')
  2. // Setter: local('key', value)
  3. // Destroyer: local('key', null)
  4. Evan.local = function(key, value) {
  5.  
  6. // Getter
  7. if (arguments.length === 1)
  8. return localStorage.getItem(key);
  9.  
  10. // Clear it no matter what (for iOS)
  11. localStorage.removeItem(key);
  12.  
  13. // Setter
  14. if (value !== null) {
  15. if ((typeof value !== 'string') && (!(value instanceof String)))
  16. value = JSON.stringify(value);
  17. localStorage.setItem(key, value);
  18. }
  19.  
  20. };

Report this snippet  

You need to login to post a comment.