Guest User

Untitled

a guest
Jul 19th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. if (!window.localStorage || !window.sessionStorage) (function () {
  2.  
  3. var Storage = function (type) {
  4. function createCookie(name, value, days) {
  5. var date, expires;
  6.  
  7. if (days) {
  8. date = new Date();
  9. date.setTime(date.getTime()+(days*24*60*60*1000));
  10. expires = "; expires="+date.toGMTString();
  11. } else {
  12. expires = "";
  13. }
  14. document.cookie = name+"="+value+expires+"; path=/";
  15. }
  16.  
  17. function readCookie(name) {
  18. var nameEQ = name + "=",
  19. ca = document.cookie.split(';'),
  20. i, c;
  21.  
  22. for (i=0; i < ca.length; i++) {
  23. c = ca[i];
  24. while (c.charAt(0)==' ') {
  25. c = c.substring(1,c.length);
  26. }
  27.  
  28. if (c.indexOf(nameEQ) == 0) {
  29. return c.substring(nameEQ.length,c.length);
  30. }
  31. }
  32. return null;
  33. }
  34.  
  35. function setData(data) {
  36. data = JSON.stringify(data);
  37. if (type == 'session') {
  38. window.name = data;
  39. } else {
  40. createCookie('localStorage', data, 365);
  41. }
  42. }
  43.  
  44. function clearData() {
  45. if (type == 'session') {
  46. window.name = '';
  47. } else {
  48. createCookie('localStorage', '', 365);
  49. }
  50. }
  51.  
  52. function getData() {
  53. var data = type == 'session' ? window.name : readCookie('localStorage');
  54. return data ? JSON.parse(data) : {};
  55. }
  56.  
  57.  
  58. // initialise if there's already data
  59. var data = getData();
  60.  
  61. return {
  62. clear: function () {
  63. data = {};
  64. clearData();
  65. },
  66. getItem: function (key) {
  67. return data[key] === undefined ? null : data[key];
  68. },
  69. key: function (i) {
  70. // not perfect, but works
  71. var ctr = 0;
  72. for (var k in data) {
  73. if (ctr == i) return k;
  74. else ctr++;
  75. }
  76. return null;
  77. },
  78. removeItem: function (key) {
  79. delete data[key];
  80. setData(data);
  81. },
  82. setItem: function (key, value) {
  83. data[key] = value+''; // forces the value to a string
  84. setData(data);
  85. }
  86. };
  87. };
  88.  
  89. if (!window.localStorage) window.localStorage = new Storage('local');
  90. if (!window.sessionStorage) window.sessionStorage = new Storage('session');
  91.  
  92. })();
Add Comment
Please, Sign In to add comment