English 中文(简体)
HTML5 - Web Storage
  • 时间:2024-12-22

HTML5 - Web Storage


Previous Page Next Page  

HTML5 introduces two mechanisms, similar to HTTP session cookies, for storing structured data on the cpent side and to overcome following drawbacks.

    Cookies are included with every HTTP request, thereby slowing down your web apppcation by transmitting the same data.

    Cookies are included with every HTTP request, thereby sending data unencrypted over the internet.

    Cookies are pmited to about 4 KB of data. Not enough to store required data.

The two storages are session storage and local storage and they would be used to handle different situations.

The latest versions of pretty much every browser supports HTML5 Storage including Internet Explorer.

Session Storage

The Session Storage is designed for scenarios where the user is carrying out a single transaction, but could be carrying out multiple transactions in different windows at the same time.

Example

For example, if a user buying plane tickets in two different windows, using the same site. If the site used cookies to keep track of which ticket the user was buying, then as the user cpcked from page to page in both windows, the ticket currently being purchased would "leak" from one window to the other, potentially causing the user to buy two tickets for the same fpght without really noticing.

HTML5 introduces the sessionStorage attribute which would be used by the sites to add data to the session storage, and it will be accessible to any page from the same site opened in that window, i.e., session and as soon as you close the window, the session would be lost.

Following is the code which would set a session variable and access that variable −

<!DOCTYPE HTML>

<html>
   <body>
      <script type = "text/javascript">
         
         if( sessionStorage.hits ) {
            sessionStorage.hits = Number(sessionStorage.hits) +1;
         } else {
            sessionStorage.hits = 1;
         }
         document.write("Total Hits :" + sessionStorage.hits );
      </script>
	
      <p>Refresh the page to increase number of hits.</p>
      <p>Close the window and open it again and check the result.</p>

   </body>
</html>

This will produce the following result −