1. localStorage
localStorage는 웹 브라우저에 데이터를 영구적으로 저장할 수 있는 클라이언트 측 저장소로, 자바스크립트를 통해 키-값 쌍 형태로 문자열 데이터를 저장하고 관리할 수 있습니다. 사용자가 페이지를 새로 고치거나 브라우저를 닫았다가 다시 열어도 데이터가 유지되며, 용량은 약 5MB 정도로 비교적 넉넉합니다. localStorage.setItem()으로 저장하고, getItem()으로 불러오며, removeItem()이나 clear()로 삭제할 수 있습니다. 단, 모든 값은 문자열로 저장되므로 객체나 배열을 저장하려면 JSON.stringify()로 문자열로 변환한 후 저장하고, 다시 꺼낼 때는 JSON.parse()로 원래 형태로 복원해야 합니다. 사용자의 설정, 최근 검색어, 장바구니 상태 등 간단한 정보를 브라우저에 지속적으로 저장할 때 유용하게 사용됩니다.
<input type="text" id="username" placeholder="이름 입력">
<button onclick="saveName()">저장</button>
<p id="welcome"></p>
<script>
function saveName() {
const name = document.getElementById("username").value;
localStorage.setItem("userName", name);
document.getElementById("welcome").innerText = `환영합니다, ${name}님!`;
}
</script>
<button onclick="saveUser()">사용자 저장</button>
<button onclick="loadUser()">사용자 불러오기</button>
<div id="info"></div>
<script>
function saveUser() {
const user = {
name: "김사과",
age: 20,
job: "개발자"
};
localStorage.setItem("user", JSON.stringify(user));
}
function loadUser() {
const data = localStorage.getItem("user");
if (data) {
const user = JSON.parse(data);
document.getElementById("info").innerText =
`이름: ${user.name}, 나이: ${user.age}, 직업: ${user.job}`;
}
}
</script>
<button onclick="toggleTheme()">테마 변경</button>
<p>현재 테마: <span id="themeText"></span></p>
<script>
const body = document.body;
function applyTheme(theme) {
body.style.backgroundColor = theme === "dark" ? "#222" : "#fff";
body.style.color = theme === "dark" ? "#fff" : "#000";
document.getElementById("themeText").innerText = theme;
}
function toggleTheme() {
const current = localStorage.getItem("theme") || "light";
const next = current === "light" ? "dark" : "light";
localStorage.setItem("theme", next);
applyTheme(next);
}
applyTheme(localStorage.getItem("theme") || "light");
</script>
2. sessionStorage
sessionStorage는 자바스크립트에서 브라우저 탭 단위로 데이터를 임시 저장할 수 있는 클라이언트 측 저장소입니다. localStorage와 비슷하게 key-value 형태로 데이터를 저장하며, 모든 값은 문자열로 저장됩니다. 그러나 sessionStorage는 브라우저 탭(또는 창)이 닫히면 데이터가 자동으로 삭제되기 때문에, 로그인 상태처럼 임시로 필요한 정보나 새로고침 중 유지해야 하는 데이터를 저장할 때 유용합니다. 예를 들어, 설문 진행 상황, 입력 중인 폼 데이터, 장바구니 미확정 항목 등 일시적인 데이터 보관에 적합합니다. 데이터를 저장할 때는 sessionStorage.setItem(), 가져올 때는 getItem(), 삭제할 때는 removeItem()이나 clear()를 사용합니다.
<h2>이 탭에서 방문한 횟수: <span id="counter">0</span>회</h2>
<script>
// 현재 값 불러오기 또는 0으로 시작
let count = sessionStorage.getItem("visitCount");
count = count ? Number(count) + 1 : 1;
// 저장
sessionStorage.setItem("visitCount", count);
// 화면에 출력
document.getElementById("counter").innerText = count;
</script>
3. Cookie
Cookie(쿠키)는 웹 브라우저에 작은 데이터를 저장하는 방식으로, 주로 사용자의 로그인 상태 유지, 사이트 방문 기록, 사용자 식별 정보 등을 저장하는 데 사용됩니다. 쿠키는 key-value 형태의 문자열 데이터로 저장되며, 서버와 클라이언트 모두 접근할 수 있다는 특징이 있습니다. 특히 쿠키는 브라우저가 자동으로 서버에 전송하기 때문에 인증 상태 유지에 매우 유용하지만, 용량이 약 4KB로 제한되어 있고, 보안에 민감한 정보는 저장하지 않는 것이 좋습니다. 자바스크립트에서는 document.cookie를 통해 쿠키를 생성, 조회, 삭제할 수 있으며, expires나 max-age 옵션을 설정하면 유효기간을 지정할 수 있습니다. 쿠키는 서버 측 언어(PHP, Node.js 등)에서도 설정하거나 읽을 수 있어, 클라이언트와 서버 간 상태 관리를 위한 중요한 도구로 사용됩니다.
<div id="popup" style="padding:20px; background:#f0f0f0; border:1px solid #ccc; width:300px;">
<p><strong>[공지]</strong> 신규 강의가 업데이트되었습니다!</p>
<label><input type="checkbox" id="hideToday"> 오늘 하루 보지 않기</label>
<button onclick="closePopup()">닫기</button>
</div>
<script>
// 쿠키 설정 함수
function setCookie(name, value, days) {
const d = new Date();
d.setTime(d.getTime() + (days*24*60*60*1000));
const expires = "expires=" + d.toUTCString();
document.cookie = `${name}=${value}; ${expires}; path=/`;
}
// 쿠키 읽기 함수
function getCookie(name) {
const decodedCookie = decodeURIComponent(document.cookie);
const cookies = decodedCookie.split("; ");
for (let cookie of cookies) {
const [key, value] = cookie.split("=");
if (key === name) return value;
}
return null;
}
// 팝업 닫기
function closePopup() {
const checkbox = document.getElementById("hideToday");
if (checkbox.checked) {
setCookie("hidePopup", "true", 1); // 1일 유지
}
document.getElementById("popup").style.display = "none";
}
// 페이지 열릴 때 쿠키 검사
window.onload = function() {
if (getCookie("hidePopup") === "true") {
document.getElementById("popup").style.display = "none";
}
};
</script>
4. IndexedDB
IndexedDB는 웹 브라우저 내에 데이터를 구조화된 방식으로 저장할 수 있는 비동기 기반의 대용량 클라이언트 측 데이터베이스입니다. 일반적인 localStorage나 sessionStorage와 달리, 숫자나 문자열뿐 아니라 객체(Object), 배열, 파일, Blob 등 다양한 형식의 데이터를 저장할 수 있으며, 수백 MB 이상도 저장 가능합니다. 트랜잭션, 인덱스 검색, 버전 관리, 비동기 처리를 지원하여 웹 앱이 오프라인에서도 동작할 수 있도록 만들어주는 중요한 기술입니다. 예를 들어, 오프라인 메모 앱, 대용량 이미지 편집기, 채팅 기록 저장 등에 활용되며, 브라우저가 제공하는 고성능 저장 공간으로 간주됩니다. 다만 사용법이 다소 복잡하여 open(), createObjectStore(), add(), get() 등의 메서드를 체계적으로 이해해야 하며, 실무에서는 idb 같은 라이브러리를 사용해 간편하게 다루기도 합니다.
<h2>📝 내 메모장 (IndexedDB)</h2>
<input type="text" id="noteInput" placeholder="메모 입력">
<button onclick="saveNote()">저장</button>
<ul id="noteList"></ul>
<script>
let db;
// 1. IndexedDB 열기 또는 생성
const request = indexedDB.open("MyNotesDB", 1);
request.onupgradeneeded = function (e) {
db = e.target.result;
// notes라는 object store가 없으면 새로 생성
if (!db.objectStoreNames.contains("notes")) {
db.createObjectStore("notes", { keyPath: "id", autoIncrement: true });
}
};
request.onsuccess = function (e) {
db = e.target.result;
displayNotes();
};
request.onerror = function () {
alert("IndexedDB 열기 실패");
};
// 2. 메모 저장 함수
function saveNote() {
const input = document.getElementById("noteInput");
const text = input.value.trim();
if (!text) return;
const tx = db.transaction("notes", "readwrite");
const store = tx.objectStore("notes");
store.add({ text: text, created: new Date() });
tx.oncomplete = function () {
input.value = "";
displayNotes();
};
}
// 3. 메모 목록 출력 함수
function displayNotes() {
const list = document.getElementById("noteList");
list.innerHTML = "";
const tx = db.transaction("notes", "readonly");
const store = tx.objectStore("notes");
const request = store.openCursor();
request.onsuccess = function (e) {
const cursor = e.target.result;
if (cursor) {
const li = document.createElement("li");
li.textContent = `[${cursor.value.created.toLocaleString()}] ${cursor.value.text}`;
list.appendChild(li);
cursor.continue();
}
};
}
</script>
'프론트엔드 > JavaScript' 카테고리의 다른 글
fetch (0) | 2025.04.18 |
---|---|
Promise 기반 API (1) | 2025.04.17 |
JSON (0) | 2025.04.16 |
정규식 (0) | 2025.04.16 |
이벤트 (0) | 2025.04.16 |