store.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. ;(function(win){
  2. var store = {},
  3. doc = win.document,
  4. localStorageName = 'localStorage',
  5. scriptTag = 'script',
  6. storage
  7. store.disabled = false
  8. store.set = function(key, value) {}
  9. store.get = function(key) {}
  10. store.remove = function(key) {}
  11. store.clear = function() {}
  12. store.transact = function(key, defaultVal, transactionFn) {
  13. var val = store.get(key)
  14. if (transactionFn == null) {
  15. transactionFn = defaultVal
  16. defaultVal = null
  17. }
  18. if (typeof val == 'undefined') { val = defaultVal || {} }
  19. transactionFn(val)
  20. store.set(key, val)
  21. }
  22. store.getAll = function() {}
  23. store.forEach = function() {}
  24. store.serialize = function(value) {
  25. return JSON.stringify(value)
  26. }
  27. store.deserialize = function(value) {
  28. if (typeof value != 'string') { return undefined }
  29. try { return JSON.parse(value) }
  30. catch(e) { return value || undefined }
  31. }
  32. // Functions to encapsulate questionable FireFox 3.6.13 behavior
  33. // when about.config::dom.storage.enabled === false
  34. // See https://github.com/marcuswestin/store.js/issues#issue/13
  35. function isLocalStorageNameSupported() {
  36. try { return (localStorageName in win && win[localStorageName]) }
  37. catch(err) { return false }
  38. }
  39. if (isLocalStorageNameSupported()) {
  40. storage = win[localStorageName]
  41. store.set = function(key, val) {
  42. if (val === undefined) { return store.remove(key) }
  43. storage.setItem(key, store.serialize(val))
  44. return val
  45. }
  46. store.get = function(key) { return store.deserialize(storage.getItem(key)) }
  47. store.remove = function(key) { storage.removeItem(key) }
  48. store.clear = function() { storage.clear() }
  49. store.getAll = function() {
  50. var ret = {}
  51. store.forEach(function(key, val) {
  52. ret[key] = val
  53. })
  54. return ret
  55. }
  56. store.forEach = function(callback) {
  57. for (var i=0; i<storage.length; i++) {
  58. var key = storage.key(i)
  59. callback(key, store.get(key))
  60. }
  61. }
  62. } else if (doc.documentElement.addBehavior) {
  63. var storageOwner,
  64. storageContainer
  65. // Since #userData storage applies only to specific paths, we need to
  66. // somehow link our data to a specific path. We choose /favicon.ico
  67. // as a pretty safe option, since all browsers already make a request to
  68. // this URL anyway and being a 404 will not hurt us here. We wrap an
  69. // iframe pointing to the favicon in an ActiveXObject(htmlfile) object
  70. // (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx)
  71. // since the iframe access rules appear to allow direct access and
  72. // manipulation of the document element, even for a 404 page. This
  73. // document can be used instead of the current document (which would
  74. // have been limited to the current path) to perform #userData storage.
  75. try {
  76. storageContainer = new ActiveXObject('htmlfile')
  77. storageContainer.open()
  78. storageContainer.write('<'+scriptTag+'>document.w=window</'+scriptTag+'><iframe src="/favicon.ico"></iframe>')
  79. storageContainer.close()
  80. storageOwner = storageContainer.w.frames[0].document
  81. storage = storageOwner.createElement('div')
  82. } catch(e) {
  83. // somehow ActiveXObject instantiation failed (perhaps some special
  84. // security settings or otherwse), fall back to per-path storage
  85. storage = doc.createElement('div')
  86. storageOwner = doc.body
  87. }
  88. function withIEStorage(storeFunction) {
  89. return function() {
  90. var args = Array.prototype.slice.call(arguments, 0)
  91. args.unshift(storage)
  92. // See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx
  93. // and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx
  94. storageOwner.appendChild(storage)
  95. storage.addBehavior('#default#userData')
  96. storage.load(localStorageName)
  97. var result = storeFunction.apply(store, args)
  98. storageOwner.removeChild(storage)
  99. return result
  100. }
  101. }
  102. // In IE7, keys cannot start with a digit or contain certain chars.
  103. // See https://github.com/marcuswestin/store.js/issues/40
  104. // See https://github.com/marcuswestin/store.js/issues/83
  105. var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g")
  106. function ieKeyFix(key) {
  107. return key.replace(/^d/, '___$&').replace(forbiddenCharsRegex, '___')
  108. }
  109. store.set = withIEStorage(function(storage, key, val) {
  110. key = ieKeyFix(key)
  111. if (val === undefined) { return store.remove(key) }
  112. storage.setAttribute(key, store.serialize(val))
  113. storage.save(localStorageName)
  114. return val
  115. })
  116. store.get = withIEStorage(function(storage, key) {
  117. key = ieKeyFix(key)
  118. return store.deserialize(storage.getAttribute(key))
  119. })
  120. store.remove = withIEStorage(function(storage, key) {
  121. key = ieKeyFix(key)
  122. storage.removeAttribute(key)
  123. storage.save(localStorageName)
  124. })
  125. store.clear = withIEStorage(function(storage) {
  126. var attributes = storage.XMLDocument.documentElement.attributes
  127. storage.load(localStorageName)
  128. for (var i=0, attr; attr=attributes[i]; i++) {
  129. storage.removeAttribute(attr.name)
  130. }
  131. storage.save(localStorageName)
  132. })
  133. store.getAll = function(storage) {
  134. var ret = {}
  135. store.forEach(function(key, val) {
  136. ret[key] = val
  137. })
  138. return ret
  139. }
  140. store.forEach = withIEStorage(function(storage, callback) {
  141. var attributes = storage.XMLDocument.documentElement.attributes
  142. for (var i=0, attr; attr=attributes[i]; ++i) {
  143. callback(attr.name, store.deserialize(storage.getAttribute(attr.name)))
  144. }
  145. })
  146. }
  147. try {
  148. var testKey = '__storejs__'
  149. store.set(testKey, testKey)
  150. if (store.get(testKey) != testKey) { store.disabled = true }
  151. store.remove(testKey)
  152. } catch(e) {
  153. store.disabled = true
  154. }
  155. store.enabled = !store.disabled
  156. if (typeof module != 'undefined' && module.exports && this.module !== module) { module.exports = store }
  157. else if (typeof define === 'function' && define.amd) { define(store) }
  158. else { win.store = store }
  159. })(Function('return this')());