localStorage에 JavaScript 객체 저장 및 검색

DDD
풀어 주다: 2024-10-09 06:21:29
원래의
504명이 탐색했습니다.

작사: Nelson Michael✏️

편집자 주: 이 기사는 JSON.stringify를 사용하여 JavaScript 개체를 직렬화하는 기술과 같이 localStorage에 개체를 저장하는 방법에 대한 심층적인 탐색을 제공하기 위해 Rahul Chhodde가 2024년 8월 7일에 마지막으로 업데이트했습니다. 그리고 localStorage에서 여러 객체를 작업하고 저장해야 하는 상황이 있습니다.

Web Storage API는 클라이언트 브라우저에 키-값 쌍으로 데이터를 안전하게 저장하고 액세스할 수 있는 JavaScript 기반 메커니즘을 제공합니다. 이는 사용자 기본 설정, 애플리케이션 상태, 경우에 따라 API 응답과 같이 민감하지 않은 데이터를 저장하는 데 유용합니다.

웹 저장소 API의 두 가지 메커니즘인 localStorage와 sessionStorage를 통해 개발자는 데이터를 지속적이고 일시적으로 저장할 수 있습니다. 이렇게 저장된 데이터는 나중에 쉽게 검색하여 사용자의 편의를 위해 활용할 수 있습니다.

이 기사에서는 JavaScript 개체를 JSON 문자열로 문자열화하고 구문 분석하여 localStorage에 저장한 다음 프로세스를 반대로 수행하여 데이터를 검색하는 방법을 알아봅니다. 또한 localStorage, sessionStorage 및 HTTP 쿠키 간의 주요 차이점을 간략하게 설명하고 다른 두 쿠키에 비해 localStorage를 사용할 때의 장점과 단점을 강조하겠습니다.

로컬스토리지란 무엇인가요?

localStorage 개체는 개발자가 브라우저 창을 닫은 후에도 지속되는 데이터를 클라이언트 브라우저에 저장할 수 있게 해주는 웹 저장소의 두 가지 메커니즘 중 하나입니다. 이렇게 저장된 데이터는 사용하기 쉬운 API 방법을 사용하여 특정 도메인 전체에서 액세스할 수 있으며 그 중 일부는 아래에 나와 있습니다.

localStorage.setItem("myDataKey", "My data");
localStorage.getItem("myDataKey"); // "My data"
localStorage.removeItem("myDataKey");
로그인 후 복사

도메인의 localStorage 개체에 저장된 데이터는 동일한 출처의 페이지에서만 액세스하거나 수정할 수 있습니다. 이 경우에는 프로토콜, 도메인 및 포트를 총칭합니다. 브라우저의 개발자 콘솔에서 다음 방법을 사용하여 이 동작을 확인할 수 있습니다.

W3Schools에 따르면 localStorage 개체는 만료 날짜 없이 데이터를 저장합니다. 사용자가 페이지를 떠나거나 브라우저 창을 닫아도 데이터는 삭제되지 않습니다. 향후 세션에서 사용할 수 있습니다. 이러한 데이터 보유 능력을 소프트웨어 및 웹 개발에서는 데이터 지속성이라고 합니다.

sessionStorage와 localStorage 사용

두 번째 웹 저장소 메커니즘인 sessionStorage는 localStorage와 거의 동일하지만 두 가지 면에서 다릅니다. 즉, 지정된(또는 현재) 탭에 대한 데이터를 일시적으로 저장하고 제한된 기간 동안만 그렇게 합니다.

sessionStorage 개체는 해당 탭이 열려 있는 한 활성 상태를 유지하고 페이지 다시 로드 및 복원을 통해 데이터를 유지합니다. 웹페이지가 브라우저 탭에 로드되면 sessionStorage가 사용되는 경우 새 페이지 세션을 생성하고 해당 탭에 할당합니다. 해당 페이지 세션은 해당 특정 탭에서 액세스되는 특정 원본에 대해서만 유효합니다.

