JavaScript - 儲存 API



什麼是 Web 儲存 API?

JavaScript 中的 Web 儲存 API 允許我們將資料儲存在使用者的本地系統或硬碟上。在 JavaScript 中引入儲存 API 之前,Cookie 用於將資料儲存在使用者的瀏覽器中。

Cookie 的主要問題是,每當瀏覽器請求資料時,伺服器都必須傳送它並將其儲存在瀏覽器中。有時,攻擊者也可能發起攻擊並竊取資料。

對於儲存 API,我們可以將使用者資料儲存在瀏覽器中,這些資料僅限於使用者裝置。

JavaScript 包含兩個不同的物件來在本地儲存資料。

  • localStorage

  • sessionStorage

在這裡,我們解釋了本地儲存和會話儲存。

Window localStorage 物件

localStorage 物件允許您以鍵值對格式將資料本地儲存在使用者的瀏覽器中。

您可以在本地儲存中儲存最多 5 MB 的資料。

您儲存在本地儲存中的任何資料都不會過期。但是,您可以使用 removeItem() 方法刪除特定項,或使用 clear() 方法刪除本地儲存中的所有項。

語法

我們可以遵循以下語法來設定和獲取瀏覽器本地儲存中的項。

localStorage.setItem(key, value); // To set key-value pair
localStorage.getItem(key); // To get data using a key

在上述語法中,setItem() 方法將專案設定到本地儲存中,而 getItem() 方法用於使用其鍵從本地儲存中獲取專案。

引數

  • key - 它可以是任何字串。

  • value - 它是以字串格式的值。

示例

在下面的程式碼中,我們將 'fruit' 作為鍵,'Apple' 作為值設定到 setItem() 函式內部的本地儲存中。當用戶單擊按鈕時,我們將呼叫 setItem() 函式。

在 getItem() 函式中,我們從本地儲存中獲取 'fruit' 鍵的值。

使用者可以先單擊“設定專案”按鈕,然後單擊“獲取專案”按鈕以從本地儲存中獲取鍵值對。

<html>
<body>    
   <button onclick = "setItem()"> Set Item </button>
   <button onclick = "getItem()"> Get Item </button>
   <p id = "demo"> </p>
   <script>
      const output = document.getElementById('demo');
      function setItem() {
         localStorage.setItem("fruit", "Apple");
      }
      function getItem() {
         const fruitName = localStorage.getItem("fruit");
         output.innerHTML = "The name of the fruit is: " + fruitName;
      }
   </script>
</body>
</html>

localStorage 不允許您儲存物件、函式等。因此,您可以使用 JSON.stringify() 方法將物件轉換為字串並將其儲存到本地儲存中。

示例:將物件儲存到本地儲存中

在下面的程式碼中,我們建立了 animal 物件。之後,我們使用 JSON.stringify() 方法將其轉換為字串,並將其作為 'animal' 物件的值儲存。

使用者可以單擊“設定專案”按鈕將物件設定到本地儲存中,並單擊“獲取專案”按鈕以從本地儲存中獲取鍵值對。

<html>
<body>    
   <button onclick = "setItem()"> Set Item </button>
   <button onclick = "getItem()"> Get Item </button>
   <p id = "demo"> </p>
   <script>
      const output = document.getElementById('demo');
      function setItem() {
         const animal = {
            name: "Lion",
            color: "Yellow",
            food: "Non-vegetarian",
         }
         localStorage.setItem("animal", JSON.stringify(animal));
      }

      function getItem() {
         const animal = localStorage.getItem("animal");
         output.innerHTML = "The animal object is: " + animal;
      }
   </script>
</body>
</html>

示例:從本地儲存中移除專案

在下面的程式碼中,當網頁載入到瀏覽器中時,我們在本地儲存中設定了鍵值對 'name' 和 'john'。

之後,使用者可以點選獲取專案按鈕從本地儲存中獲取專案。它將顯示您的姓名。

點選移除專案按鈕後,您可以再次點選獲取專案按鈕,它將顯示 null,因為該專案已從本地儲存中刪除。

<html>
<body>
   <button onclick = "getItem()"> Get Item </button>
   <button onclick = "removeItem()"> Remvoe Item </button>
   <p id = "demo"></p>
   <script>
      const output = document.getElementById('demo');
      localStorage.setItem('name', 'John');
      function getItem() {
         output.innerHTML = "The name of the person is: " + 
		 localStorage.getItem('name');
      }
      function removeItem() {
         localStorage.removeItem('name');
         output.innerHTML = 'Name removed from local storage. Now, you can\'t get it.';
      }
   </script>
</body>
</html>

Window sessionStorage 物件

sessionStorage 物件也允許以鍵值對格式在瀏覽器中儲存資料。

