HTML5 Web Storage – Store prudently

Hungarian Web Storage version

In this Article I am endeavor to do a demonstration in HTML5 to be introduced data storage modul (Web Storage) of a client side. Naturally it will not change the World as it seems – since the “cloud” we know that it will -, but nevertheless it assures a great option which we could solve only with different tricks so far (e.g.: Cookie). But the Cookie had many disadvantage (limited size 4KB, traffic through the forwarding per request etc.). Well on the other hands the HTML5 Web Storage by the current definition can store 5MB data per source. Plenty of data can be stored here. It is important aswell that no unnecessary traffic will spring up because it is not sending data only if we ask. (by the way it is not done to make 5MB storages)

The Web Storage itself stores the data in a key/value pair form and we can search back with this in a later time when we need it. The type of the key is text while the type of the value can be anything. Let’s see the types of the storage:

1. Session Storage

The data will be stored here until the end of the browsing Session. After that they will be deleted (this can redeem the cookies). As long as the data will not be important to us in a later time, or for users, it is worthwhile to use this solution due to saving of the resources.

2. Local Storage

It is a different case like the previous. The data will be stored here and remains until we will not delete the key/value pairs or the user will not do this with his/her browser. Now You could ask why is this so good? Because e.g.: if a user opens a new window he/she can get the data or if he/she quits from his/her browser and re-enter, the data will be available.

Their Use

Thereupon I will not unfold them in half because they feeding from one API means they have the same functions and attributes furthermore the access and the storage of the data is the same. Let’s see which functions are necessary to use the Storage:

  • clear() – We can clear the plot of our Storage.
  • getItem(key) – Returns the associated value that has been used as key.
  • key(index) – Returns the associated key that has been given in index parameter.
  • length – Returns the number of the stored key/value pair.
  • removeItem(key) – Removes a key and related data from the storage.
  • setItem(key,value) – with this function we can store data in the Storage.

Storage Event – something has changed

If we store a new data belonging to our website (setItem), or remove data (removeItem) delete the plot of the Storage (clear) we can redeem an onStorage event which returns with the following value:

  • storageArea – Session or Local
  • key – key that changes
  • oldValue – its old value
  • newValue – its new value
  • url – the site’s URL which key has been changed.

In Practice

First of all let’s see, how we can simply look with a Script’s help that our browser may support the Web Storage function or not

function supportsLocalStorage() {
    return ('localStorage' in window) && window['localStorage'] !== null;
}

if(supportsLocalStorage()) {
    // call Web Storage here
}
else {
    alert('The Web Storage is not supported!');
}

If it supports that we can let the “call Web Storage here” out with set/get/remove/clear components:

//
// Data Storage
//
sessionStorage.setItem('key','value'); //in case of session storage
localStorage.setItem('key','value'); //in case of local storage
//short form
sessionStorage.kulcs="value";
localStorage.kulcs="value";
//
//Data reading
//
sessionStorage.getItem("key"); //returns value is the one that belongs to the key
localStorage.getItem("key"); //returns value is the one that belongs to the key
//short form
sessionStorage.kulcs;
localStorage.kulcs;
//
//Data delete
//
sessionStorage.removeItem("key"); // removing the key and the value that belongs to it
localStorage.removeItem("key");
//
//Storage full delete
//
sessionStorage.clear();
localStorage.clear();

Now let’s see two simply examples to these. In our example we call in the user’s name with a help of a simple form. After that we ensure the opportunity to query the data stored in the Storage too. I will not place any commentary i have tried to give a descriptive name to everything. Let’s begin with the localStorage.


<!DOCTYPE html>
 <html>
 <head>
 <title> Local Storage Demo</title>
 </head>
 <body>

<script>
 function datain() {
 var name = document.simpleform.Name.value;
 localStorage.firstname = name;
 }

function dataout() {
 alert(localStorage.firstname);
 }
 </script>

<div align="center">
 <p> What is your name? I will remember to it!</p>
 <form name="simpleform">
 <input type="text" name="Name" />
 <input type="submit" onclick="datain()" />
 <input type="button" id="" value="Query" onclick="dataout()" />
 </form>
 </div>
 </body>
 </html>

You can try the working localstorage example here.

Let’s see the same with the sessionStorage.


<!DOCTYPE html>
<html>
<head>
<title> Session Storage demo</title>
</head>

<body>
<script>

function datain() {
var nev = document.simpleform.name.value;
sessionStorage.firstname = nev;
}

function dataout() {
alert(sessionStorage.firstname);
}

</script>
<div align="center">
<p> What is your name? I will remember to it but the time until you not close me!</p>
<form name="simpleform">
<input type="text" name="name" />
<input type="submit" onclick="datain()" />
<input type="button" id="" value="Query" onclick="dataout()" />
</form>

</div>
</body>
</html>

You can try the working sessionstorage example here.

If we see well the two examples there is only 2 words difference between them. It is plain that their use is not different.

Now let’s see another example. Let’s make a simple counter that increases the localStorage and the sessionStorage value with 1 by every loading of the page. Together with a delete button so that we can erase our storage at the end.


<!DOCTYPE html>
<html>
<head>
<title>Web Storage Counter Demo</title>
</head>

<body>
<h1>Have I Seen it before? How many times?</h1>
<p>localStorage - Page loading number: <span id="localpiece">0</span> db</p>
<p>sessionStorage - Page loading number: <span id="sessionpiece">0</span> db</p>

<script type="text/javascript">
if (!localStorage.pageloading) //creating and zero-setting of localStorage and incrase with 1 by every loading of the page
localStorage.pageloading= 0;
localStorage.pageloading= 1 + parseInt(localStorage.pageloading);
document.getElementById('localpiece').innerHTML = localStorage.pageloading; //put in localpiece

if (!sessionStorage.pageloading) //creating and zero-setting of sessionStorage and incrase with 1 by every loading of the page
sessionStorage.pageloading= 0;
sessionStorage.pageloading= 1 + parseInt(sessionStorage.pageloading);
document.getElementById('sessionpiece').innerHTML = sessionStorage.pageloading; //put in sessionpiece

function slclear() { //delete Local- and SessionStorage with a button
sessionStorage.clear();
localStorage.clear();
}
</script>

<p>Refresh to the site and then close it and reopen from the post. As You can see the localstorage kept its plot, the sessionstorage lost it.</p>
<input type="button" value="Delete" onclick="slclear();" />

</body>
</html>

You can try the working storage example here.

I hope it helped to understand the use of the localStorage and the sessionStorage. In the next part we are going to create a simple Agenda list with the localStorage. I know that a lot have been published on the internet but maybe we can make a different version.

Source:

http://www.whatwg.org/specs/web-apps/current-work/multipage/webstorage.html#webstorage

Creative Commons Licenc
HTML5 Web Storage – Store prudently  a Creative Commons Nevezd meg! – Ne add el! – Így add tovább! 2.5 Magyarország Licenc alatt van.

Permissions beyond the scope of this license may be available at http://html5.ugyesen.com.

You may also like...