JavaScript local storage


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

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).


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.