HTML5 API - LocalStorage, SessionStorage



기존 쿠키 방식과 더불어 HTML5는 로컬에 메모리 데이터를 담는 localStorge 방식과 브라우저 메모리를 활용하는 sessionStorage 방식을 지원합니다.


먼저 localStorage 방식은 용량이 제한(보통 4KB)적인 쿠키 방식에 비해 문서나 메일과 같은 덩치 큰 데이터를 수용할 수 있는 방식이며, 객체({}) 타입의 메모리 할당과 오프라인 참조까지 지원하는 구조입니다.


이 방식의 데이터 생명 주기는 모든 브라우저 창 종료 시에도 유지되며, 같은 도메인에서 실행되는 모든 브라우저 창과 모든 탭을 통해 데이터가 공유됩니다.



두 번째로 sessionStorage 방식은 데이터 생명 주기를 제외한 대부분의 기능들은 localStorage 방식과 동일합니다.


이 방식의 데이터 생명 주기는 데이터가 저장된 브라우저 창 또는 탭에서만 해당 값이 유지됩니다. 즉, localStorage 방식과 달리 모든 브라우저 창과 탭에서 공유되지 않습니다.





1. 브라우저 지원현황:



브라우저 지원현황:

http://caniuse.com/#feat=namevalue-storage






아래는 두 가지 Storage 방식을 모듈화 한 API 코드입니다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Storage</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.     var Storage = (function (win, doc) {
  11.  
  12.         return function (type, onStorage) {
  13.  
  14.             function init() {
  15.  
  16.                 this.type = type || 'session';
  17.                 this.storage = win[this.type === 'local' ? 'localStorage' : 'sessionStorage'];
  18.                 this.length = this.storage.length;
  19.  
  20.                 // events
  21.                 this.onStorage = onStorage || function () { ; };
  22.  
  23.                 //add evnets
  24.                 appendEvent.call(this);
  25.  
  26.                 return this;
  27.             };
  28.  
  29.             init.prototype =
  30.             {
  31.                 set: set,
  32.                 get: get,
  33.                 remove: remove,
  34.                 removeAll: removeAll
  35.             };
  36.  
  37.             return new init;
  38.         };
  39.  
  40.         function appendEvent() {
  41.             var that = this;
  42.  
  43.             // storage 이벤트는 다른 document 기준에서 동일키 값 변경 시 발생된다.
  44.             // (자기 document 안에서는 발생이 되지않는다. 즉, 탭을 하나 열고 테스트한다.)
  45.             bind(window, 'storage', function (e) {
  46.                 that.onStorage.apply(that, [e, that.type, e.url, e.key, e.oldValue, e.newValue]);
  47.             });
  48.         };
  49.  
  50.         // 스토리지 key value 생성
  51.         function set(key, value) {
  52.  
  53.             key = key || '';
  54.             // JSON 객체담기
  55.             value = value && value.constructor === Object ? JSON.stringify(value) : value;
  56.  
  57.             this.storage.setItem(key, value);
  58.             this.length = this.storage.length;
  59.  
  60.             return this;
  61.         };
  62.  
  63.         // 스토리지 key value 가져오기
  64.         function get(key) {
  65.            
  66.             var item = this.storage.getItem(key);
  67.             try {
  68.                 // JSON 객체 가져오기
  69.                 return JSON.parse(item).constructor === Object && JSON.parse(item);
  70.             }
  71.             catch (e) {
  72.                 return item;
  73.             }
  74.         };
  75.  
  76.         // 스토리지 삭제
  77.         function remove(key) {
  78.             this.storage.removeItem(key);
  79.  
  80.             this.length = this.storage.length;
  81.             return this;
  82.         };
  83.  
  84.         // 스토리지 전체 삭제
  85.         function removeAll() {
  86.             this.storage.clear();
  87.  
  88.             this.length = this.storage.length;
  89.             return this;
  90.         };
  91.  
  92.     })(window, document);
  93.  
  94.    
  95.    
  96.     // 로컬 스토리지 생성
  97.     var local = Storage('local', function (e, type, url, oldValue, newValue) { alert(e); });
  98.    
  99.     // 세션 스토리지 생성
  100.     var session = Storage('session', function (e, type, url, oldValue, newValue) { alert(e); });
  101.  
  102.     function add() {
  103.  
  104.         local.set('key', 'value1');
  105.         session.set('key', 'value1');
  106.     };
  107.  
  108.     function modify() {
  109.    
  110.         local.set('key', 'value2');
  111.         session.set('key', {'value2': 'value2'});
  112.     };
  113.  
  114.     function get(){
  115.  
  116.         alert(local.get('key'));
  117.         alert(session.get('key').value2);
  118.     };
  119.  
  120.     function remove() {
  121.  
  122.         local.remove('key');
  123.         session.remove('key');
  124.     };
  125.  
  126.     function removeAll() {
  127.  
  128.         local.removeAll();
  129.         session.removeAll();
  130.     };
  131.  
  132.  
  133.     function length() {
  134.         alert('local-length:' + local.length + ',' + 'session-length:' + session.length);
  135.     }
  136.  
  137.  
  138.     // 이벤트 할당
  139.     function bind(elem, type, handler, capture) {
  140.         type = typeof type === 'string' && type || '';
  141.         handler = handler || function () { ; };
  142.  
  143.         if (elem.addEventListener) {
  144.             elem.addEventListener(type, handler, capture);
  145.         }
  146.         else if (elem.attachEvent) {
  147.             elem.attachEvent('on' + type, handler);
  148.         }
  149.  
  150.         return elem;
  151.     };
  152.  
  153.  
  154. //]]>
  155. </script>
  156. <input type="button" value="storageAppend" onclick="add()" />
  157. <input type="button" value="storageModify" onclick="modify()" />
  158. <input type="button" value="storageGet" onclick="get()" />
  159. <input type="button" value="storageRemove" onclick="remove()" />
  160. <input type="button" value="storageRemoveAll" onclick="removeAll()" />
  161. <input type="button" value="storageLength" onclick="length()" />
  162. </body>
  163. </html>




실행 결과: