首頁 > web前端 > js教程 > 主體

在 localStorage 中儲存和檢索 JavaScript 對象

DDD
發布: 2024-10-09 06:21:29
原創
504 人瀏覽過

尼爾森麥可撰寫✏️

編者註:本文由Rahul Chhodde 於2024 年8 月7 日最新更新,旨在更深入地探討在localStorage 中儲存對象,例如使用JSON.stringify 序列化JavaScript 對象的技術,以及需要在localStorage 中處理和儲存多個物件的情況。

Web Storage API 提供基於 JavaScript 的機制,可以在客戶端瀏覽器中以鍵值對的形式安全地儲存和存取資料。這對於儲存非敏感資料(例如使用者首選項、應用程式狀態,甚至在某些情況下的 API 回應)非常有用。

Web Storage API 的兩種機制 localStorage 和 sessionStorage 允許開發者持久和暫時儲存資料。以後可以輕鬆檢索這些儲存的資料並利用這些資料來方便使用者。

在本文中,我們將學習如何將 JavaScript 物件字串化並解析為 JSON 字串,以將它們保存在 localStorage 中,然後反向執行該過程以檢索資料。我們還將簡要介紹 localStorage、sessionStorage 和 HTTP cookie 之間的主要區別,重點介紹使用 localStorage 相對於其他兩者的優點和缺點。

什麼是本地儲存?

localStorage 物件是 Web Storage 的兩種機制之一,它允許開發人員將資料儲存在客戶端瀏覽器上,即使在瀏覽器視窗關閉後,這些資料仍然存在。可以使用易於使用的 API 方法在整個特定網域中存取這些儲存的數據,其中一些方法如下所示:

localStorage.setItem("myDataKey", "My data");
localStorage.getItem("myDataKey"); // "My data"
localStorage.removeItem("myDataKey");
登入後複製

請注意,網域中儲存在 localStorage 物件中的資料只能由同源頁面存取或修改,在本例中,同源頁面統稱為協定、網域和連接埠。您可以在瀏覽器的開發者控制台中使用這些方法來驗證此行為。

根據 W3Schools 的說法,localStorage 物件儲存沒有過期日期的資料。即使用戶離開頁面或關閉瀏覽器窗口,資料也不會被刪除;它將可供未來的會議使用。這種保存資料的能力在軟體和 Web 開發中稱為資料持久性。

使用 sessionStorage 與 localStorage

第二種 Web 儲存機制 sessionStorage 與 localStorage 幾乎相同,但有兩點不同:它暫時儲存指定(或目前)選項卡的數據,並且僅在有限的時間內儲存資料。

只要對應的選項卡打開,sessionStorage 物件就會保持活動狀態,並透過頁面重新載入和復原來保留資料。當網頁載入到瀏覽器標籤中時,sessionStorage(如果使用)會建立一個新的頁面會話並將其指派給該標籤。此頁面會話僅對在該特定標籤中存取的特定來源有效。

注意:對於給定頁面的每種協議,每種 Web 儲存中儲存的資料都是不同的。這表示透過 HTTP 存取的網站上儲存的資料與透過 HTTPS 存取的相同網站上儲存的資料儲存在不同的 sessionStorage 物件上。

sessionStorage 和 localStorage 之間的主要區別

localStorage 和sessionStorage 的工作原理類似,但主要區別在於localStorage 中儲存的資料是持久的,在同一來源的選項卡之間共享,並且在該特定來源中永遠持續,除非瀏覽器的儲存被清除或者我們使用JavaScript 或清除localStorage手動。

使用 Chrome DevTools,您可以查看 localStorage 和 sessionStorage 物件中的數據,並觀察我們剛剛介紹的差異。以下螢幕截圖描述了在 DevTools 的「應用程式」標籤中找到這兩個物件:Storing and retrieving JavaScript objects in localStorage

為了儲存和重複使用使用者首選項、應用程式狀態、API 回應和更大的資料區塊等資訊以提高感知效能,我們選擇localStorage 而不是sessionStorage,因為這些資訊應該偶爾持續使用,以個性化和更新使用者體驗。

注意:當最後一個私有選項卡關閉時,以私有選項卡或隱身模式開啟的網站的localStorage 物件中儲存的資料將被清除,這是有意義的,因為它是私有瀏覽會話。

Web 儲存與 HTTP cookie

