IE8 supports Web Storage, therefore Vault can be used with IE8+, but note browser storage limitations in IE8 compared to modern browsers.
Using native HTML5 APIs can be a huge pain, that’s why we should aim to create abstractions. Let’s build a script/module that bakes in the required functionality so that it makes all future development seamless.
So what is Vault? Vault is for localStorage and sessionStorage. These two HTML5 APIs allow for either storage to be kept persistently (localStorage) or just for a session (sessionStorage), a session is until a browser tab is closed killing the process/web document.
Looking at native methods
HTML5 localStorage will be the main lead for these short examples as the syntax is identical to sessionStorage, just the word is different for each type. Here’s how to quickly set and get a value:
HTML5 localStorage accepts only key + value pairs, which means you cannot store Objects - which would be the only really useful way of using localStorage. Or can we?…
Using JSON we can convert an Object to a String. If I then wanted to store an Object in localStorage, I can simply push the String. To do this, you might do the following using the native JSON.stringify() method inside the setItem call:
…But now our Object has been stored as a String and will still remain a String. We need to use JSON again to parse it back into an Object:
This whole going back and forth between JSON parsing/stringify-ing and writing the same code is what inspired Vault, it makes things easy, especially if you’re interchanging between localStorage and sessionStorage in the same application - you’ve got the whole power under the hood.
I’ll talk you through the APIs for Vault and you can get using it. Vault builds in these above methods, automatically parses and stringifies your code for you, letting you develop with minimal code. It also allows you to switch easily between localStorage and sessionStorage.
To set data into web storage, you must use the
set() API. With this API, there are three ordered arguments,
type, which denotes the type of Web Storage,
key for the Object’s key, and
value for the key value:
Obtaining set data is easy with the
get() API, simply reference a previously set key with
type and the
Removing set data is easy with the
remove() API, again reference a previously set key with
type and the
It’s a good idea to empty the user’s Web Storage when possible to avoid overloading it, there are limits which differ per browser. Specifically modern browsers allow around
5MB but IE versions are limited. IE8 also supports Web Storage and Vault.
Example to empty
As always, grab the code on GitHub and help contribute to open source!