javascript

Cookie Store API

hjcode 2024. 2. 22. 13:35
https://developer.mozilla.org/en-US/docs/Web/API/CookieStore
 

CookieStore - Web APIs | MDN

The CookieStore interface of the Cookie Store API provides methods for getting and setting cookies asynchronously from either a page or a service worker.

developer.mozilla.org

 

쿠키 가져오기

쿠키를 사용하려면 아래처럼 전체 문자열을 뒤져보거나 라이브러리를 사용했어야 했다.

 

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
https://www.quirksmode.org/js/cookies.html

 

 

하지만 이제 cookieStore를 사용하고 해당 작업을 쉽게 할 수 있다.
get 메소드는 Promise를 반환하기 때문에 await을 통해 결과를 받을 수 있다.

 

try {
  const getCookie = await cookieStore.get('cookie1')

  if (getCookie) {
    console.log(`getCookie:`, getCookie)
  } else {
    console.log('not found')
  }
} catch (err) {
  console.error(err)
}

 

쿠키 쓰기

document.cookie = "test1=Hello; SameSite=None; Secure";

function createCookie(name, value, days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
  } else var expires = "";
  document.cookie = name + "=" + value + expires + "; path=/";
}

 

쿠키를 쓰려면 위처럼 써야한다.
작업 후 쿠키 생성이 성공되었는지 확인하려면 위에 readCookie 로 해당 쿠키를 찾는다.

cookieStore를 사용하면 set 메소드만 사용하면 된다.
마찬가지로 Promise를 반환하기 때문에 await을 통해 결과를 받을 수 있다.

 

const day = 24 * 60 * 60 * 1000;
try {
  await cookieStore.set({
    name: "test11",
    value: "test-value",
    expires: Date.now() + day,
  })
} catch (err) {
  console.error(err)
}

 

쿠키 삭제

cookieStrore 에서는 delete 메소드만 사용하면 쿠키를 제거할 수 있다.

 

try {
  await cookieStore.delete('test11')
} catch (err) {
  console.error(err)
}

 

쿠키 변경 이벤트

CookieChangeEvent를 사용하면 쿠키의 변경을 감지할 수 있다.

 

cookieStore.addEventListener("change", (event) => {
  console.log(event);
});

const one_day = 24 * 60 * 60 * 1000;
cookieStore.set({
  name: "cookie1",
  value: "cookie1-value",
  expires: Date.now() + one_day,
});

cookieStore.delete("cookie1")

 

 

changed와 deleted로 변경된 내용을 배열로 받아볼 수 있다.

반응형