Web Storage API

A short-term storage space that keeps data only while the same tab is open, and automatically clears everything when the tab is closed.

sessionStorage

同じタブを開いている間だけデータを置いておける、短期間の保存場所で、タブを閉じると自動的に消えるメモのような機能。

sessionStorage とは?

sessionStorage(セッションストレージ) は、「同じタブ(同じウィンドウ)を開いているあいだだけ使える、小さなメモ帳」です。

ユーザーが途中でページを更新したり、入力欄を少し移動しても、タブを閉じるまではデータを残しておけます。

「タブを閉じたら自動的に片付く temporary(短い時間の)保存場所」というイメージです。

簡単な使用例

以下は、入力した名前を sessionStorage に保存して、次のページ読み込み時も表示する例です。

JavaScript

function saveName() {
    const name = document.getElementById('nameInput').value;
    sessionStorage.setItem('userName', name);
}

function loadName() {
    const savedName = sessionStorage.getItem('userName');
    if (savedName) {
        document.getElementById('greeting').textContent = `こんにちは、${savedName}さん`;
    }
}

window.onload = loadName;

HTML

<input id="nameInput" type="text" placeholder="名前を入力">
<button onclick="saveName()">保存</button>
<p id="greeting"></p>