ieuserdata.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview Provides data persistence using IE userData mechanism.
  16. * UserData uses proprietary Element.addBehavior(), Element.load(),
  17. * Element.save(), and Element.XMLDocument() methods, see:
  18. * http://msdn.microsoft.com/en-us/library/ms531424(v=vs.85).aspx.
  19. *
  20. */
  21. goog.provide('goog.storage.mechanism.IEUserData');
  22. goog.require('goog.asserts');
  23. goog.require('goog.iter.Iterator');
  24. goog.require('goog.iter.StopIteration');
  25. goog.require('goog.storage.mechanism.ErrorCode');
  26. goog.require('goog.storage.mechanism.IterableMechanism');
  27. goog.require('goog.structs.Map');
  28. goog.require('goog.userAgent');
  29. /**
  30. * Provides a storage mechanism using IE userData.
  31. *
  32. * @param {string} storageKey The key (store name) to store the data under.
  33. * @param {string=} opt_storageNodeId The ID of the associated HTML element,
  34. * one will be created if not provided.
  35. * @constructor
  36. * @extends {goog.storage.mechanism.IterableMechanism}
  37. * @final
  38. */
  39. goog.storage.mechanism.IEUserData = function(storageKey, opt_storageNodeId) {
  40. /**
  41. * The key to store the data under.
  42. *
  43. * @private {?string}
  44. */
  45. this.storageKey_ = storageKey;
  46. /**
  47. * The document element used for storing data.
  48. *
  49. * @private {Element}
  50. */
  51. this.storageNode_ = null;
  52. goog.storage.mechanism.IEUserData.base(this, 'constructor');
  53. // Tested on IE6, IE7 and IE8. It seems that IE9 introduces some security
  54. // features which make persistent (loaded) node attributes invisible from
  55. // JavaScript.
  56. if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9)) {
  57. if (!goog.storage.mechanism.IEUserData.storageMap_) {
  58. goog.storage.mechanism.IEUserData.storageMap_ = new goog.structs.Map();
  59. }
  60. this.storageNode_ = /** @type {Element} */ (
  61. goog.storage.mechanism.IEUserData.storageMap_.get(storageKey));
  62. if (!this.storageNode_) {
  63. if (opt_storageNodeId) {
  64. this.storageNode_ = document.getElementById(opt_storageNodeId);
  65. } else {
  66. this.storageNode_ = document.createElement('userdata');
  67. // This is a special IE-only method letting us persist data.
  68. this.storageNode_['addBehavior']('#default#userData');
  69. document.body.appendChild(this.storageNode_);
  70. }
  71. goog.storage.mechanism.IEUserData.storageMap_.set(
  72. storageKey, this.storageNode_);
  73. }
  74. try {
  75. // Availability check.
  76. this.loadNode_();
  77. } catch (e) {
  78. this.storageNode_ = null;
  79. }
  80. }
  81. };
  82. goog.inherits(
  83. goog.storage.mechanism.IEUserData,
  84. goog.storage.mechanism.IterableMechanism);
  85. /**
  86. * Encoding map for characters which are not encoded by encodeURIComponent().
  87. * See encodeKey_ documentation for encoding details.
  88. *
  89. * @type {!Object}
  90. * @const
  91. */
  92. goog.storage.mechanism.IEUserData.ENCODE_MAP = {
  93. '.': '.2E',
  94. '!': '.21',
  95. '~': '.7E',
  96. '*': '.2A',
  97. '\'': '.27',
  98. '(': '.28',
  99. ')': '.29',
  100. '%': '.'
  101. };
  102. /**
  103. * Global storageKey to storageNode map, so we save on reloading the storage.
  104. *
  105. * @type {goog.structs.Map}
  106. * @private
  107. */
  108. goog.storage.mechanism.IEUserData.storageMap_ = null;
  109. /**
  110. * Encodes anything other than [-a-zA-Z0-9_] using a dot followed by hex,
  111. * and prefixes with underscore to form a valid and safe HTML attribute name.
  112. *
  113. * We use URI encoding to do the initial heavy lifting, then escape the
  114. * remaining characters that we can't use. Since a valid attribute name can't
  115. * contain the percent sign (%), we use a dot (.) as an escape character.
  116. *
  117. * @param {string} key The key to be encoded.
  118. * @return {string} The encoded key.
  119. * @private
  120. */
  121. goog.storage.mechanism.IEUserData.encodeKey_ = function(key) {
  122. // encodeURIComponent leaves - _ . ! ~ * ' ( ) unencoded.
  123. return '_' + encodeURIComponent(key).replace(/[.!~*'()%]/g, function(c) {
  124. return goog.storage.mechanism.IEUserData.ENCODE_MAP[c];
  125. });
  126. };
  127. /**
  128. * Decodes a dot-encoded and character-prefixed key.
  129. * See encodeKey_ documentation for encoding details.
  130. *
  131. * @param {string} key The key to be decoded.
  132. * @return {string} The decoded key.
  133. * @private
  134. */
  135. goog.storage.mechanism.IEUserData.decodeKey_ = function(key) {
  136. return decodeURIComponent(key.replace(/\./g, '%')).substr(1);
  137. };
  138. /**
  139. * Determines whether or not the mechanism is available.
  140. *
  141. * @return {boolean} True if the mechanism is available.
  142. */
  143. goog.storage.mechanism.IEUserData.prototype.isAvailable = function() {
  144. return !!this.storageNode_;
  145. };
  146. /** @override */
  147. goog.storage.mechanism.IEUserData.prototype.set = function(key, value) {
  148. this.storageNode_.setAttribute(
  149. goog.storage.mechanism.IEUserData.encodeKey_(key), value);
  150. this.saveNode_();
  151. };
  152. /** @override */
  153. goog.storage.mechanism.IEUserData.prototype.get = function(key) {
  154. // According to Microsoft, values can be strings, numbers or booleans. Since
  155. // we only save strings, any other type is a storage error. If we returned
  156. // nulls for such keys, i.e., treated them as non-existent, this would lead
  157. // to a paradox where a key exists, but it does not when it is retrieved.
  158. // http://msdn.microsoft.com/en-us/library/ms531348(v=vs.85).aspx
  159. var value = this.storageNode_.getAttribute(
  160. goog.storage.mechanism.IEUserData.encodeKey_(key));
  161. if (!goog.isString(value) && !goog.isNull(value)) {
  162. throw goog.storage.mechanism.ErrorCode.INVALID_VALUE;
  163. }
  164. return value;
  165. };
  166. /** @override */
  167. goog.storage.mechanism.IEUserData.prototype.remove = function(key) {
  168. this.storageNode_.removeAttribute(
  169. goog.storage.mechanism.IEUserData.encodeKey_(key));
  170. this.saveNode_();
  171. };
  172. /** @override */
  173. goog.storage.mechanism.IEUserData.prototype.getCount = function() {
  174. return this.getNode_().attributes.length;
  175. };
  176. /** @override */
  177. goog.storage.mechanism.IEUserData.prototype.__iterator__ = function(opt_keys) {
  178. var i = 0;
  179. var attributes = this.getNode_().attributes;
  180. var newIter = new goog.iter.Iterator();
  181. newIter.next = function() {
  182. if (i >= attributes.length) {
  183. throw goog.iter.StopIteration;
  184. }
  185. var item = goog.asserts.assert(attributes[i++]);
  186. if (opt_keys) {
  187. return goog.storage.mechanism.IEUserData.decodeKey_(item.nodeName);
  188. }
  189. var value = item.nodeValue;
  190. // The value must exist and be a string, otherwise it is a storage error.
  191. if (!goog.isString(value)) {
  192. throw goog.storage.mechanism.ErrorCode.INVALID_VALUE;
  193. }
  194. return value;
  195. };
  196. return newIter;
  197. };
  198. /** @override */
  199. goog.storage.mechanism.IEUserData.prototype.clear = function() {
  200. var node = this.getNode_();
  201. for (var left = node.attributes.length; left > 0; left--) {
  202. node.removeAttribute(node.attributes[left - 1].nodeName);
  203. }
  204. this.saveNode_();
  205. };
  206. /**
  207. * Loads the underlying storage node to the state we saved it to before.
  208. *
  209. * @private
  210. */
  211. goog.storage.mechanism.IEUserData.prototype.loadNode_ = function() {
  212. // This is a special IE-only method on Elements letting us persist data.
  213. this.storageNode_['load'](this.storageKey_);
  214. };
  215. /**
  216. * Saves the underlying storage node.
  217. *
  218. * @private
  219. */
  220. goog.storage.mechanism.IEUserData.prototype.saveNode_ = function() {
  221. try {
  222. // This is a special IE-only method on Elements letting us persist data.
  223. // Do not try to assign this.storageNode_['save'] to a variable, it does
  224. // not work. May throw an exception when the quota is exceeded.
  225. this.storageNode_['save'](this.storageKey_);
  226. } catch (e) {
  227. throw goog.storage.mechanism.ErrorCode.QUOTA_EXCEEDED;
  228. }
  229. };
  230. /**
  231. * Returns the storage node.
  232. *
  233. * @return {!Element} Storage DOM Element.
  234. * @private
  235. */
  236. goog.storage.mechanism.IEUserData.prototype.getNode_ = function() {
  237. // This is a special IE-only property letting us browse persistent data.
  238. var doc = /** @type {Document} */ (this.storageNode_['XMLDocument']);
  239. return doc.documentElement;
  240. };