History API

페이지를 다시 받지 않고도 URL과 뒤로가기 기록을 관리합니다.

···
html
<div class="v"><header>HISTORY STACK <span id="url">/home</span></header><div class="stage history"><div class="cards"><div id="h0">/home</div><div id="h1">/items</div><div id="h2">/items/7</div></div><div class="current">view: <b id="view">Home</b></div></div><div class="muted">push → push → back → back</div></div>
css
.v{width:min(94vw,760px);height:min(88vh,320px);padding:clamp(9px,2.4vmin,18px);border:1px solid var(--line);border-radius:12px;background:var(--surface);font:500 clamp(12px,2.4vmin,16px)/1.3 var(--font-sans,system-ui,sans-serif);display:flex;flex-direction:column;gap:clamp(5px,1.4vmin,10px);overflow:hidden}.v header{display:flex;align-items:center;justify-content:space-between;gap:8px;color:var(--accent);font-weight:700}.v header span{color:var(--muted);font-weight:500}.v .stage{flex:1;min-height:0;position:relative}.v .muted{color:var(--muted)}.v .active{background:color-mix(in srgb,var(--accent) 18%,var(--surface));border-color:var(--accent)!important;color:var(--fg)}.v button{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--line);border-radius:7px;padding:5px 8px;cursor:pointer}.history{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:13px}.cards{display:flex;gap:6px;align-items:end}.cards div{padding:8px 5px;border:1px solid var(--line);border-radius:7px;background:var(--bg);color:var(--muted)}.cards div.on{border-color:var(--accent);color:var(--fg);box-shadow:0 5px 12px #0002}.current b{color:var(--accent)}
js
let step=0;const order=[0,1,2,1],names=["Home","Items","Detail"],paths=["/home","/items","/items/7"];function tick(){const i=order[step];for(let j=0;j<3;j++)document.getElementById("h"+j).classList.toggle("on",i===j);document.getElementById("url").textContent=paths[i];document.getElementById("view").textContent=names[i];step=(step+1)%order.length}tick();setInterval(tick,850)

`pushState`는 현재 문서의 세션 기록에 새 항목을 넣습니다. 뒤로가기로 항목이 바뀌면 `popstate`가 발생하며 앱은 그 상태에 맞는 화면을 그릴 수 있습니다.

데모는 경로 칩을 쌓고 뒤로 가며 현재 위치를 강조합니다. History API 자체가 콘텐츠를 바꿔주지는 않으므로 화면 갱신과 URL 처리를 함께 구현해야 합니다.

언제 쓰나

클라이언트 라우팅에서 URL과 뒤로가기 동작을 일치시킬 때 사용합니다.

페이지로 열기 ↗