Saturday, January 18, 2014

Using Web Storage

What is HTML5 Web Storage?

With HTML5, web pages can store data locally within the user's browser.
Earlier, this was done with cookies. However, Web Storage is more secure and faster. The data is not included with every server request, but used ONLY when asked for. It is also possible to store large amounts of data, without affecting the website's performance.

The data is stored in key/value pairs, and a web page can only access data stored by itself.

localStorage and sessionStorage 
There are two new objects for storing data on the client:
  • localStorage - stores data with no expiration date

The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.
  • sessionStorage - stores data for one session
  • it persists in the same tab, being the origin of the context, and in every page surfed inside the tab, so it could be extremely unsafe to trust it for important data
  • it is automatically cleaned as soon as we close the tab or the browser, so used RAM will be automatically cleaned and without scripting effort
Before using web storage, check browser support for localStorage and sessionStorage:
  // localStorage and sessionStorage code goes here
  // Your Webbrowser doesn't support webstorage !

We are going to use Session storage to save username and password. 

        function getServerPwd(aName) {
            if (typeof (Storage) !== "undefined") {
                if (!sessionStorage.user_name) {
                    sessionStorage.user_name = aName;
                    sessionStorage.user_pwd = getHashPwd(aName);
                return sessionStorage.user_pwd;
            else {
                alert("browser doesn't support session data !");
            return "";

        function getHashPwd(aName)

        var hash = 0, i, char;
   if (aName.length == 0) return hash;
   for (i = 0, l = aName.length; i < l; i++) {
       char  = aName.charCodeAt(i);
       hash  = ((hash<<5)-hash)+char;
       hash |= 0; // Convert to 32bit integer
    return hash;

No comments:

Post a Comment