”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 在 localStorage 中存储和检索 JavaScript 对象

在 localStorage 中存储和检索 JavaScript 对象

发布于2024-11-09
浏览:129

Written by Nelson Michael✏️

Editor’s note: This article was last updated by Rahul Chhodde on 7 August 2024 to offer a deeper exploration of storing objects in localStorage, such as techniques to serialize JavaScript objects using JSON.stringify, and situations where working with and storing multiple objects in localStorage is necessary.

The Web Storage API provides JavaScript-based mechanisms to securely store and access data as key-value pairs in the client's browser. This is useful for storing non-sensitive data such as user preferences, application states, and even API responses in some cases.

The two mechanisms of the Web Storage API, localStorage and sessionStorage, allow developers to store data persistently and temporarily. This stored data can be easily retrieved later and utilized to facilitate the user.

In this article, we'll learn how to stringify and parse JavaScript objects into JSON strings to save them in localStorage, and then reverse the process to retrieve the data. We'll also briefly cover the key differences between localStorage, sessionStorage, and HTTP cookies, highlighting the benefits and drawbacks of using localStorage over the other two.

What is localStorage?

The localStorage object is one of the two mechanisms of Web Storage that allow developers to store data on the client’s browser that persists even after the browser window is closed. This stored data can be accessed throughout a particular domain using easy-to-use API methods, some of which are shown below:

localStorage.setItem("myDataKey", "My data");
localStorage.getItem("myDataKey"); // "My data"
localStorage.removeItem("myDataKey");

Note that the data stored in the localStorage object from a domain can only be accessed or modified by pages of the same origin, which — in this case — stands for protocol, domain, and port collectively. You can verify this behavior using these methods in your browser’s developer console.

According to W3Schools, the localStorage object stores the data with no expiration date. The data will not be deleted even when the user leaves the page or closes the browser window; it will be available for future sessions. This ability to hold the data is known as data persistence in software and web development.

Using sessionStorage vs. localStorage

The second Web Storage mechanism, sessionStorage, is nearly identical to localStorage but differs in two ways: it temporarily stores data for the specified (or current) tab and does so for only a limited period.

The sessionStorage object stays active as long as the corresponding tab is open and persists data through page reloads and restorations. When a webpage is loaded into a browser tab, sessionStorage, if used, creates a new page session and assigns it to that tab. That page session is only valid for that particular origin accessed in that specific tab.

Note: Data stored in each kind of Web Storage is distinct for each protocol of a given page. This means that data stored on a site accessed via HTTP is stored on a different sessionStorage object than data stored on the same site accessed via HTTPS.

Key differences between sessionStorage and localStorage

localStorage and sessionStorage work similarly, but the main difference is that data stored in localStorage is persistent, shared between tabs of the same origin, and lasts forever for that specific origin unless the browser's storage is cleared or we clear localStorage using JavaScript or manually.

Using Chrome DevTools, you can view the data in both localStorage and sessionStorage objects and observe the distinctions we just covered. Here’s a screenshot depicting locating both objects in the Application tab of DevTools: Storing and retrieving JavaScript objects in localStorage

To store and reuse information like user preferences, application states, API response, and larger chunks of data to facilitate perceived performance, we choose localStorage over sessionStorage, because this info should persist to be used occasionally to personalize and update the user experience.

Note: When the last private tab is closed, data stored in the localStorage object of a site opened in a private tab or incognito mode is cleared, which makes sense because it’s a private browsing session.

Web Storage vs. HTTP cookies

HTTP cookies are a conventional mechanism for storing small bits of data exchanged between the client and the server during each HTTP request.

Once connected to a client, the server generates certain bits of information, saves them in a cookie file, and sends them to the client’s browser. This information is labeled with a unique ID for each user and their computer, which helps the server identify the user whenever a connection is established.

Cookies carry information such as auth and session data, CSRF tokens, tracking data, and tiny, site-specific user preferences to help personalize a user's experience. However, they can be a privacy nightmare. We'll discuss this in the following segment.

Why and when to use cookies?

Cookies are not the recommended solution for storing larger volumes of data on the client side. They are better suited for session management and are one of the most widely supported solutions for doing so.

With each request, cookies are sent to the server in the HTTP headers from the browser, as opposed to using localStorage or sessionStorage, which are only accessed by the application as client-side data storage and open to vulnerabilities.

For session security, cookies marked as Secure and HttpOnly can minimize the chances of session hijacking, limiting XSS (cross-site scripting) and CSRF (cross-side request forgery) attacks on the user's browser during the session.

When not to use cookies

HTTP cookies have been a long-standing standard, and keeping your apps 100% cookie-free isn’t always possible. However, there are a few cases where you might want to avoid them:

  • Cookies are supposed to be transmitted with every request made to the server, which is why they are kept tiny and can’t hold data more than 4KB. This makes them unfit for caching big values like huge user preference data, application states, user-authored documents, etc.
  • Third-party cookies raise a serious privacy concern, as the site you’ve visited doesn’t create or own them. Such cookies are usually linked to tracking user data, which puts them under suspicion, and many browsers are preparing to restrict them to safeguard user privacy

