Storage.prototype_extension

Storage.prototype extension to store all kinds of data.

目前为 2015-01-20 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/7573/32728/Storageprototype_extension.js

  1. /***************************************************************************************
  2. ****************************************************************************************
  3. *****
  4. ***** Storage.prototype extension to store all kinds of data
  5. *****
  6. ***** NOTE: Nested functions in objects are not supported (ignored).
  7. *****
  8. ***** This library extends the Storage object used by localStorage and sessionStorage
  9. ***** to allow them to store all types of javascript variables with some optimizations.
  10. *****
  11. ***** sessionStorage maintains a separate storage area for each given origin that's
  12. ***** available for the duration of the page session (as long as the browser is open,
  13. ***** including page reloads and restores).
  14. *****
  15. ***** localStorage does the same thing,
  16. ***** but persists even when the browser is closed and reopened.
  17. *****
  18. ***** Add it to your script with:
  19. ***** // require
  20. *****
  21. ***** Usage:
  22. ***** localStorage.set (key, value);
  23. ***** sessionStorage.set (key, value);
  24. *****
  25. ***** var x = localStorage.get (key, defaultValue);
  26. ***** var y = sessionStorage.get (key, defaultValue);
  27. *****
  28. ***** Size:
  29. ***** Storage.getSize ();
  30. *****
  31. ***** Test mode:
  32. ***** Storage.runTestCases ();
  33. *****
  34. */
  35.  
  36. (function() {
  37.  
  38. var BOOLEAN_MARKER = 'b';
  39. var NUMBER_MARKER = 'n';
  40. var STRING_MARKER = 's';
  41. var JSON_MARKER = 'j';
  42. var FUNCTION_MARKER = 'f';
  43.  
  44. var TEST_CASES = {
  45. t00: true,
  46. t01: false,
  47. t02: 0,
  48. t03: 1,
  49. t04: 2147483646,
  50. t05: -2147483646,
  51. t06: "",
  52. t07: !0,
  53. t08: !1,
  54. t09: null,
  55. t10: undefined,
  56. t11: "true",
  57. t12: "false",
  58. t13: {
  59. t131: "t131",
  60. t132: {
  61. t1321: 't621',
  62. t1322: true,
  63. t1323: this.t1321, // ignored
  64. t1324: 1324
  65. },
  66. t133: undefined, // ignored
  67. t134: function(){
  68. console.log("t134");
  69. } // ignored
  70. },
  71. t14: function(){
  72. console.log("t14");
  73. }, // fine
  74. t15: {
  75. t151: function (){
  76. console.log("t151");
  77. } // ignored
  78. } // empty object
  79. };
  80.  
  81. //--- Check that the environment is proper.
  82. if (typeof(window.Storage) != "function")
  83. console.error('Storage is not supported! This library requires your browser to support the Web Storage function.');
  84. if (typeof(window.localStorage) != "object")
  85. console.error('This library requires localStorage support. Your current browser does not support localStorage!');
  86. if (typeof(window.sessionStorage) != "object")
  87. console.warn('Your browser does not support sessionStorage. Store locally only!');
  88.  
  89.  
  90. /*--- set (key, value)
  91. The Storage object stores only strings, like a cookie,
  92. but in a more intuitive way.
  93.  
  94. This function extends that to allow storing any data type.
  95.  
  96. Parameters:
  97. key
  98. String: The unique (within this domain) name for this value.
  99. Should be restricted to valid Javascript identifier characters.
  100.  
  101. value
  102. Any valid javascript value. Strings in JavaScript are UTF-16,
  103. so each character requires two bytes of memory.
  104. This means that while many browsers have a 5 MB limit,
  105. you can only store 2.5 M characters. This function logs an
  106. error if your browser limit is exceeded.
  107.  
  108. Returns:
  109. When browser limit has been reached...
  110. undefined and an error is thrown wherever possible.
  111.  
  112. In all other cases...
  113. undefined only.
  114. */
  115. Storage.prototype.set = function(key, value) {
  116.  
  117. if (typeof key != "string") {
  118. console.error('Illegal key passed to Storage.prototype.setObject.');
  119. return;
  120. }
  121.  
  122. if(value == void 0){
  123. console.error('Illegal value sent to Storage.set().');
  124. return;
  125. }
  126.  
  127. if (/[^\w _-]/.test(key)) {
  128. console.warn('Suspect, probably illegal, key passed to localStorage.set().');
  129. }
  130.  
  131. var safeStr = false;
  132. switch (typeof value) {
  133. case 'boolean':
  134. safeStr = BOOLEAN_MARKER + (value ? '!0' : '!1');
  135. break;
  136. case 'string':
  137. safeStr = STRING_MARKER + value;
  138. break;
  139. case 'number':
  140. safeStr = NUMBER_MARKER + value;
  141. break;
  142. case 'object':
  143. safeStr = JSON_MARKER + JSON.stringify(value);
  144. break;
  145. case 'function':
  146. safeStr = FUNCTION_MARKER + value.toString();
  147. break;
  148. default:
  149. console.error('Unknown type in Storage.set()!');
  150. break;
  151. }
  152.  
  153. try {
  154. if(safeStr)
  155. this.setItem(key, safeStr);
  156. } catch(err){
  157. console.error("Problem occurred while saving: " + err);
  158. }
  159. }; //-- End of get()
  160.  
  161.  
  162. /*--- get (key, defaultValue)
  163. The Storage object retrieves only strings, like a cookie,
  164. but in a more intuitive way.
  165.  
  166. This function extends that to allow retrieving data
  167. from the correct data type.
  168.  
  169. Parameters:
  170. key
  171. String: The unique (within this domain) name for this value.
  172. Should be restricted to valid Javascript identifier characters.
  173.  
  174. defaultValue
  175. Optional. Any value to be returned, when no value has previously
  176. been set.
  177.  
  178. Returns:
  179. When this name has been set...
  180. The variable or function value as previously set.
  181.  
  182. When this name has not been set and a default is provided...
  183. The value passed in as a default.
  184.  
  185. When this name has not been set and default is not provided...
  186. undefined
  187. */
  188. Storage.prototype.get = function(key, defaultValue) {
  189. var value = this.getItem(key);
  190.  
  191. if(value == void 0)
  192. return defaultValue;
  193.  
  194. switch (value[0]) {
  195. case 'b':
  196. return eval(value.substr(1));
  197. break;
  198. case 's':
  199. return value.substr(1);
  200. break;
  201. case 'n':
  202. case 'j':
  203. return JSON.parse(value.substr(1));
  204. break;
  205. case 'f':
  206. return eval('(' + value.substr(1) + ')');
  207. break;
  208. default:
  209. console.error('Unknown type in Storage.get()!');
  210. break;
  211. }
  212.  
  213. return undefined;
  214. }; //-- End of get()
  215.  
  216. /*--- getSize ()
  217. Each separate storage object when local and session are instantiated
  218. can hold up to 5 MB of stringified data. This is an approximation
  219. of the current local or session object size.
  220.  
  221. Parameters:
  222. none
  223.  
  224. Returns:
  225. int showing the length of the localStorage object.
  226. */
  227. Storage.prototype.getSize = function() {
  228. return JSON.stringify(localStorage).length;
  229. };
  230.  
  231. /*--- runTests ()
  232. Tests setting and retrieving values of all types on the Storage
  233. object with this extension.
  234.  
  235. Parameters:
  236. none
  237.  
  238. Returns:
  239. undefined and console output with test results.
  240. */
  241. Storage.prototype.runTests = function(){
  242.  
  243. for(var testCase in TEST_CASES){
  244. if(TEST_CASES.hasOwnProperty(testCase)){
  245.  
  246. try{
  247.  
  248. var testValue = TEST_CASES[testCase];
  249. console.log("Setting", testCase, "with value", testValue, "(", typeof testValue, ")");
  250.  
  251. this.set(testCase, testValue);
  252.  
  253. console.log("Variable successfully set. Retrieving...");
  254.  
  255. var retrieved = this.get(testCase);
  256. console.log("Retrieved", testCase, "with value", retrieved, "(", typeof retrieved, ")");
  257.  
  258. testValue === retrieved || (typeof testValue == typeof retrieved)
  259. ? console.info("Test case succeeded.")
  260. : console.warn("Test case failed");
  261.  
  262. } catch (err){
  263. console.error("Test case failed:", err);
  264. }
  265.  
  266. }
  267. }
  268. };
  269. }());