참고: 웹 스토리지 종류에 따라 저장되는 데이터는 해당 페이지의 프로토콜별로 다릅니다. 이는 HTTP를 통해 액세스되는 사이트에 저장된 데이터가 HTTPS를 통해 액세스되는 동일한 사이트에 저장된 데이터와 다른 sessionStorage 개체에 저장된다는 의미입니다.

sessionStorage와 localStorage의 주요 차이점

localStorage와 sessionStorage는 비슷하게 작동하지만, 주요 차이점은 localStorage에 저장된 데이터가 지속적이고 동일한 출처의 탭 간에 공유되며 브라우저의 저장 공간을 지우거나 JavaScript를 사용하여 localStorage를 지우지 않는 한 해당 특정 출처에 대해 영원히 지속된다는 것입니다. 수동으로.

Chrome DevTools를 사용하면 localStorage 및 sessionStorage 개체 모두의 데이터를 보고 방금 다룬 차이점을 관찰할 수 있습니다. 다음은 DevTools의 Application 탭에서 두 개체를 찾는 방법을 보여주는 스크린샷입니다. Storing and retrieving JavaScript objects in localStorage

사용자 기본 설정, 애플리케이션 상태, API 응답 및 대규모 데이터 청크와 같은 정보를 저장하고 재사용하여 인지된 성능을 촉진하기 위해 sessionStorage 대신 localStorage를 선택합니다. 사용자 경험을 개인화하고 업데이트하기 위해 이 정보가 가끔 지속되어야 하기 때문입니다. .

참고: 마지막 비공개 탭을 닫으면 비공개 탭이나 시크릿 모드에서 열린 사이트의 localStorage 개체에 저장된 데이터가 지워지는데, 이는 비공개 탐색 세션이기 때문에 의미가 있습니다.

웹 저장소와 HTTP 쿠키 비교

HTTP 쿠키는 각 HTTP 요청 중에 클라이언트와 서버 간에 교환되는 작은 데이터 비트를 저장하는 일반적인 메커니즘입니다.

클라이언트에 연결되면 서버는 특정 정보 비트를 생성하여 쿠키 파일에 저장한 후 클라이언트의 브라우저로 보냅니다. 이 정보에는 각 사용자와 해당 컴퓨터의 고유 ID가 표시되어 연결이 설정될 때마다 서버가 사용자를 식별하는 데 도움이 됩니다.

쿠키는 사용자 경험을 개인화하는 데 도움이 되는 인증 및 세션 데이터, CSRF 토큰, 추적 데이터, 작은 사이트별 사용자 기본 설정과 같은 정보를 전달합니다. 그러나 이는 개인 정보 보호에 대한 악몽이 될 수 있습니다. 이에 대해서는 다음 부분에서 논의하겠습니다.

쿠키를 사용하는 이유와 시기는 무엇입니까?

쿠키는 클라이언트 측에 더 많은 양의 데이터를 저장하는 데 권장되는 솔루션이 아닙니다. 이는 세션 관리에 더 적합하며 이를 위해 가장 널리 지원되는 솔루션 중 하나입니다.

애플리케이션이 클라이언트 측 데이터 저장소로만 액세스하고 취약성에 노출되어 있는 localStorage 또는 sessionStorage를 사용하는 것과 달리 각 요청마다 쿠키는 브라우저의 HTTP 헤더를 통해 서버로 전송됩니다.

세션 보안을 위해 Secure 및 HttpOnly로 표시된 쿠키는 세션 하이재킹 가능성을 최소화하고 세션 중에 사용자 브라우저에 대한 XSS(교차 사이트 스크립팅) 및 CSRF(교차 측 요청 위조) 공격을 제한할 수 있습니다.

쿠키를 사용하지 말아야 할 경우