These points leave us to store our heaps of non-sensitive data in localStorage. Such situations often demand saving complex data like JavaScript objects locally, which requires a slightly different approach.

How to store a JavaScript object in localStorage

Modern web apps often demand saving JavaScript objects locally to provide offline access, restore application state, or cache an API response for perceived performance benefits.

Note that such data shouldn’t carry sensitive information, as once stored in Web Storage, it becomes accessible to any JavaScript code running on the same origin.

Let's start by gaining a basic understanding of how to work with localStorage by exploring its methods and properties for various use cases:

  • setItem(): Adds data to a Web Storage object using its two arguments, a key, and a value: localStorage.setItem("key", "value")
  • getItem(): Returns the value of the key name that’s passed to it: localStorage.getItem("key")
  • **removeItem()**: Removes a key that’s passed to it with its corresponding value: localStorage.removeItem("key")
  • clear(): Clears all the key-value pairs in the associated storage and should be used with caution: localStorage.clear()
  • **key()**: Returns the key at the specified index in the storage: localStorage.key(0)
  • length: Returns the total number of key-value pairs stored in the associated storage: localStorage.length

You can learn more about these methods on MDN’s Web Storage API docs.

The example below demonstrates data persistence accomplished using some of these Web Storage API methods. Click the Current count button, rerun the CodePen, and see the count data persisting using localStorage:

See the Pen localStorage in action by Rahul (@_rahul) on CodePen.

In the demo above, whenever you click the count or the clear button, multiple localStorage items are created, read, or modified and the changes to the corresponding values are reflected in the frontend.

JavaScript object serialization

Storing JavaScript object data in Web Storage is a bit tricky, as it allows you to store only string values. If we try to store a JavaScript object without first converting it to a string, we will get an [object Object] response, as shown in the image below:
Storing and retrieving JavaScript objects in localStorage [object Object] is a string representation of an object instance whose value was never read at the time of storing the data, which will result in data loss.

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 records console logs, page load times, stack traces, slow network requests/responses with headers bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier!

Try it for free.

