如何使用HTML5 localStorage和sessionStorage?

HTML5引入了两种机制,类似于HTTP会话cookie,用于在客户端存储结构化数据并克服以下缺点。

  • Cookies包含在每个HTTP请求中,从而通过传输相同的数据来减慢Web应用程序的速度。

  • Cookies被限制为大约4 KB的数据。不足以存储所需数据。

两种存储机制是会话存储和本地存储,它们将用于处理不同的情况。

会话存储

会话存储是针对以下场景设计的:用户正在执行单个事务,但可能同时在不同窗口中执行多个事务。

您可以尝试运行以下命令来设置会话变量并访问该变量

示例


<!DOCTYPE HTML>
<html>
   <body>
      <script type="text/javascript">
         if( sessionStorage.hits ){
            sessionStorage.hits = Number(sessionStorage.hits) +1;
         } else{
            sessionStorage.hits = 1;
         }
         document.write("总命中:" + 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>

本地存储

本地存储专为跨多个窗口且持续时间超出当前会话的存储而设计。特别是,出于性能方面的考虑,Web应用程序可能希望在客户端存储兆字节的用户数据,例如整个用户编写的文档或用户的邮箱。

您可以尝试运行以下代码来设置本地存储变量,并在每次访问此页面时甚至在下次打开窗口时都访问该变量。

示例


<!DOCTYPE HTML>
<html>
   <body>
      <script type="text/javascript">
         if( localStorage.hits ){
            localStorage.hits = Number(localStorage.hits) +1;
         } else{
            localStorage.hits = 1;
         }
         document.write("总命中:" + localStorage.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>