它還允許您儲存最多 5 MB 的資料。

儲存在 sessionStorage 中的資料在您關閉瀏覽器選項卡時過期。這是 sessionStorage 和 localStorage 之間的主要區別。您還可以使用 removeItem() 或 clear() 方法在不關閉瀏覽器選項卡的情況下從 sessionStorage 中移除專案。

注意 - 一些瀏覽器(如 Chrome 和 Firefox)會在您關閉後重新開啟瀏覽器選項卡時保留 sessionStorage 資料。如果您關閉瀏覽器視窗,它肯定會刪除 sessionStorage 資料。

語法

請按照以下語法使用 sessionStorage 物件從 sessionStorage 設定和獲取資料。

sessionStorage.setItem(key, value); // To set key-value pair
sessionStorage.getItem(key); // To get data using a key

setItem() 和 getItem() 方法與 localStorage 物件一起使用時,在 sessionStorage 物件中產生相同的結果。

引數

  • key − 它是一個字串格式的鍵。

  • value − 它是一個字串格式的鍵值。

示例

在下面的程式碼中,我們使用 'username' 作為鍵,'tutorialspoint' 作為值。我們使用 setItem() 方法將鍵值對儲存在 sessionStorage 物件中。

點選設定專案按鈕後,您可以點選獲取專案按鈕從 sessionStorage 獲取鍵值對。

<html>
<body>
   <button onclick = "setItem()"> Set Item </button>
   <button onclick = "getItem()"> Get Item </button>
   <p id = "output"> </p>
   <script>
      const output = document.getElementById('output');
      function setItem() {
         sessionStorage.setItem("username", "tutorialspoint");
      }
      function getItem() {
         const username = sessionStorage.getItem("username");
         output.innerHTML = "The user name is: " + username;
     }
   </script>
</body>
</html>

您不能直接在本地儲存或會話儲存中儲存檔案或影像資料,但您可以讀取檔案資料,將其轉換為字串,並將其儲存在會話儲存中。

示例

在下面的程式碼中,我們使用了 <input> 元素來獲取使用者的影像輸入。當用戶上傳影像時,它將呼叫 handleImageUpload() 函式。

在 handleImageUpload() 函式中,我們獲取上傳的影像。之後,我們使用 FileReader 讀取影像資料,並將資料設定為 sessionStorage 中的值。

在 getImage() 函式中,我們從 sessionStorage 獲取影像,並將其資料設定為影像 'src' 屬性的值。

使用者可以先上傳影像,然後點選獲取影像按鈕在網頁上顯示影像。

<html>
<body>
   <h2> Upload image of size less than 5 MB </h2>
   <input type = "file" id = "image" accept = "image/*" onchange = "handleImageUpload()">
   <div id = "output"> </div> <br>
   <button onclick = "getImage()"> Get Image </button>
   <script>
      // To handle image upload
      function handleImageUpload() {
         const image = document.getElementById('image');
         const output = document.getElementById('output');
         const file = image.files[0];
         // Read Image file
         if (file) {
            const reader = new FileReader();
            reader.onload = function (event) {
               const data = event.target.result;
               // Storing the image data in sessionStorage
               sessionStorage.setItem('image', data);
            };
            reader.readAsDataURL(file);
         }
      }
      // Function to get image
      function getImage() {
         let data = sessionStorage.getItem("image");
         output.innerHTML = `<img src="${data}" alt="Uploaded Image" width="300">`;
      }
   </script>
</body>
</html>

您還可以像使用 localStorage 一樣,在 sessionStorage 物件中使用 removeItem() 或 clear() 方法。

Cookie 與 localStorage 與 sessionStorage

在這裡,我們給出了 cookie、localStorage 和 sessionStorage 物件之間的區別。

特性 Cookie 本地儲存 會話儲存
儲存限制 每個 cookie 4 KB 5 MB 5 MB
過期 它有一個過期日期。 它永不過期。 在您關閉瀏覽器視窗時,它將被刪除。
可訪問性 它可以在客戶端和伺服器端訪問。 它只能由客戶端訪問。 它只能由客戶端訪問。
安全性 它可能存在漏洞。 它是完全安全的。 它是完全安全的。

儲存物件屬性和方法

屬性/方法 描述
key(n) 獲取本地或會話儲存中第 n 個鍵的名稱。
length 獲取本地或會話儲存中鍵值對的數量。
getItem(key) 獲取與作為引數傳遞的鍵相關的值。
setItem(key, value) 在本地或會話儲存中設定或更新鍵值對。
removeItem(key) 使用其鍵從儲存中移除鍵值對。
clear() 從本地或會話儲存中移除所有鍵值對。
廣告