HTML - Web 儲存



Web 儲存

HTML Web 儲存 是一種用於在客戶端儲存結構化資料的機制,無需將其傳送到伺服器。這兩種儲存機制是 會話儲存本地儲存。兩者都統稱為 HTML5 Web 儲存 API 的一部分。

Web 儲存的必要性

HTML Web 儲存 的引入是為了克服 Cookie 的以下缺點

  • Cookie 包含在每個 HTTP 請求中,從而透過傳輸相同的資料來減慢 Web 應用程式的速度。
  • Cookie 包含在每個 HTTP 請求中,從而透過網際網路傳送未加密的資料。
  • Cookie 的資料限制約為 4 KB。不足以儲存所需資料。

Web 儲存的型別

HTML 提供兩種型別的 Web 儲存

  • 會話儲存
  • 本地儲存

要在 Web 應用程式中使用這兩種 Web 儲存(會話儲存本地儲存),您可以分別透過 window.sessionStoragewindow.localStorage 屬性訪問它們。

會話儲存

會話儲存 是臨時的,並在頁面會話結束時清除,會話結束髮生在瀏覽器選項卡或視窗關閉時。儲存在會話儲存中的資料特定於每個選項卡或視窗。

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 應用程式手動將其刪除。特別是,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>

刪除 Web 儲存

在本地計算機上儲存敏感資料可能很危險,並且可能會留下安全漏洞。會話儲存資料將在會話終止後立即由瀏覽器刪除。

但是,要清除本地儲存設定,我們需要呼叫 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>
廣告