UNPKG

7.12 kBMarkdownView Raw
1store.js
2========
3
4store.js exposes a simple API for cross browser local storage
5
6```js
7// Store 'marcus' at 'username'
8store.set('username', 'marcus')
9
10// Get 'username'
11store.get('username')
12
13// Remove 'username'
14store.remove('username')
15
16// Clear all keys
17store.clear()
18
19// Store an object literal - store.js uses JSON.stringify under the hood
20store.set('user', { name: 'marcus', likes: 'javascript' })
21
22// Get the stored object - store.js uses JSON.parse under the hood
23var user = store.get('user')
24alert(user.name + ' likes ' + user.likes)
25
26// Get all stored values
27store.getAll().user.name == 'marcus'
28
29// Loop over all stored values
30store.forEach(function(val, key) {
31 console.log(key, '==', val)
32})
33```
34
35
36How does it work?
37------------------
38store.js uses localStorage when available, and falls back on the userData behavior in IE6 and IE7. No flash to slow down your page load. No cookies to fatten your network requests.
39
40store.js depends on JSON for serialization to disk.
41
42
43Installation
44------------
45Just grab [store.min.js] or [store+json2.min.js] and include them with a script tag.
46
47
48`store.enabled` flag
49--------------------
50If your product depends on store.js, you must check the `store.enabled` flag first:
51
52```html
53<script src="store.min.js"></script>
54<script>
55 init()
56 function init() {
57 if (!store.enabled) {
58 alert('Local storage is not supported by your browser. Please disabled "Private Mode", or upgrade to a modern browser')
59 return
60 }
61 var user = store.get('user')
62 // ... and so on ...
63 }
64</script>
65```
66
67LocalStorage may sometimes appear to be available but throw an error when used. An example is Safari's private browsing mode. Other browsers allow the user to temporarily disable localStorage. Store.js detects these conditions and sets the `store.enabled` flag appropriately.
68
69
70Screencast
71-----------
72[Introductory Screencast to Store.js](http://javascriptplayground.com/blog/2012/06/javascript-local-storage-store-js-tutorial) by Jack Franklin.
73
74
75Contributors & Forks
76--------------------
77Contributors: https://github.com/marcuswestin/store.js/graphs/contributors
78
79Forks: https://github.com/marcuswestin/store.js/network/members
80
81
82In node.js
83----------
84store.js works as expected in node.js, assuming that global.localStorage has been set:
85
86```
87global.localStorage = require('localStorage')
88var store = require('./store')
89store.set('foo', 1)
90console.log(store.get('foo'))
91```
92
93
94Supported browsers
95------------------
96 - Tested in iOS 4
97 - Tested in iOS 5
98 - Tested in iOS 6
99 - Tested in Firefox 3.5
100 - Tested in Firefox 3.6
101 - Tested in Firefox 4.0+
102 - Support dropped for Firefox < 3.5 (see notes below)
103 - Tested in Chrome 5
104 - Tested in Chrome 6
105 - Tested in Chrome 7
106 - Tested in Chrome 8
107 - Tested in Chrome 10
108 - Tested in Chrome 11+
109 - Tested in Safari 4
110 - Tested in Safari 5
111 - Tested in IE6
112 - Tested in IE7
113 - Tested in IE8
114 - Tested in IE9
115 - Tested in IE10
116 - Tested in Opera 10
117 - Tested in Opera 11
118 - Tested in Opera 12
119 - Tested in Node.js v0.10.4 (with https://github.com/coolaj86/node-localStorage 1.0.2)
120
121*Private mode* Store.js may not work while browsing in private mode. This is as it should be. Check the `store.enabled` flag before relying on store.js.
122
123*Saucelabs.com rocks* Extensive browser testing of store.js is possible thanks to Saucelabs.com. Check them out, they're awesome.
124
125*Firefox 3.0 & 2.0:* Support for FF 2 & 3 was dropped in v1.3.6. If you require support for ancient versions of FF, use v1.3.5 of store.js.
126
127*Important note:* In IE6 and IE7, many special characters are not allowed in the keys used to store any key/value pair. With [@mferretti](https://github.com/mferretti)'s help, there's a suitable workaround which replaces most forbidden characters with "___".
128
129
130Storage limits
131--------------
132 - IE6 & IE7: 1MB total, but 128kb per "path" or "document" (see http://msdn.microsoft.com/en-us/library/ms531424(v=vs.85).aspx)
133 - See http://dev-test.nemikor.com/web-storage/support-test/ for a list of limits per browser
134
135Unsupported browsers
136-------------------
137 - Firefox 1.0: no means (beside cookies and flash)
138 - Safari 2: no means (beside cookies and flash)
139 - Safari 3: no synchronous api (has asynch sqlite api, but store.js is synch)
140 - Opera 9: don't know if there is synchronous api for storing data locally
141 - Firefox 1.5: don't know if there is synchronous api for storing data locally
142
143
144Some notes on serialization
145---------------------------
146localStorage, when used without store.js, calls toString on all stored values. This means that you can't conveniently store and retrieve numbers, objects or arrays:
147
148```js
149localStorage.myage = 24
150localStorage.myage !== 24
151localStorage.myage === '24'
152
153localStorage.user = { name: 'marcus', likes: 'javascript' }
154localStorage.user === "[object Object]"
155
156localStorage.tags = ['javascript', 'localStorage', 'store.js']
157localStorage.tags.length === 32
158localStorage.tags === "javascript,localStorage,store.js"
159```
160
161What we want (and get with store.js) is
162
163```js
164store.set('myage', 24)
165store.get('myage') === 24
166
167store.set('user', { name: 'marcus', likes: 'javascript' })
168alert("Hi my name is " + store.get('user').name + "!")
169
170store.set('tags', ['javascript', 'localStorage', 'store.js'])
171alert("We've got " + store.get('tags').length + " tags here")
172```
173
174The native serialization engine of javascript is JSON. Rather than leaving it up to you to serialize and deserialize your values, store.js uses JSON.stringify() and JSON.parse() on each call to store.set() and store.get(), respectively.
175
176Some browsers do not have native support for JSON. For those browsers you should include [JSON.js](non-minified copy is included in this repo).
177
178
179No sessionStorage/auto-expiration?
180----------------------------------
181No. I believe there is no way to provide sessionStorage semantics cross browser. However, it is trivial to expire values on read on top of store.js:
182
183```js
184var storeWithExpiration = {
185 set: function(key, val, exp) {
186 store.set(key, { val:val, exp:exp, time:new Date().getTime() })
187 },
188 get: function(key) {
189 var info = store.get(key)
190 if (!info) { return null }
191 if (new Date().getTime() - info.time > info.exp) { return null }
192 return info.val
193 }
194}
195storeWithExpiration.set('foo', 'bar', 1000)
196setTimeout(function() { console.log(storeWithExpiration.get('foo')) }, 500) // -> "bar"
197setTimeout(function() { console.log(storeWithExpiration.get('foo')) }, 1500) // -> null
198```
199
200
201Testing
202-------
203For a browser: Go to http://marcuswestin.github.io/store.js/test.html to test the latest version of store.js.
204
205For a browser, locally: do `npm install node-static && ./node_modules/node-static/bin/cli.js` and go to http://localhost:8080
206
207(Note that test.html must be served over http:// or https://. This is because localStore does not work in some browsers when using the file:// protocol.)
208
209For Nodejs: do `npm install . localStorage && node test-node.js`
210
211
212 [JSON.js]: http://www.json.org/json2.js
213 [store.min.js]: https://raw.github.com/marcuswestin/store.js/master/store.min.js
214 [store+json2.min.js]: https://raw.github.com/marcuswestin/store.js/master/store+json2.min.js
215
\No newline at end of file