History API

It manages the URL and back stack without fetching a new document.

···
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` adds an entry to the current document’s session history. Back navigation fires `popstate`, letting an app render the matching view.

The demo stacks route chips and moves backward. The History API does not replace page content for you; rendering and URL handling must be implemented together.

When to use

Use it to keep URLs and back navigation aligned in client-side routing.

Open as page ↗