HTTP cookie 是一種傳統機制,用於儲存每個 HTTP 請求期間用戶端和伺服器之間交換的少量資料。

連接到客戶端後,伺服器會產生某些訊息,將它們保存在 cookie 檔案中,並將它們傳送到客戶端的瀏覽器。此資訊標有每個使用者及其電腦的唯一 ID,這有助於伺服器在建立連線時識別使用者。

Cookie 攜帶身份驗證和會話資料、CSRF 令牌、追蹤資料以及微小的、特定於網站的使用者偏好等信息,以幫助個性化使用者體驗。然而,它們可能會成為隱私噩夢。我們將在下面的部分討論這個問題。

為什麼以及何時使用 cookie?

Cookie 不是在客戶端儲存大量資料的建議解決方案。它們更適合會話管理,並且是最廣泛支援的解決方案之一。

對於每個請求,cookie 都會在 HTTP 標頭中從瀏覽器發送到伺服器,而不是使用 localStorage 或 sessionStorage,後者僅由應用程式作為客戶端資料儲存進行訪問,並且存在漏洞。

為了會話安全,標記為Secure和HttpOnly的cookie可以最大限度地減少會話劫持的機會,限制會話期間對使用者瀏覽器的XSS(跨站腳本)和CSRF(跨端請求偽造)攻擊。

何時不使用 cookie

HTTP cookie 一直是長期存在的標準,讓您的應用程式 100% 不含 cookie 並不總是可能的。但是,在某些情況下您可能希望避免它們:

  • Cookie 應該隨著向伺服器發出的每個請求一起傳輸,這就是為什麼它們保持很小並且不能容納超過 4KB 的資料。這使得它們不適合快取大值,例如巨大的使用者偏好資料、應用程式狀態、使用者編寫的文件等。
  • 第三方 cookie 引發了嚴重的隱私問題,因為您造訪的網站並未建立或擁有它們。此類 cookie 通常與追蹤使用者資料相關聯,這使它們受到懷疑,許多瀏覽器正準備限制它們以保護使用者隱私

這些點讓我們將大量非敏感資料儲存在 localStorage 中。這種情況通常需要在本地保存 JavaScript 物件等複雜數據,這需要稍微不同的方法。

如何在 localStorage 儲存 JavaScript 對象

現代 Web 應用程式通常需要在本地保存 JavaScript 對象,以提供離線存取、恢復應用程式狀態或快取 API 回應以獲得可感知的效能優勢。

請注意,此類資料不應攜帶敏感訊息,因為一旦儲存在 Web 儲存中,在同一來源上執行的任何 JavaScript 程式碼都可以存取它。

讓我們先透過探索 localStorage 各種用例的方法和屬性來基本了解如何使用 localStorage:

  • setItem():使用兩個參數(一個鍵和一個值)將資料新增至 Web Storage 物件: localStorage.setItem("key", "value")
  • getItem():傳回傳遞給它的鍵名稱的值:localStorage.getItem("key")
  • **removeItem()**:刪除傳遞給它的鍵及其對應的值:localStorage.removeItem("key")
  • clear():清除關聯儲存中的所有鍵值對,應謹慎使用:localStorage.clear()
  • **key()**:傳回儲存中指定索引處的鍵:localStorage.key(0)
  • length:傳回關聯儲存中儲存的鍵值對總數:localStorage.length

您可以在 MDN 的 Web Storage API 文件中了解有關這些方法的更多資訊。

下面的範例示範了使用其中一些 Web Storage API 方法完成的資料持久性。點選 目前計數 按鈕,重新執行 CodePen,並查看使用 localStorage 儲存的計數資料:

查看 Rahul (@_rahul) 在 CodePen 上使用 Pen localStorage 的實際情況。

在上面的示範中,每當您按一下計數或清除按鈕時,都會建立、讀取或修改多個 localStorage 項,並且對應值的變更會反映在前端中。

JavaScript 物件序列化

在 Web Storage 中儲存 JavaScript 物件資料有點棘手,因為它允許您僅儲存字串值。如果我們嘗試儲存 JavaScript 物件而不先將其轉換為字串,我們將得到 [object Object] 回應,如下圖所示:
Storing and retrieving JavaScript objects in localStorage [object Object] 是物件實例的字串表示形式,其值在儲存資料時從未被讀取,這將導致資料遺失。

The correct way to store object data to localStorage is to first convert it to a string. Then, we can move on to the storage procedure.

