如何使用 HTML5 localStorage 和 sessionStorage?


HTML5 類似於 HTTP 會話 Cookie,引入了兩種用於儲存客戶端結構化資料的機制,以克服以下缺點。

  • Cookie 隨每次 HTTP 請求一同傳送,從而透過傳輸相同資料減慢了 Web 應用程式的速度。
  • Cookie 限制為大約 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("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 應用程式可能希望出於效能原因將兆位元組的使用者資料(例如整個使用者創作的文件或使用者的郵箱)儲存在客戶端。

你可以嘗試執行以下程式碼來設定本地儲存變數,並在每次訪問該頁面時(即使在你下次開啟瀏覽器視窗時)訪問該變數。

示例

線上演示

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

更新日期: 2020 年 5 月 18 日

437 次瀏覽

開啟您的 職業生涯

完成課程,獲得認證

入門
廣告
© . All rights reserved.