HTML5 - Web存储

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

  • 每个HTTP请求都包含Cookie,从而通过传输相同的数据来降低Web应用程序的速度.

  • 每个HTTP请求都包含Cookie,因此,通过互联网发送未加密的数据.

  • Cookie限制为大约4 KB的数据.不足以存储所需的数据.

这两个存储是会话存储本地存储并且它们将用于处理不同的情况.

几乎所有浏览器的最新版本都支持HTML5存储,包括Internet Explorer.

会话存储

会话存储适用于用户执行单个事务但可能在不同窗口中执行多个事务的情况时间.

示例

例如,如果用户在两个不同的窗口购买机票,则使用相同的网站.如果该站点使用cookie来跟踪用户正在购买的票证,那么当用户在两个窗口中从一页到另一页点击时,当前正在购买的票证将从一个窗口"泄漏"到另一个窗口,从而可能导致用户在没有真正注意的情况下购买同一航班的两张票.

HTML5引入了 sessionStorage 属性,网站将使用该属性将数据添加到会话存储,该窗口中打开的同一站点的任何页面都可以访问它,即会话,一旦关闭窗口,会话就会丢失.

以下是设置会话变量并访问该变量的代码 :

<!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>

本地存储

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

同样,cookie不能很好地处理这种情况,因为它们随每个请求一起发送。

示例

HTML5引入了localStorage属性,该属性将用于访问页面的本地存储区域而没有时间限制,并且只要您使用该页面,该本地存储都将可用。

以下是设置本地存储变量并在每次访问此页面时(甚至是下次打开窗口时)访问该变量的代码

<!DOCTYPE HTML>

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

删除网络存储

在本地计算机上存储敏感数据可能很危险,并且可能会留下安全漏洞。

会话终止后,浏览器会立即删除会话存储数据。

要清除本地存储设置,您需要调用localStorage.remove('key'); 其中"键"是您要删除的值的键。 如果要清除所有设置,则需要调用localStorage.clear()方法。

以下是清除完整本地存储的代码

<!DOCTYPE HTML>

<html>
   <body>

      <script type = "text/javascript">
         localStorage.clear();

         // Reset number of hits.
         if( localStorage.hits ) {
            localStorage.hits = Number(localStorage.hits) +1;
         } else {
            localStorage.hits = 1;
         }
         document.write("Total Hits :" + localStorage.hits );
			
      </script>
		
      <p>Refreshing the page would not to increase hit counter.</p>
      <p>Close the window and open it again and check the result.</p>

   </body>
</html>



本文链接:https://www.f2er.com/3188911.html