This object-to-string conversion of object data is known as serialization, and turning this converted string back to object data is called deserialization. Let’s briefly discuss two important JSON methods that are responsible for object data serialization and deserialization:

  • JSON.stringify: Converts any object value into a string JSON (serialization)
  • JSON.parse: Turns a JSON string into its corresponding object or value (deserialization)

Now, utilizing the setItem method with JSON stringify, we can easily convert a JavaScript object to a JSON string and push it to the localStorage object. Here’s a quick example to demonstrate this:

const userObj = {
  name: "John Doe",
  age: 32,
  gender: "Male",
  profession: "Optician" 
};

localStorage.setItem("userObj", JSON.stringify(myObject));
登入後複製

Now, if we try to retrieve the object data without deserializing it, we will receive a JSON string instead of an object, which makes sense, as it is what we stored to localStorage.

We need to deserialize this JSON string data using the JSON parse method to turn it back into a JavaScript object:

let newObject = localStorage.getItem("myObject");
console.log(JSON.parse(newObject));
登入後複製

Here, we retrieved our previously set JavaScript object using the getItem method on the localStorage object and saved it into a variable. Next, we parsed that string into a JavaScript object and finally logged it to the console:
Storing and retrieving JavaScript objects in localStorage

More examples of storing objects in localStorage

  • Storing Date objects: Constructing an object using the current timestamp using the Date object and a random value, and saving it to or clearing it from the localStorage using button inputs
  • Persisting remote data: Fetching remote data from a dummy API and storing it in localStorage; the network fetch in this example is only triggered when no associated data in localStorage is found

Storing multiple objects in localStorage

Let’s say we have a bunch of similar objects, and we want to group all of them and store them as one JSON string in the localStorage. We can turn them into an object array and then serialize them as shown below:

const todos = [todo1, todo2, todo3];
localStorage.setItem("todos", JSON.stringify(todos));
登入後複製

If you have bigger chunks of data to work with, you might want to store each of them with separate keys, but accessing all of them quickly can be done using this namespace approach:

// Storing
localStorage.setItem('todos:1', JSON.stringify(todo1));
localStorage.setItem('todos:2', JSON.stringify(todo2));

// Retrieving
const keys = Object.keys(localStorage).filter(key => key.startsWith('todos:'));
const todos = keys.map(key => JSON.parse(localStorage.getItem(key)));
登入後複製

Limitations of storing objects to localStorage

localStorage is one of the mechanisms of the Web Storage API. The API provides 5-10MB of storage per origin, and the exact storage may vary depending on the browser. Respecting this size limit, you should avoid storing more than 3-4MB of data per origin in Web Storage objects.

Keep in mind that Web Storage API operations are synchronous and block the main thread, therefore performing heavy operations using it may block other resources from loading in the browser.

Types of data that can be stored as a JSON string

Primitive data types like numbers, Booleans, and strings are JSON-safe, while values like functions, undefined, symbols, and Date objects are not JSON-safe. If no JSON-safe values are found during conversion, they are either excluded from an object or changed to null in an array.

Note: Some of these such values can be made JSON-safe, for example, we used the toISOstring method with the Date object in this example to make it JSON-safe before pushing it to Web Storage.

Conclusion

In this article, we learned a useful technique for storing multiple bits of information in a single localStorage key and using the JSON stringify and parse methods. We also covered some working demonstrations that apply this approach to different tasks, as well as storing and retrieving multiple JavaScript objects from localStorage.

In summary, we should be mindful of the data we store locally, and take advantage of the localStorage object to store JavaScript objects by first converting them to JSON strings with the JSON.stringify method and then turning them back to objects with the JSON.parse method.


LogRocket: Debug JavaScript errors more easily by understanding the context

Debugging code is always a tedious task. But the more you understand your errors, the easier it is to fix them.

LogRocket allows you to understand these errors in new and unique ways. Our frontend monitoring solution tracks user engagement with your JavaScript frontends to give you the ability to see exactly what the user did that led to an error.

Storing and retrieving JavaScript objects in localStorage

LogRocket 記錄控制台日誌、頁面載入時間、堆疊追蹤、帶有標頭正文的慢速網路請求/回應、瀏覽器元資料和自訂日誌。了解 JavaScript 程式碼的影響從未如此簡單!

免費試用。

以上是在 localStorage 中儲存和檢索 JavaScript 對象的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!