Script Valley
JavaScript in the Browser: DOM, Events & APIs
Web APIs: History, URL, Clipboard, and ObserversLesson 6.1

How the History API enables single-page app navigation

history.pushState, history.replaceState, popstate event, window.location, URL state management, SPA routing basics

History API

History API stack

The History API lets you change the browser URL and history stack without a full page reload - the foundation of single-page app (SPA) routing.

// Push a new URL onto the history stack
history.pushState({ page: 'about' }, '', '/about');

// Replace current entry without adding to stack
history.replaceState({ page: 'home' }, '', '/');

// Read current URL parts
console.log(window.location.pathname); // '/about'
console.log(window.location.search);   // '?tab=profile'
console.log(window.location.hash);     // '#section-2'

Handling the Back Button

The popstate event fires when the user navigates with Back or Forward. The state object you passed to pushState is available on the event.

window.addEventListener('popstate', (e) => {
  console.log('Navigated to state:', e.state);
  renderPage(e.state?.page || 'home');
});

Minimal SPA Router

function navigate(path, state = {}) {
  history.pushState(state, '', path);
  renderPage(path);
}

document.querySelectorAll('a[data-spa]').forEach(link => {
  link.addEventListener('click', (e) => {
    e.preventDefault();
    navigate(link.getAttribute('href'));
  });
});

Up next

Parsing and building URLs with the URL API

Sign in to track progress