HTTP 쿠키는 오랜 표준이었으며 앱을 100% 쿠키 없이 유지하는 것이 항상 가능한 것은 아닙니다. 그러나 피해야 할 몇 가지 경우가 있습니다.

  • 쿠키는 서버에 대한 모든 요청과 함께 전송되어야 하므로 쿠키가 작게 유지되고 4KB 이상의 데이터를 저장할 수 없습니다. 이로 인해 대규모 사용자 기본 설정 데이터, 애플리케이션 상태, 사용자 작성 문서 등과 같은 큰 값을 캐싱하는 데 적합하지 않습니다.
  • 제3자 쿠키는 귀하가 방문한 사이트에서 쿠키를 생성하거나 소유하지 않기 때문에 심각한 개인정보 보호 문제를 야기합니다. 이러한 쿠키는 일반적으로 사용자 데이터 추적과 연결되어 의심을 불러일으키며, 많은 브라우저에서는 사용자 개인 정보 보호를 위해 쿠키를 제한할 준비를 하고 있습니다

이러한 점 때문에 민감하지 않은 데이터 더미를 localStorage에 저장하게 됩니다. 이러한 상황에서는 JavaScript 객체와 같은 복잡한 데이터를 로컬에 저장해야 하는 경우가 많으며 약간 다른 접근 방식이 필요합니다.

localStorage에 JavaScript 객체를 저장하는 방법

최신 웹 앱에서는 인지된 성능 이점을 위해 오프라인 액세스를 제공하거나, 애플리케이션 상태를 복원하거나, API 응답을 캐시하기 위해 JavaScript 개체를 로컬에 저장해야 하는 경우가 많습니다.

웹 저장소에 일단 저장되면 동일한 출처에서 실행되는 모든 JavaScript 코드에 액세스할 수 있으므로 이러한 데이터에는 민감한 정보가 포함되어서는 안 됩니다.

다양한 사용 사례에 대한 방법과 속성을 탐색하여 localStorage 작업 방법에 대한 기본적인 이해부터 시작하겠습니다.

  • setItem(): 두 개의 인수인 키와 값을 사용하여 웹 저장소 개체에 데이터를 추가합니다. localStorage.setItem("key", "value")
  • getItem(): 전달된 키 이름의 값을 반환합니다: localStorage.getItem("key")
  • **removeItem()**: 해당 값과 함께 전달된 키를 제거합니다: localStorage.removeItem("key")
  • clear(): 연결된 저장소의 모든 키-값 쌍을 지우므로 주의해서 사용해야 합니다. localStorage.clear()
  • **key()**: 저장소의 지정된 인덱스에 있는 키를 반환합니다: localStorage.key(0)
  • length: 연결된 저장소(localStorage.length)에 저장된 키-값 쌍의 총 개수를 반환합니다.

MDN의 웹 저장소 API 문서에서 이러한 방법에 대해 자세히 알아볼 수 있습니다.

아래 예에서는 이러한 Web Storage API 방법 중 일부를 사용하여 달성한 데이터 지속성을 보여줍니다. 현재 개수 버튼을 클릭하고 CodePen을 다시 실행한 후 localStorage:

를 사용하여 지속되는 개수 데이터를 확인하세요.

CodePen에서 Rahul(@_rahul)이 실제로 사용하는 Pen localStorage를 확인하세요.

위 데모에서는 개수나 지우기 버튼을 클릭할 때마다 여러 localStorage 항목이 생성되거나 읽혀지거나 수정되고 해당 값의 변경 사항이 프런트엔드에 반영됩니다.

JavaScript 객체 직렬화

웹 스토리지에 JavaScript 객체 데이터를 저장하는 것은 문자열 값만 저장할 수 있기 때문에 약간 까다롭습니다. JavaScript 개체를 먼저 문자열로 변환하지 않고 저장하려고 하면 아래 이미지와 같이 [object Object] 응답을 받게 됩니다.
Storing and retrieving JavaScript objects in localStorage [객체 객체]는 데이터 저장 시 값을 읽은 적이 없어 데이터 손실이 발생하는 객체 인스턴스를 문자열로 표현한 것입니다.

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 학습자의 빠른 성장을 도와주세요!