HTML5 Local StorageとSession Storageを使いこなしてブラウザでデータを保存しよう
HTML5 Local StorageとSession Storageは、ブラウザ上でデータを保存するためのAPIです。どちらもJavaScriptからアクセスできますが、保存期間とデータの共有範囲が異なります。
Local Storage
- データはブラウザが閉じられるまで永続的に保存されます。
- 同じドメイン内のすべてのページからアクセスできます。
- データ容量は5MB程度です。
Session Storage
- データ容量はLocal Storageと同じです。
使い分け
- ユーザー設定やログイン情報など、永続的に保存したいデータにはLocal Storageを使用します。
- 買い物かごや一時的なメッセージなど、セッション間で保持したいデータにはSession Storageを使用します。
例
- 買い物かごの中身はSession Storageを使用します。
コード例
// Local Storageにデータを設定
localStorage.setItem('username', 'John Doe');
// Local Storageからデータを取得
const username = localStorage.getItem('username');
// Session Storageにデータを設定
sessionStorage.setItem('cart', JSON.stringify([
{
id: 1,
name: '商品1',
price: 1000
},
{
id: 2,
name: '商品2',
price: 2000
}
]));
// Session Storageからデータを取得
const cart = JSON.parse(sessionStorage.getItem('cart'));
注意
- Local StorageとSession Storageは、ブラウザごとに実装が異なる場合があります。
- データの安全性には注意が必要です。
以下のコードは、ユーザー名とパスワードをLocal Storageに保存し、ログイン状態を維持する例です。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Local Storageサンプル</title>
</head>
<body>
<h1>ログイン</h1>
<form onsubmit="login(event)">
<label for="username">ユーザー名:</label>
<input type="text" id="username" name="username">
<label for="password">パスワード:</label>
<input type="password" id="password" name="password">
<button type="submit">ログイン</button>
</form>
<script>
function login(event) {
event.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
// ユーザー名とパスワードをLocal Storageに保存
localStorage.setItem('username', username);
localStorage.setItem('password', password);
// ログイン後の処理
// ...
}
// Local Storageからユーザー名とパスワードを取得
const storedUsername = localStorage.getItem('username');
const storedPassword = localStorage.getItem('password');
// 既にログイン済みの場合は、ログイン後の処理を実行
if (storedUsername && storedPassword) {
// ログイン後の処理
// ...
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Session Storageサンプル</title>
</head>
<body>
<h1>買い物かご</h1>
<ul id="cart-items"></ul>
<script>
// 商品データ
const products = [
{
id: 1,
name: '商品1',
price: 1000
},
{
id: 2,
name: '商品2',
price: 2000
}
];
// 商品を追加
function addCartItem(productId) {
const product = products.find(product => product.id === productId);
// 商品をSession Storageに追加
const cartItems = JSON.parse(sessionStorage.getItem('cart-items')) || [];
cartItems.push(product);
sessionStorage.setItem('cart-items', JSON.stringify(cartItems));
// 買い物かごの更新
updateCartItems();
}
// 買い物かごの表示を更新
function updateCartItems() {
const cartItems = JSON.parse(sessionStorage.getItem('cart-items')) || [];
const cartItemsElement = document.getElementById('cart-items');
cartItemsElement.innerHTML = '';
for (const cartItem of cartItems) {
const cartItemElement = document.createElement('li');
cartItemElement.textContent = `${cartItem.name} (${cartItem.price}円)`;
cartItemsElement.appendChild(cartItemElement);
}
}
// 最初の表示
updateCartItems();
</script>
</body>
</html>
上記はあくまでサンプルコードであり、実際の利用シーンに合わせて改変する必要があります。
主な代替方法
- Cookie
- IndexedDB
- Web SQL Database
- Service Worker
各方法の特徴
- 昔からあるデータ保存方法
- 比較的シンプル
- 容量は4KB程度と小さい
- セキュリティ面で脆弱な場合がある
- 大容量のデータを保存できる
- オブジェクトストアと呼ばれる構造化されたデータ形式で保存できる
- 複雑なデータ構造を保存するのに適している
- SQLを使ってデータ操作ができる
- 現在は非推奨
- プッシュ通知やオフラインアクセスなどの機能を提供できる
- データ保存も可能
- 少量のデータを保存する場合はCookie
- 大容量のデータを保存する場合はIndexedDB
- 複雑なデータ構造を保存する場合はIndexedDBまたはWeb SQL Database
- プッシュ通知やオフラインアクセスなどの機能も必要場合はService Worker
- 各方法にはそれぞれメリットとデメリットがあります。
- 使用する前に各方法の特徴をよく理解しておく必要があります。
javascript html local-storage