Local Storage Library


SUBMITTED BY: djwisnia55

DATE: Sept. 29, 2016, 6:46 p.m.

FORMAT: JavaScript

SIZE: 1.5 kB

HITS: 724

  1. LocalStorage = new (function() {
  2. var _supported = "localStorage" in window;
  3. var _counter = {};
  4. this.set = function(key, value, persistent) {
  5. if(_supported) {
  6. try {
  7. if(typeof(value) == 'object') {
  8. value = JSON.stringify(value);
  9. }
  10. if(persistent) {
  11. key = '@' + key;
  12. }
  13. if(_counter.lastKey != key) {
  14. _counter.lastKey = key;
  15. _counter.count = 1;
  16. }
  17. window.localStorage.setItem(key, value);
  18. }
  19. catch(e) {
  20. console.error('LocalStorage', e);
  21. if(e.name == 'NS_ERROR_DOM_QUOTA_REACHED') {
  22. Object.keys(window.localStorage).forEach(function(key) {
  23. if(key[0] != '@') {
  24. this.remove(key);
  25. }
  26. }.bind(this));
  27. if(_counter.count < 3) {
  28. this.set(key, value);
  29. }
  30. }
  31. }
  32. _counter.count = 1;
  33. }
  34. return this;
  35. };
  36. var _get = function(key) {
  37. var value = window.localStorage.getItem(key);
  38. try {
  39. value = JSON.parse(value);
  40. }
  41. catch(e) {}
  42. return value;
  43. };
  44. this.get = function(key) {
  45. if(_supported) {
  46. if(window.localStorage.hasOwnProperty('@' + key)) {
  47. return _get('@' + key);
  48. }
  49. else {
  50. return _get(key);
  51. }
  52. }
  53. return null;
  54. };
  55. this.remove = function(key, force) {
  56. if(_supported) {
  57. window.localStorage.removeItem(key);
  58. if(force) {
  59. window.localStorage.removeItem('@' + key);
  60. }
  61. }
  62. return this;
  63. };
  64. this.clear = function() {
  65. if(_supported) {
  66. window.localStorage.clear();
  67. }
  68. return this;
  69. };
  70. });

comments powered by Disqus