At the beginning of this book, we took a look at how you can use Local Storage to store persistent information on a client computer, which remains there even when the browser is closed. That's great, but isn't it a little overkill for instances such as shopping carts? You'd be right – we don't need to store information about purchases forever; indeed, information should only be stored for the duration of the current session. In this recipe, we're going to take another look at Session Storage, to see how it stacks up against LocalStorage.
In the following steps, we will take a look at how it works and stacks up against Local Storage:
sessionvlocaldemo.html
:<!DOCType html> <html> <head> </head> <body> <div id="content"> </div> </body> </html>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.min.js"></script> <style type="text/css"> #content { width: 400px; padding: 10px; margin-left: auto; margin-right: auto; margin-top: 5%; border: 1px solid #c4c4c4; } </style>
<script type="text/javascript"> function clickCounter() { if(typeof(Storage)!=="undefined") { if (sessionStorage.clickcount) { sessionStorage.clickcount=Number (sessionStorage.clickcount)+1; } else { sessionStorage.clickcount=1; } document.getElementById("result").innerHTML= "You have clicked the button " + sessionStorage.clickcount + " time(s)."; } else { document.getElementById("result").innerHTML= "Sorry, your browser does not support web storage..."; } }
localStorage
area:function storeItem() { var item = $('#item').val(); var items = localStorage.getItem('myItems'), if (items != null) { items = JSON.parse(items); } else { items = new Array(); } items.push(item); localStorage.setItem('myItems', JSON.stringify(items)); refresh(); }
function refresh() { var items = localStorage.getItem('myItems'), var ul = $('ul'), ul.html(''), if (items != null) { items = JSON.parse(items); $(items).each(function (index, data) { ul.append('<li>' + data + '</li>'), }); } }
refresh
function that we've just set up:$(function () { refresh(); }); </script>
<p><b>SessionStorage Demo:</b></p> <p><button onclick="clickCounter()" type="button"> Click me!</button></p> <div id="result"></div> <p>Click the button to see the counter increase.</p> <hr> <p><b>LocalStorage Demo:</b></p> <p>Enter item:</p> <input type="text" id="item" /> <input type="button" value="store" onclick= "storeItem()" /> <br /> <ul></ul>
At the heart of Session Storage, there is actually very little difference compared to that of Local Storage. Both work on the same basis of setting and getting a named key/value pair within the browser's storage area. Clicking on the SessionStorage
button will increase the counter ad
to infinitum. It will be reset as soon as you refresh your browser window. In contrast, adding any entries to the LocalStorage
option will store the values; these will remain stored, irrespective of any browser refresh.
If you need information to remain on the browser after it has been closed or restarted, you should use Local Storage. If, however, you're only looking to keep values for the duration of a single session, Session Storage is the better option.
Now that we have had an opportunity to look at Session Storage, let's dig into how both methods work in more detail.
Both Local and Session Storage work using the same methods:
Type |
Name and arguments |
Purpose |
---|---|---|
string |
|
Returns the name of a key at the index in the argument |
string |
|
Returns the value of the key |
void |
|
Assigns a value to a key |
void |
|
Removes the key whose name is in the argument |
void |
|
Clears the storage space and removes all keys |
long |
|
Number of items stored |
The Storage API has been defined so that each of the get
, set
, and remove
methods are known as getters, setters, and deleters. To see what I mean, take a look at the following two examples:
var myVar = sessionStorage.getItem('myKey'),
sessionStorage.setItem('myKey', 'myValue'),
These two methods get and set the information into the myKey
value within the localStorage
area of the browser as a sessionStorage
key/value pair. However, you could equally write the following:
sessionStorage.myKey = 'myValue'; var myVar = sessionStorage.myKey;
The preceding code would achieve the same result and is probably a little more readable too! The same applies to localStorage
:
localStorage.setItem('myKey', 'myValue'), var myVar = localStorage.getItem('myKey'),
You could write this as follows:
localStorage.myKey = 'myValue'; var myVar = localStorage.myKey;
The preceding code will achieve the same result.
Now we've seen how Session Storage works. We will now see some more differences between Session Storage and Local Storage. Before doing so, we're going to take a look at a theoretical example of how you could approximate the effect of Session Storage if you don't have any access to jQuery or a library such as Modernizr, or to a more recent browser. It will look ugly, but there is a reason for showing you this. All will become clear as we go through the next recipe.