目录

HTML5 - Web存储( Web Storage)

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

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

  • 每个HTTP请求都包含Cookie,从而通过Internet发送未加密的数据。

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

这两个存储是session storagelocal storage ,它们将用于处理不同的情况。

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

会话存储

Session Storage设计用于用户执行单个事务但可以同时在不同窗口中执行多个事务的场景。

例子 (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 clicked 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 flight without really noticing.

HTML5引入了sessionStorage属性,站点将使用该属性将数据添加到会话存储中,并且可以访问该窗口中打开的同一站点的任何页面,即session并且只要关闭窗口,会话将丢失。

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

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

这将产生以下结果 -

新页面打开

本地存储

Local Storage设计用于跨越多个窗口的存储,并且持续超出当前会话。 特别是,出于性能原因,Web应用程序可能希望在客户端存储兆字节的用户数据,例如整个用户创作的文档或用户的邮箱。

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

例子 (Example)

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>

这将产生以下结果 -

新页面打开

删除Web存储

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

Session Storage Data终止后, Session Storage Data将立即被浏览器删除。

要清除本地存储设置,您需要调用localStorage.remove('key') ; 其中'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>

这将产生以下结果 -

新页面打开
↑回到顶部↑
WIKI教程 @2018