Computer >> 컴퓨터 >  >> 프로그래밍 >> HTML

HTML DOM localStorage 속성 – 브라우저에 데이터 영구 저장하기

HTML DOM의 localStorage 속성은 사용자가 키-값(key-value) 쌍을 웹 브라우저의 로컬 저장소에 직접 저장하여 나중에 참조할 수 있도록 해줍니다. 저장된 데이터는 사용자가 명시적으로 삭제하거나 지우기 전까지는 브라우저를 닫거나 페이지를 새로 고침해도 손실되지 않습니다.

구문(Syntax)

다음은 기본 구문입니다 −

Window.localStorage

localStorage 객체에서 사용할 수 있는 주요 메서드는 다음과 같습니다 −

  • setItem('key', 'value') − 지정한 키에 값을 저장합니다.
  • getItem('key') − 지정한 키에 해당하는 값을 불러옵니다.
  • removeItem('key') − 지정한 키와 그 값을 삭제합니다.

localStorage의 주요 특징

  • 저장된 데이터는 만료 기간이 없으며 세션이 종료되어도 유지됩니다.
  • 데이터는 문자열(string) 형태로만 저장됩니다.
  • 동일 출처(프로토콜, 도메인, 포트가 같은 경우)에서만 접근할 수 있습니다.
  • 브라우저마다 약 5MB 내외의 저장 용량을 제공합니다.

이제 localStorage 속성의 실제 동작 예제를 살펴보겠습니다 −

예제

<!DOCTYPE html>
<html>
<head>
<title>LocalStorage clear()</title>
<style>
   form {
      width:70%;
      margin: 0 auto;
      text-align: center;
   }
   * {
      padding: 2px;
      margin:5px;
   }
   input[type="button"] {
      border-radius: 10px;
   }
   table,th,td {
      border:1px solid black;
      border-collapse: collapse;
      margin: 0 auto;
   }
</style>
</head>
<body>
   <form>
      <fieldset>
         <legend>LocalStorage clear( )</legend>
         <table>
            <tr>
               <th>Key</th>
               <th>Value</th>
            </tr>
            <tr>
               <td>PassKey</td>
               <td>ja12ertplo</td>
            </tr>
         </table>
         <input type="button" value="Store Key" onclick="storeData()">
         <input type="button" value="Delete Key" onclick="clearData()">
         <div id="divDisplay"></div>
      </fieldset>
   </form>
   <script>
      var divDisplay = document.getElementById("divDisplay");
      var extStyle = document.getElementById("extStyle");
      function clearData(){
         localStorage.clear();
         divDisplay.textContent = 'Succesfully Deleted';
      }
      function storeData(){
         localStorage.setItem('PassKey','ja12ertplo');
         divDisplay.textContent = 'Succesfully Stored';
      }
   </script>
</body>
</html>

출력 결과

'Store Key' 버튼을 클릭하면 키-값 쌍이 localStorage에 저장됩니다 −

HTML DOM localStorage 속성 – 브라우저에 데이터 영구 저장하기

'Delete Key' 버튼을 클릭하면 localStorage에 저장된 모든 데이터가 삭제됩니다 −

HTML DOM localStorage 속성 – 브라우저에 데이터 영구 저장하기