Recently I had a need to use HTML5 LocalStorage API in my web application project. The requirement was to save the vertical scroll position of window when a user drills down to low level details by navigating to other view. I didn’t wanted to cookies because cookies are sent on every request to the server and I have no need to send this detail to the server as it is just related to client.
Then I was left with LocalStorage and SessionStorage as options. I found that SessionStorage is not maintained when the page reloads and when the browser is closed. So, I opted to use LocalStorage API for this use case and came up with the code below which is a localStorageWrapper module that can be accessed as a module when using RequireJS (a module loader). A client consuming this wrapper is able to set, get, check the existence of a key and clear all the items in client’s localStorage. An item that can be save is made up of a key and a value. This value can be just a string or an javascript object that can be JSON stringified and then saved. This can be seen in the set function of the localStorageWrapper module below.
When using these fancy new HTML5 APIs, one should care about the browser support. You can use CanIuse website to check it. This is a very good resource to check support for everything and anything related to web.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
|
To properly provide graceful degradation, you can use Modernizr to check if client supports a particular HTML5 feature. When using Modernizr, the client code consuming the above module looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|