In this recipe, we're going to take a look at how Session Storage works, using a simple demo in the form of a click counter, which will reset each time you refresh your browser session.
For the purposes of this task, all you will need is a normal text editor of your choice.
In the following steps, we will take a look at how Session Storage works:
sessiondemo.html
:<!DOCTYPE html> <html> <head> <meta content="utf-8"> <script src= "http://code.jquery.com/jquery-1.8.1.min.js"></script> <script type="text/javascript"></script> </head> <body> </body> </html>
<p><button id="clickCounter" type="button">Click me!</button></p> <div id="result"></div> <p>Click the button to see the counter increase.</p> <p>Close the browser tab (or window), and try again, and the counter is reset.</p>
<script>
tags, which will keep a count of how many times you click on the button and display the results on the screen:$(document).ready(function(){ $("#clickCounter").click(function () { if (sessionStorage.clickcount) { sessionStorage.clickcount=Number (sessionStorage.clickcount)+1; } else { sessionStorage.clickcount=1; } $("#result").html("You have clicked the button " + sessionStorage.clickcount + " time(s)."); }); });
In this recipe, we've set up a simple HTML document, which has a button that acts as a counter. We start with a check to ensure that there is a clickcount
property in Session Storage. If not, we create a new one and assign it the value 1
. Each time we click on the button, it increases the clickcount
attribute of Session Storage by a factor of one and updates the count on the screen.
The final step in this recipe is arguably the most important one in the whole recipe. It illustrates perfectly that Session Storage only lasts for as long as the current browser session. It is sufficient to merely refresh the screen. As soon as you do that, you will lose the count, which the browser resets back to 1
in preparation for a new counting session. If your data needs to be more persistent, you will need to use Local Storage instead, as we will see in the next recipe.