HTML5 Web Storage

소스를 살펴보고 있는 도중에 자바스크립트 부분에서 localStorage와 sessionStorage가 보였다.

이게 뭔가 살펴보니까 HTML5에 있는 Web Storage라는 기술이었다.

모질라 developer 사이트에서는 HTML5 Web Storage를 이렇게 설명하고 있다.

브라우저에서 쿠키를 사용하는 것 보다 훨씬 직관적으로 데이터를 저장할 수 있다고 한다.

실제로 Web Storage(이하 웹 저장소)를 사용하면 JSON 형식으로도 저장할 수 있고 기존의 쿠키와 달리

저장 용량도 더 크고 정보가 서버로 전송되지 않기 때문에 트래픽 비용에서도 이점이 있다고 한다.

HTML 웹 저장소는 클라이언트에 데이터를 저장하기 위해 두 가지 객체를 제공한다.

  • window.localStorage - 만료 날짜가 없는 데이터를 저장한다.
  • window.sessionStorage - 하나의 세션에 대해 데이터를 저장한다. (브라우저 탭을 닫으면 데이터가 사라진다.)

웹 저장소를 사용하기 이전에 localStorage 및 sessionStorage 의 브라우저에 대한 지원 여부를 확인할 필요가 있다.

1
2
3
4
5
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
} else {
// Sorry! No Web Storage support..
}

localStorage Object

localStorage 객체는 쿠키와는 다르게 만료 날짜가 없는 데이터를 저장한다.

이 데이터는 브라우저를 종료하지 않는 한 삭제되지 않는다. 다음 날 또는 다음 주 몇 년 동안 사용할 수 있다.

1
2
3
4
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");

설명

key/value 형식을 가지는 localStorage를 생성한다. (여기에서 key는 “lastname”, value는 “Smith”)

lastname이라는 값을 검색해여 id가 result인 요소에 값을 넣는다.

localStorage에서 “lastname”이라는 키에 해당하는 값을 삭제하고 싶으면 아래와 같이 하면된다.

1
localStorage.removeItem("lastname");

name/value의 쌍은 항상 string 형식으로 저장된다. 저장할 때 항상 string 형식으로 변환해서 저장해야 한다.

아래의 예제는 사용자가 버튼을 클릭 한 횟수를 계산한다. 이 코드에서 문자열 값은 숫자형으로 변환된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
<script>
function clickCounter() {
if(typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount)+1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " + localStorage.clickcount + " time(s).";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
</script>
</head>
<body>
<p><button onclick="clickCounter()" type="button">Click me!</button></p>
<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).</p>
</body>
</html>

sessionStorage Object

sessionStorage 객체는 하나의 session에 대해서만 데이터를 저장한다는 점만 제외하고는 localStorage 객체와 같다.

이 데이터는 사용자가 특정 브라우저 탭을 종료하면 삭제된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
<script>
function clickCounter() {
if(typeof(Storage) !== "undefined") {
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount)+1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " + sessionStorage.clickcount + " time(s) in this session.";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
</script>
</head>
<body>
<p><button onclick="clickCounter()" type="button">Click me!</button></p>
<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter is reset.</p>
</body>
</html>

얼핏 보면 위의 localStorage의 예제와 같아 보이지만 다른 점은 localStorage는 탭을 닫았다가 다시 실행해도 clickcount가 유지되지만 sessionStorage는 브라우저의 탭을 닫았다가 실행하면 데이터가 삭제되고 처음부터 clickcount가 시작된다.

출처

도움 되는 사이트

Share