版本声明 本文转载于:https://dev.to/logrocket/storing-and-retrieving-javascript-objects-in-localstorage-157j?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 在 Go 中使用 WebSocket 进行实时通信
    在 Go 中使用 WebSocket 进行实时通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    编程 发布于2024-11-09
  • 修复 D3.js GeoJSON 绘图问题:如何纠正缠绕顺序?
    修复 D3.js GeoJSON 绘图问题:如何纠正缠绕顺序?
    D3.js 错误绘制 GeoJSON:缠绕顺序问题当尝试使用 geoJSON 数据可视化俄罗斯地区时,程序员遇到了一个问题其中 D3.js 绘制单个黑色矩形而不是所需的地图轮廓。这种差异是由于 geoJSON 文件中坐标的缠绕顺序问题引起的。了解缠绕顺序GeoJSON 坐标可以按顺时针或逆时针顺序排...
    编程 发布于2024-11-09
  • 多重继承的问题
    多重继承的问题
    Java不支持类的多重继承,标准方法不规避此限制,因为类可以维护状态(使用实例变量),但接口不能。 默认方法提供了行为多重继承的有限形式,允许一个类通过默认方法从多个接口继承行为。 当一个类实现的两个接口具有相同的默认方法时,可能会发生冲突,例如两个接口 Alpha 和 Beta 都使用了 res...
    编程 发布于2024-11-09
  • 如何避免 getImageData() 中的“画布已被跨域数据污染”错误?
    如何避免 getImageData() 中的“画布已被跨域数据污染”错误?
    如何避免 getImageData() 中出现“画布已被跨源数据污染”错误使用 getImageData( 时) 方法从画布检索像素数据,您可能会遇到错误“画布已被跨源数据污染”。当您尝试访问受从其他域加载的数据影响的画布上的像素数据时,会出现此错误。要了解此错误的原因,请考虑大多数浏览器中实现的安...
    编程 发布于2024-11-09
  • ## Promise.all:Node.js 中是并行执行还是顺序执行?
    ## Promise.all:Node.js 中是并行执行还是顺序执行?
    Promise.all:Node.js 中并行执行还是顺序执行?问题: Promise.all(iterable) 是否顺序处理 Promise 或并行?答案: Promise.all 不执行 Promise;相反,它只是同时等待多个承诺。 Promise 的计算和结果由调用 Promise.all...
    编程 发布于2024-11-09
  • 如何克服 Splinter/Selenium 中的 ElementClickInterceptedException:被其他拦截时单击元素的指南
    如何克服 Splinter/Selenium 中的 ElementClickInterceptedException:被其他拦截时单击元素的指南
    被其他人拦截时单击元素:在 Splinter/Selenium 中处理 ElementClickInterceptedException抓取网页时,单击某些元素可能会具有挑战性,因为模糊元素的存在。在 Selenium 中,当尝试单击被另一个元素遮挡的元素时,会引发 ElementClickInte...
    编程 发布于2024-11-09
  • Java Sound 可以播放 MP3 文件吗?
    Java Sound 可以播放 MP3 文件吗?
    Java Sound 默认不支持 MP3。对于特定 JRE 中支持的类型,请检查 AudioSystem.getAudioFileTypes()。有一种方法可以添加 MP3 支持。将基于 JMF 的 mp3plugin.jar 添加到项目的运行时类路径中。虽然 javax.sound.sampled...
    编程 发布于2024-11-09
  • HTML 创新
    HTML 创新
    HTML5 的创新方向错误。在某种程度上,我是一个有连续性的思考者,并尊重任何进步都是好的。然而,更进一步,语义标签的决定是糟糕的。 这是正确的!我对那件事采取了政治态度! ⭐ 语义元素一定是由非 HTML 开发人员想到的。书面经验没有价值,真正的 100% 对于 HTML5 语义元素的真实非营销术...
    编程 发布于2024-11-09
  • Redux 工具包:React Thunk 和 React Saga。向 Vishal Tiwari 学习。
    Redux 工具包:React Thunk 和 React Saga。向 Vishal Tiwari 学习。
    React Thunk 和 React Saga 是用于处理 React 应用程序中副作用的中间件库,特别是用于管理 API 调用等异步操作。两者通常与 Redux 一起使用,但用途和方法略有不同。 React Thunk 1. 概述: React ...
    编程 发布于2024-11-09
  • 如何使用并发在 Go 中高效地读写 CSV 文件?
    如何使用并发在 Go 中高效地读写 CSV 文件?
    Go 中高效的 CSV 读写Go 中高效读写 CSV 文件的任务涉及优化 I/O 操作。考虑以下代码片段,该代码片段读取 CSV 文件,对数据执行计算,并将结果写入新的 CSV 文件:package main import ( "encoding/csv" "f...
    编程 发布于2024-11-09
  • 以下是一些标题选项,请记住问题格式:

简单直接:

* 如何用JavaScript动态调整输入字段宽度?
* 创建响应式输入字段:JavaScript So
    以下是一些标题选项,请记住问题格式: 简单直接: * 如何用JavaScript动态调整输入字段宽度? * 创建响应式输入字段:JavaScript So
    动态调整输入字段的宽度以适应其输入动态调整输入字段的宽度以匹配其内容长度可以增强用户体验防止布局混乱。虽然设置固定宽度可能会导致多余的空间或截断文本,但动态方法可确保输入字段具有视觉吸引力和功能性。不幸的是,使用 CSS 的 min-width 属性设置最小宽度不适用于输入字段。然而,现代浏览器提供...
    编程 发布于2024-11-09
  • 如何使用 JavaScript 从 iFrame 重定向父窗口?
    如何使用 JavaScript 从 iFrame 重定向父窗口?
    从 iFrame 重定向父窗口如果父窗口中嵌入了 iFrame,则可能需要重定向父窗口窗口的位置更改为新的 URL。为了实现这一点,JavaScript 提供了一个简单的解决方案。使用 JavaScript 重定向父窗口在 iFrame 的 JavaScript 代码中,您可以使用以下方法: 重定向...
    编程 发布于2024-11-09
  • 如何使用 Curl 模拟 Web 浏览器的 GET 请求?
    如何使用 Curl 模拟 Web 浏览器的 GET 请求?
    使用 Curl 模拟 Web 浏览器的 GET 请求尝试使用curl 检索网页时,您可能会遇到似乎源于以下原因的错误无法识别或未实现的请求标头。这是因为curl本身并不模拟Web浏览器的GET请求标头。要正确模拟Web浏览器,请按照下列步骤操作:配置用户代理:使用CURLOPT_USERAGENT为...
    编程 发布于2024-11-09
  • 通过“从参数中提取信息”项目释放您的 Python 能力
    通过“从参数中提取信息”项目释放您的 Python 能力
    您准备好将您的 Python 技能提升到新的水平了吗? LabEx 提供的“从参数中提取信息”项目就是您的最佳选择。这个引人入胜的项目将指导您完成从给定文本中提取数字、计算平均值并将结果格式化为小数点后两位的过程。潜入并释放你作为 Python 程序员的真正潜力! 踏上激动人心的旅程...
    编程 发布于2024-11-09
  • HTML 表单中的默认提交按钮行为是什么?
    HTML 表单中的默认提交按钮行为是什么?
    确定 HTML 表单中的默认提交按钮在未单击特定提交按钮的情况下提交 HTML 表单时,例如按 输入或在 JavaScript 中使用 HTMLFormElement.submit(),浏览器需要确定多个提交按钮(如果有)中的哪一个应被视为按下的按钮。此确定对于触发 onclick 事件处理程序和发...
    编程 发布于2024-11-09

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3