Storage.prototype_extension

Storage.prototype extension to store all kinds of data.

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址