목록에서 글 A, B, C를 Ctrl을 누른 채 연달아 클릭했더니 탭 세 개가 전부 C로 열렸다. 가끔은 A만 나오고 나머지 두 탭은 텅 비었다.
당시 프로젝트는 화면 간 값 전달(파라미터 전달, 뒤로가기 시 검색조건 복원, window.open 팝업 값 전달)에 document.cookie를 쓰고 있었다. 쿠키는 같은 브라우저의 모든 탭이 공유한다. 탭마다 다른 값을 넘기려면 key도 탭마다 달라야 한다. 화면 카테고리마다 고정 key 하나를 쓰던 구조를, 쿠키마다 고유 key를 만들고 URL로 넘기는 방식으로 바꿨다.
탭 세 개가 key 하나를 덮어쓰고 있었다
기존에는 목록에서 상세로 갈 때 고정 key에 파라미터를 쓰고, 상세 탭이 그 key를 읽은 뒤 지웠다. 한 번 클릭할 땐 괜찮지만 연달아 세 번 누르면 바로 꼬인다.
sequenceDiagram
participant L as 목록 탭
participant K as 쿠키 (공통 key)
participant A as 상세 탭 A
participant B as 상세 탭 B
L->>K: A 파라미터 쓰기
L->>K: B 파라미터로 덮어쓰기
L->>K: C 파라미터로 덮어쓰기
A->>K: 읽기 (C 파라미터가 나온다)
B->>K: 읽기 (C 파라미터가 나온다)탭 A가 읽기 전에 목록 탭이 C 값으로 덮어쓴 것이다. 빈 화면이 나온 건 먼저 뜬 탭이 값을 읽고 쿠키를 지워 버렸기 때문이다. document.cookie가 비동기라서가 아니라 여러 탭이 같은 key를 써서 생긴 문제다.
왜 쿠키를 그대로 썼나
localStorage는 브라우저에 영구 저장돼 흐름에 따라 지워지지 않고 남을 수 있어 제외. 모든 경우를 막으려면 공수가 큼.sessionStorage는 같은 탭 안에서만 쓸 수 있어 목록 탭에서 쓴 값을 새 상세 탭에서 읽을 수 없으므로 제외.이미 많은 화면이
document.cookie기반이라 js-cookie 같은 라이브러리 대신 공통 함수만 고치기로 함. (레거시 화면을 다 뜯어고칠 순 없었다.)
key를 매번 새로 만들고 URL로 넘긴다
| 구분 | 기존 | 변경 후 |
|---|---|---|
| 쿠키 key | 화면 카테고리별 고정 key | 쿠키마다 새로 만든 랜덤 key |
| key 전달 | 고정값이라 필요 없음 | URL QueryString의 dataKey |
| 쿠키 누적 | 고정 key라 누적 없음 | 생성할 때 총 크기를 보고, 기준을 넘으면 가장 오래된 쿠키 삭제 |
먼저 common.js의 쿠키 생성 함수다.
// 고유 key name 쿠키 생성 함수
// 여러 Tab 동시 오픈시 데이터 조회 에러 대응 > 탭끼리 같은 key를 덮어쓰던 현상
function setRareCookie(cookieValue, expireDate, uri) {
checkAndDeleteCookie(); // 총 크기 체크. 기준치 이상인 경우 가장 오래된 쿠키 삭제하는 함수
let cookieName = randomNum(); // 쿠키의 고유 key name 생성
changeBrowserLocation(cookieName); // key name을 URL에 설정
document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expireDate + ";path=" + uri;
return cookieName;
}
function randomNum(){
let randomNum = String(Math.floor(Math.random() * 10000));
let currDateTime = String(new Date().getTime()).substring(3);
return currDateTime + randomNum;
}
// 고유 key name을 URL에 설정
function changeBrowserLocation(dataKey){
let params = new URLSearchParams(location.search);
params.set('dataKey', dataKey);
let queryString = params.toString();
let url = location.pathname + '?' + queryString;
window.history.replaceState({}, document.title, url);
}
randomNum()은 밀리초 단위 현재 시각(13자리)에서 앞 세 자리를 뗀 10자리 뒤에 0~9999 난수를 붙인다. 앞 10자리가 시각이라 나중에 오래된 쿠키를 고를 때 쓴다. changeBrowserLocation()은 history.replaceState로 페이지 이동 없이 현재 URL의 dataKey만 바꾼다. 뒤로가기로 목록에 돌아와도 key가 살아남는 이유다.
조회와 삭제는 URL의 dataKey로 처리한다.
// URL에 있는 dataKey를 Key Name으로 갖는 쿠키 조회
function getRareCookie() {
let cookieName = getDataKey();
let cookie = document.cookie;
if (cookie.length > 0 && !isEmpty(cookieName)) {
let startIndex = cookie.indexOf(cookieName);
if (startIndex != -1) {
startIndex += cookieName.length;
let endIndex = cookie.indexOf(";", startIndex);
if (endIndex == -1) endIndex = cookie.length;
return unescape(cookie.substring(startIndex + 1, endIndex));
} else {
return '';
}
} else {
return '';
}
}
// 쿠키 삭제
function deleteRareCookie(uri) {
let expireDate = new Date();
expireDate.setDate(expireDate.getDate() - 1);
document.cookie = getDataKey() + "= " + ";expires=" + expireDate.toGMTString() + ";path=" + uri;
}
// URL의 QueryString 중 dataKey 유무 확인
function getDataKey(){
let dataKey = new URL(location.href).searchParams.get('dataKey') || '';
return dataKey;
}
// 화면 이동시 URL에 cookie key name 전달
function getDataKeyUrl(delimiter){
let dataKey = getDataKey();
return dataKey && `${delimiter}dataKey=${dataKey}`;
}
다만 getRareCookie()는 indexOf로 부분 문자열을 찾아서 다른 쿠키에 같은 숫자가 들어 있으면 오동작할 여지가 있다. split('; ')로 쪼개 정확히 비교하는 편이 안전하다. escape/unescape, toGMTString도 deprecated API라 새로 짠다면 encodeURIComponent/decodeURIComponent, toUTCString을 쓰는 게 맞다.
화면을 옮길 때마다 쿠키가 쌓이므로 생성할 때마다 총 크기를 확인해 오래된 것부터 지운다.
// 쿠키의 총 크기 반환 함수
function getCookieSize() {
let totalSize = 0;
let cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].trim();
totalSize += cookie.length * 2; // 쿠키의 길이 2배(유니코드 문자 고려)
}
return totalSize;
}
// 총 크기를 체크하여 기준치 이상인 경우 가장 오래된 쿠키 삭제
function checkAndDeleteCookie() {
let maxSize = 8500;
while (getCookieSize() > maxSize) {
let cookies = document.cookie.split('; ');
let oldestCookie = 0;
let firstOfAll = true;
let deleteTargetCookieName = 0;
for (let i = 0; i < cookies.length; i++) {
let keyName = cookies[i].substring(0, cookies[i].indexOf('='));
if(!isNumericString(keyName)) continue;
let keyName_dateTime = parseInt(keyName.substring(0,10));
if(firstOfAll) {
oldestCookie = keyName_dateTime;
deleteTargetCookieName = keyName;
firstOfAll = false;
continue;
}
if(oldestCookie > keyName_dateTime){
oldestCookie = keyName_dateTime;
deleteTargetCookieName = keyName;
}
}
if(firstOfAll) break; // 삭제할 쿠키 없는 경우 break
document.cookie = deleteTargetCookieName + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
}
}
function isNumericString(str) {
let pattern = /^\d+$/;
return pattern.test(str);
}
숫자로만 된 key만 지워서 다른 쿠키는 건드리지 않고, 지울 게 없으면 break로 무한 루프를 막는다. (path=/ 쿠키가 쌓이면 요청 헤더도 커지니 정리 로직은 필수다.)
화면에서는 목록 초기화 때 쿠키를 읽어 검색조건을 복원하고 지우며, 상세로 갈 때 새 쿠키를 굽고 key를 URL에 붙인다.
// 리스트페이지.js: 저장된 쿠키를 조회하고, 있으면 화면에 데이터 세팅
화면시작시실행되는초기화함수 : function(){
this.searchCondition = getRareCookie();
if(this.searchCondition != '') {
...
(화면 inputbox에 setting 변수 초기화)
...
deleteRareCookie("/");
}
}
...
// 상세페이지로 이동
화면이동함수 : function(){
...
let dataKey = setRareCookie({다음화면에 전달할 JSON 데이터}, expireDate, "/");
window.location.href = "{상세페이지URL}?dataKey=" + dataKey;
}
상세에서 뒤로 갈 때는 URL의 key를 목록 URL에 그대로 붙여 넘긴다.
// 상세페이지.js: 뒤로가기 시 파라미터 설정
뒤로가기함수 : function() {
window.location.href = "{목록페이지URL}" + getDataKeyUrl("?");
}