JS

자바스크립트 활용 예시(Cookie, 내부 저장소)

goshek 2024. 8. 14. 11:18
/*
    쿠키
    : 웹 사이트가 사용자의 브라우저에 저장하는 작은 텍스트 파일

    & 쿠키의 구조
    -이름: 각 쿠키를 식별하는 고유한 이름
    -값: 각 쿠키에 저장하는 정보의 문자열
    -만료날짜: 쿠키의 수명
    -경로 도메인 secure플래그, HttpOnly플래그
   
    & 쿠키의 한계
    - 용량 제한(4KB), 보안에 취약(개인 정보 보호 문제)

    & 쿠키 생성 및
    1. 쿠키 생성
    : document. cookie 속성
    : 웹 브라우저에 쿠키를 생성하고 관리 (쿠키 설정, 읽기, 수정 및 삭제)

    >>document.cookie에 문자열을 할당하면 생성과 수정이 가능
    (필수) 쿠키의 이름, 값
    (선택, 추가 사항) 만료 날짜, 경로, 도메인, 보안

    ? 기본 형식
    document.cookie= "쿠키이름=쿠키값; expiers= 날짜; path=경로;domain= 도멤인; secure"
    ex) 사용자 이름 쿠키 설정
    "username"이라는 쿠키에 "gs"라는 값을 저장
    - 경로값: 해당 웹 페이지에서 쿠키값에 접근할 수 있는 경로를 지정
    >> '/' 빈 슬래시 사용: 어떤 경로에서든지 쿠키값에 접근 가능
*/
document.cookie= "username=gs; path=/";

/*
    - 만료 날짜: expires 속성을 사용
    >> 만료 날짜를 설정하지 않는 경우 세션 쿠키로 자동 설정되어 브라우저가 닫힐 때 자동 삭제
    >> :KST(한국 표준시)시간 단위보다 9시간 느림(한국이 UTC보다 9시간 빠름)
*/
let date= new Date();
// >> Date 객체에 .setTime()속성: 시간 데이터를 설정
// >> Date 객체에 .getTime()속성: 시간 데이터를 가져오기
date.setTime(date.getTime()+ (1*60*60*1000)); //현재 시간에 1시간을 추가
let expires= "expires=" + date.toUTCString(); //시간을 문자열로 변환
// "expires=시간 문자열"
document.cookie="userAge=20;"+ expires+ "; path=/"
//"userAge=50; expires=시간문자열; path=/"

let date2= new Date();
date2.setTime(date2.getTime()+ (24*60*60*1000));
let expires2= "expires= "+date2.toUTCString(); //시간을 문자열로 변환
document.cookie="oneDay=하루"+ date.toUTCString;

 

 

document.cooke="cookie02=안녕;"

/*
    ! 쿠키 값 가져오는 방법
    1) document.cookie에서 반환된 문자열을 분석
    2) 특정 쿠키 이름을 찾아 해당 값을 추출

    ? 쿠키 문자열 분리
    : 웹 문서에 저장된 쿠키로부터 문자열을 세미콜론을 기준으로 분리해서 개별 쿠키를 배열로 반환
*/
function getCookieValue(cookiename){
    let cookies= document.cookie.split(";");
    let length= cookies.length;
    for(let i=0; i<length;i++){
        let cookie= cookies[i]; //배열을 순횐하며 각 쿠키를 변수에 저장
        let parts= cookie.split('='); //쿠키를 이름과 값으로 분리
        let name= parts[0].trim();
        if(name=== cookie.name){
            return parts[1] || ''; // 값이 있으면 반환하고, 해당 이름에 값이 없으면 빈 문자열을 반환
        }
    }
    return '';
}
let username= getCookieValue('username');
console.log(username);
let userAge= getCookieValue('userAge');
console.log(userAge);

function deleteCookie(cookieName){
    document.cookie= cookieName+ "=; expires=Fri, 17 May 2024 00:00:00 GMT; path=/;"
}
deleteCookie('username');
deleteCookie('userAge');
deleteCookie('oneDay');

// 원하는 쿠키이름, 쿠키 값 >> 전체 프로젝트 경로에서 접근 가능한 쿠키 설정
// +) 만료 날짜 1시간 뒤
let date= new Date();
date.setTime(date.getTime()+ (1*60*60*1000)); //현재 시간에 1시간을 추가
let expires= "expires=" + date.toUTCString(); //시간을 문자열로 변환
// "expires=시간 문자열"
document.cookie="cookieName=chocoCookie;"+ expires+ "; path=/";

 

 

/*
    ! 로컬 스토리지
    : 웹 브라우저가 제공하는 저장 공간
    >> 사용자의 컴퓨터에 영구적으로 데이터를 저장 가능

    HTML5 웹 스토리지 사양의 일부 도입으로 쿠키의 한계를 보완한 큰 저장
    용량과 보안을 제공

    ? 1. 로컬 스토리지 데이터 저장
    : localStorage.setItem(key, value)
    >> 웹 브라우저의 저장공간에 데이터 저장(브라우저를 닫아도 데이터가 유지)
*/
;
//localStorage.setItem('key', value);

/*
    # 로컬 스토리지의 데이터 저장
    : 기본적으로 문자열 데이터만 저장
    >> 기본 자료형의 경우 저장 가능
    but, 인식은 문자열
    로컬 스토리지엣 ㅓ객체나 배열과 같은 참조 자료형 데이터를 저장하려면 문자열 형태로 변환
    >> JSON.stringfy()
*/
localStorage.setItem('userAge',50);

let userInfo={
    name: 'Hyuck',
    age: 20
};
localStorage.setItem('userInfo',JSON.stringify(userInfo));

/*
    ? 로컬 스토리지 데이터 불러오기
    localStorage.getItem(key);
    >> 해당 키가 존재하지 않으면 null을 반환
*/
console.log(localStorage.getItem('userInfo'));//{"name":"Hyuck","age":20}
console.log(localStorage.getItem('no'));//null

/*
    참조 자료형(객체, 배열)
*/
let storedData= localStorage.getItem('userInfo');
let userInfoValue= JSON.parse(storedData);
console.log(userInfoValue);
console.log(userInfoValue.name);

/*
    # 로컬 스토리지에서 데이터를 가져오는 경우
    : null을 반환하는 상활을 대비하여 데이터 사용 전 null값 처리를 확인

    ? 로컬 스토리지 데이터 삭제
    : localStorage.removeItem(key);
    : localStorage.clear();
*/
localStorage.removeItem('userAge');
localStorage.removeItem('isStudent');

localStorage.clear();