Introduction to Web Storage

Discussion in 'Web Development' started by pradeep, Nov 22, 2013.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Web Storage also known as DOM storage is web application technology which allows storage of data inside a web browser. It is similar to storing data in cookies but the capacity is huge, but unlike cookies no stored data is sent over to the server with each request. Web storage can store both persistent or session based data, and key value pair but only of string data type and nothing else.

    This allows developers to cache/store data on the client end and save time fetching data from server or as a fail-safe to failed internet connection, an example would be Wordpress where when you compose a post the details are stored into the Web storage and in case of a browser crash or failed submit to the server Wordpress easily recovers it an shows it.

    Generally all browsers allow at least 5MB data to be stored per origin i.e. hostname, and it is user configurable. There are two types of storage types sessionStorage and localStorage, and it can be accessed using the JavaScript API, Web storage is supported by Firefox 2+, Safari 4+, Chrome 4+, Opera 10.50+, IE8+ onwards. Next we'll be looking into a few code examples in which we try using Web storage functionality.

    Accessing Web Storage using the JavaScript API



    Make sure you have a web browser from the above mentioned list to try the following code sample.

    Code:
    // Store value
    localStorage.setItem('myKey', {
        val: 'myValue'
    });
    
    // Retrieve
    alert(typeof localStorage.getItem('myKey'));
    
    // Store an JavaScript object using JSON
    localStorage.setItem('myKey', JSON.stringify({
        val: 'myValue',
        val2: 'myValue2'
    }));
    
    // Retrieve
    alert(JSON.parse(localStorage.getItem('myKey')).val);
    
     
    shabbir likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice