localStorage での JavaScript オブジェクトの保存と取得

DDD
リリース: 2024-10-09 06:21:29
オリジナル
504 人が閲覧しました

ネルソン・マイケル著✏️

編集者注: この記事は、JSON.stringify を使用して JavaScript オブジェクトをシリアル化する手法など、localStorage にオブジェクトを格納する方法をさらに詳しく説明するために、2024 年 8 月 7 日に Rahul Chhodde によって最後に更新されました。また、複数のオブジェクトを操作して localStorage に保存する必要がある状況も必要です。

Web Storage API は、クライアントのブラウザでデータをキーと値のペアとして安全に保存し、アクセスするための JavaScript ベースのメカニズムを提供します。これは、ユーザー設定、アプリケーションの状態、場合によっては API 応答などの非機密データを保存するのに役立ちます。

Web Storage API の 2 つのメカニズム、localStorage と sessionStorage を使用すると、開発者はデータを永続的かつ一時的に保存できます。この保存されたデータは後で簡単に取得でき、ユーザーの利便性を高めるために利用できます。

この記事では、JavaScript オブジェクトを文字列化して JSON 文字列に解析して localStorage に保存し、その逆のプロセスを行ってデータを取得する方法を学びます。また、localStorage、sessionStorage、HTTP Cookie の主な違いについても簡単に説明し、他の 2 つと比べて localStorage を使用する利点と欠点を強調します。

ローカルストレージとは何ですか?

localStorage オブジェクトは、Web Storage の 2 つのメカニズムのうちの 1 つで、開発者はこれを使用して、ブラウザ ウィンドウが閉じられた後も保持されるデータをクライアントのブラウザに保存できます。この保存されたデータは、使いやすい API メソッドを使用して特定のドメイン全体でアクセスできます。その一部を以下に示します。

localStorage.setItem("myDataKey", "My data");
localStorage.getItem("myDataKey"); // "My data"
localStorage.removeItem("myDataKey");
ログイン後にコピー

ドメインから localStorage オブジェクトに保存されたデータは、同じオリジンのページからのみアクセスまたは変更できることに注意してください。この場合、プロトコル、ドメイン、ポートの総称です。ブラウザの開発者コンソールで次の方法を使用して、この動作を確認できます。

W3Schools によると、localStorage オブジェクトには有効期限なしでデータが保存されます。ユーザーがページから離れたり、ブラウザ ウィンドウを閉じたりした場合でも、データは削除されません。今後のセッションで利用できるようになります。データを保持するこの機能は、ソフトウェアおよび Web 開発ではデータの永続性として知られています。

sessionStorage と localStorage の使用

2 番目の Web ストレージ メカニズムである sessionStorage は、localStorage とほぼ同じですが、2 つの点で異なります。指定された (または現在の) タブのデータを一時的に保存し、限られた期間のみ保存します。

sessionStorage オブジェクトは、対応するタブが開いている限りアクティブなままであり、ページのリロードと復元を通じてデータを保持します。 Web ページがブラウザーのタブに読み込まれると、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 応答、および知覚されるパフォーマンスを向上させるために大きなデータの塊などの情報を保存して再利用するには、sessionStorage ではなく localStorage を選択します。これは、この情報がユーザー エクスペリエンスのパーソナライズと更新のために時々使用されるように永続化する必要があるためです。 。

注: 最後のプライベート タブを閉じると、プライベート タブまたはシークレット モードで開いたサイトの localStorage オブジェクトに保存されているデータがクリアされます。これはプライベート ブラウジング セッションであるため当然のことです。

Web ストレージと HTTP Cookie の比較

HTTP Cookie は、各 HTTP リクエスト中にクライアントとサーバー間で交換される少量のデータを保存するための従来のメカニズムです。

クライアントに接続されると、サーバーは特定の情報を生成し、Cookie ファイルに保存して、クライアントのブラウザに送信します。この情報には、各ユーザーとそのコンピューターに固有の ID が付けられ、接続が確立されるたびにサーバーがユーザーを識別するのに役立ちます。

Cookie には、認証データとセッション データ、CSRF トークン、追跡データ、およびユーザー エクスペリエンスのパーソナライズに役立つサイト固有の小さなユーザー設定などの情報が含まれます。ただし、プライバシーにとって悪夢となる可能性があります。これについては次のセグメントで説明します。

Cookie を使用する理由と使用時期?

Cookie は、クライアント側で大量のデータを保存する場合に推奨されるソリューションではありません。これらはセッション管理により適しており、そのための最も広くサポートされているソリューションの 1 つです。

リクエストごとに、クライアント側のデータ ストレージとしてアプリケーションによってのみアクセスされ、脆弱性が存在する localStorage または sessionStorage を使用するのではなく、ブラウザから HTTP ヘッダーで Cookie がサーバーに送信されます。

セッションのセキュリティについては、Secure および HttpOnly としてマークされた Cookie を使用すると、セッション ハイジャックの可能性が最小限に抑えられ、セッション中のユーザーのブラウザに対する XSS (クロスサイト スクリプティング) および CSRF (クロスサイド リクエスト フォージェリ) 攻撃が制限されます。

Cookieを使用しない場合

HTTP Cookie は長年にわたる標準であり、アプリを 100% Cookie なしで維持することは必ずしも可能ではありません。ただし、次のような場合にはそれらを避けたほうがよい場合があります。

  • Cookie はサーバーへのリクエストごとに送信されることになっているため、Cookie は小さく保たれ、4KB を超えるデータを保持できません。そのため、巨大なユーザー設定データ、アプリケーションの状態、ユーザーが作成したドキュメントなどの大きな値をキャッシュするのには適していません。
  • サードパーティ Cookie は、訪問したサイトが作成または所有していないため、プライバシーに関する重大な懸念を引き起こします。このような Cookie は通常、ユーザー データの追跡に関連付けられているため、疑惑の対象となっており、多くのブラウザーがユーザーのプライバシーを保護するためにクッキーを制限する準備を進めています

これらの点により、非機密データのヒープを localStorage に保存する必要があります。このような状況では、JavaScript オブジェクトのような複雑なデータをローカルに保存することが必要になることが多く、これには少し異なるアプローチが必要です。

JavaScript オブジェクトを localStorage に保存する方法

最新の Web アプリでは、オフライン アクセスを提供したり、アプリケーションの状態を復元したり、パフォーマンス上のメリットを得るために API 応答をキャッシュしたりするために、JavaScript オブジェクトをローカルに保存することが必要になることがよくあります。

このようなデータは、Web Storage に保存されると、同じオリジンで実行されているすべての JavaScript コードからアクセスできるようになるため、機密情報を含むべきではないことに注意してください。

まずは、さまざまなユースケースでのメソッドとプロパティを調べて、localStorage の操作方法の基本を理解しましょう。

  • setItem(): 2 つの引数 (キーと値) を使用して 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:

を使用して保持されているカウント データを確認します。

CodePen で Rahul (@_rahul) による Pen localStorage の動作をご覧ください。

上記のデモでは、カウントまたはクリア ボタンをクリックするたびに、複数の localStorage アイテムが作成、読み取り、または変更され、対応する値への変更がフロントエンドに反映されます。

JavaScript オブジェクトのシリアル化

JavaScript オブジェクト データを Web Storage に保存するには、文字列値しか保存できないため、少し注意が必要です。最初に文字列に変換せずに JavaScript オブジェクトを保存しようとすると、以下の画像に示すように、[object Object] 応答が返されます。
[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 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!