Voice of a Developer: Web Storage API - Part 25

Introduction

 
The Web offers a variety of APIs to build your app or website. You could access using JavaScript code. These days browsers offer many APIs to developers. In the last article, we read about XMLHttpRequest API and in this article, we will understand Storage APIs available.
 
Before moving further let us look at the previous articles of the JavaScript series:
Before I dig into storage we will understand the key-value pairs.
 

Key-Value pair (KVP)

 
KVP stores two values together. It is a set of two linked data items; a unique key and some value. This is frequently used in the hash, map, dictionary, JSON, configuration files, etc. Example – below the representation of KVP could be translated in the form of Object in JavaScript.
 
Key-Value
 
  1. var obj = {width: 300, height:200, title: 'Menu'};   
Now let’s proceed with Storage API
 

Web Storage API

 
When we think about storage we think of Database, Files, etc. With HTML5 web storage provides a client-side method for storing information.
 
The two ways within Web storage are:
  • sessionStorage: maintains storage as long as the browser is open, including page reloads and restores. It gets clear when the session ends.
  • localStorage: same thing like sessionStorage, but persists even when the browser is closed/opened again. This means it has no expiration time.
Note: There was a way in Firefox 9, i.e., globalStorage but it was deprecated after HTML5 introduced this local storage.
 

Access client-side storage

 
These are available via Window.sessionStorage & Window.localStorage. Both of these provide access to create, get, modify, delete client-side storage depending upon session or local store.
 

Facts about client-side storage

 

How much storage does browser provide?

 
Generally, 5MB, 5MB is available for sessionStorage& localStorage respectively. 
 

How can we check the available storage in our browser?

 
You can leverage utility to run these tests at your browser and it will show you the output. I conducted test at my browser Chrome 50 & Firefox 45 and both gave same result, i.e., 5 MB.
 
output
 

Misconception

 
Please note 5MB does not mean 5 million characters are allowed. Developers think that each character occupies 1 byte, which is correct for some programming languages. But JavaScript occupies 2 bytes each character as it stores string on basis on UTF-16.
 

localStorage

 
Write localStorage
 
Below code will write data into localStorage and using setItem() function:
  1. <script>    
  2.    localStorage.setItem("fname""Sumit");    
  3.    localStorage.setItem("lname""Jolly");    
  4.    localStorage.setItem("profile""http://www.c-sharpcorner.com/members/sumit-jolly");    
  5. </script>   
    Configure a website in local Web server and run URL: http://localhost:8079/test.html
     
    You can see ‘Local Storage’ content in browser after clicking Resources in Chrome.
     
    Local Storage
     
    If you run on Firefox then it will also create a Local Storage but the view is disabled by default. To enable it goto ‘Toolbox options’ and click Storage checkbox.
     
    Toolbox options
     
    Aforesaid, localStorage has no expiration and even you close browser it’ll stay there. You can try this and would be able to see data in localStorage of browser.
     

    Read localStorage

     
    You can retrieve data from localStorage using getItem() function. I prefer iterating to KVP.
     
    Example
    1. (function() {    
    2.    for (var i = 0; i < localStorage.length; i++){    
    3.       console.log(localStorage.getItem(localStorage.key(i)));    
    4.    }    
    5. })(); // self-invoking function will give below output   
      Output
       
      Sumit
      Jolly
       
      http://www.c-sharpcorner.com/members/sumit-jolly
       
      There are many other functions and properties you can explore like removeItem, clear, length.
       

      sessionStorage

       
      It is the same as localStorage with the difference that it is associated with session only. After you close browser window it is gone. I believe if you have more security aspect than go for sessionStorage rather localStorage.
       

      Cookies

       
      For many years, cookies are used to remember user information. So whenever a user visits page his/her information is stored in a cookie. It is also saved as KVP.
       
      A simple cookie can be created like:
      1. document.cookie = "fname=Sumit";    
      2. document.cookie = "lname=Jolly";    
      3. console.log(document.cookie); // fname=Sumit; lname=Jolly   
        You can check it in browser Resources Developer Tools.
         
        Developer Tools
         
        Notice an expiry date is set to Session. The reason we have not defined an expiry date to a cookie, so the default is session. 
         
        You could do via setting an expiry date along with.
        1. document.cookie = "fname=Sumit; expires=Mon, 15 Aug 2016 12:00:00 UTC";   
        setting
         
        Here are the differences between the three storage types we discussed:
         
        localStorage sessionStorage Cookies
        Not added Not added Added to every HTTP request
        No expiry date Expire with session Has both features i.e., session and you can define expiry date
        Limit of 5MB Limit of 5MB Cookies give you a limit of 4096 bytes
         

        Summary

         
        Now the world is going towards fat client and thin server. With browsers becoming more capable of faster processing of data and power with various resources, think of the client before the server for good performance of your web application.


        Similar Articles